[
  {
    "path": ".github/CODEOWNERS",
    "content": "* @carlosmiei\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.md",
    "content": "---\nname: Bug report\nabout: Create a report to help us improve\ntitle: ''\nlabels: ''\nassignees: ''\n\n---\n\n**Describe the bug**\nA clear and concise description of what the bug is.\n\n**To Reproduce**\nCode snippet to reproduce the behavior:\n\n**Expected behavior**\nA clear and concise description of what you expected to happen.\n\n**Environment (please complete the following information):**\n - Python version: [e.g. 3.5]\n - Virtual Env: [e.g. virtualenv, conda]\n - OS: [e.g. Mac, Ubuntu]\n - python-binance version\n\n**Logs**\nPlease set logging to debug and paste any logs here, or upload `debug.log` file to the issue.\n```python\nimport logging\n# This will log to both console and file\nlogging.basicConfig(level=logging.DEBUG,format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\nhandlers=[\nlogging.FileHandler('debug.log'),\nlogging.StreamHandler()\n]\n)\n```\n\n**Additional context**\nAdd any other context about the problem here.\n"
  },
  {
    "path": ".github/workflows/python-app.yml",
    "content": "# This workflow will install Python dependencies, run tests and lint with a single version of Python\n# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python\n\nname: Python application\n\non:\n  workflow_dispatch:\n  push:\n    branches: [ main, master ]\n  pull_request:\n    branches: [ main, master ]\n\npermissions:\n  contents: read\n\njobs:\n  lint:\n    runs-on: ubuntu-latest\n    timeout-minutes: 5\n    steps:\n    - uses: actions/checkout@v5\n    - name: Set up Python\n      uses: actions/setup-python@v6\n      with:\n        python-version: '3.9'\n    - name: Install Ruff\n      run: pip install ruff\n    - name: Lint code with Ruff\n      run: ruff check --output-format=github --target-version=py39 .\n    - name: Check code formatting with Ruff\n      run: ruff format --check .\n      continue-on-error: true\n\n  test:\n    needs: lint\n    runs-on: ubuntu-22.04\n    timeout-minutes: 40\n    strategy:\n      max-parallel: 2\n      matrix:\n        python-version: ['3.8', '3.9', '3.10', '3.11', '3.12']\n    env:\n      PROXY: \"http://188.245.226.105:8911\"\n      TEST_TESTNET: \"true\"\n      TEST_API_KEY: \"u4L8MG2DbshTfTzkx2Xm7NfsHHigvafxeC29HrExEmah1P8JhxXkoOu6KntLICUc\"\n      TEST_API_SECRET: \"hBZEqhZUUS6YZkk7AIckjJ3iLjrgEFr5CRtFPp5gjzkrHKKC9DAv4OH25PlT6yq5\"\n      TEST_FUTURES_API_KEY: \"227719da8d8499e8d3461587d19f259c0b39c2b462a77c9b748a6119abd74401\"\n      TEST_FUTURES_API_SECRET: \"b14b935f9cfacc5dec829008733c40da0588051f29a44625c34967b45c11d73c\"\n    steps:\n    - uses: actions/checkout@v5\n    - name: Checking env\n      run: |\n        echo \"PROXY: $PROXY\"\n        echo \"Python version: ${{ matrix.python-version }}\"\n    - name: Set up Python ${{ matrix.python-version }}\n      uses: actions/setup-python@v6\n      with:\n        python-version: ${{ matrix.python-version }}\n        cache: 'pip'\n    - name: Install dependencies\n      run: |\n        python -m pip install --upgrade pip\n        pip install pytest pytest-cov pyright tox\n        if [ -f requirements.txt ]; then pip install -r requirements.txt; fi\n        if [ -f test-requirements.txt ]; then pip install -r test-requirements.txt; fi\n    - name: Type check with pyright (Python 3.12 only)\n      if: matrix.python-version == '3.12'\n      run: pyright\n    - name: Test with tox\n      run: tox -e py\n    - name: Coveralls Parallel\n      uses: coverallsapp/github-action@v2\n      with:\n        parallel: true\n  finish:\n    needs: test\n    if: ${{ always() }}\n    runs-on: ubuntu-latest\n    timeout-minutes: 5\n    steps:\n    - name: Coveralls Finished\n      uses: coverallsapp/github-action@v2\n      with:\n        parallel-finished: true\n"
  },
  {
    "path": ".gitignore",
    "content": ".tox\n.cache/v/cache\ndocs/_build\nbinance/__pycache__/\nbuild/\ndist/\npython_binance.egg-info/\n*__pycache__\n*.egg-info/\n.idea/\nvenv*/\n.vscode\n.binance/"
  },
  {
    "path": ".pre-commit-config.yaml",
    "content": "repos:\n-   repo: https://github.com/pre-commit/pre-commit-hooks\n    rev: v4.5.0\n    hooks:\n    -   id: check-yaml\n    -   id: end-of-file-fixer\n    -   id: trailing-whitespace\n\n-   repo: https://github.com/astral-sh/ruff-pre-commit\n    rev: v0.8.1\n    hooks:\n    -   id: ruff\n    -   id: ruff-format\n\n-   repo: https://github.com/RobertCraigie/pyright-python\n    rev: v1.1.389\n    hooks:\n    -   id: pyright\n"
  },
  {
    "path": ".readthedocs.yaml",
    "content": "# Read the Docs configuration file for Sphinx projects\n# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details\n\n# Required\nversion: 2\n\n# Set the OS, Python version and other tools you might need\nbuild:\n  os: ubuntu-22.04\n  tools:\n    python: \"3.12\"\n    # You can also specify other tool versions:\n    # nodejs: \"20\"\n    # rust: \"1.70\"\n    # golang: \"1.20\"\n\n# Build documentation in the \"docs/\" directory with Sphinx\nsphinx:\n  configuration: docs/conf.py\n  # You can configure Sphinx to use a different builder, for instance use the dirhtml builder for simpler URLs\n  # builder: \"dirhtml\"\n  # Fail on all warnings to avoid broken references\n  # fail_on_warning: true\n\n# Optionally build your docs in additional formats such as PDF and ePub\n# formats:\n#   - pdf\n#   - epub\n\n# Optional but recommended, declare the Python requirements required\n# to build your documentation\n# See https://docs.readthedocs.io/en/stable/guides/reproducible-builds.html\npython:\n  install:\n    - requirements: docs/requirements.txt\n    - requirements: requirements.txt\n"
  },
  {
    "path": ".travis.yml",
    "content": "dist: xenial\n\nlanguage: python\n\npython:\n  - \"3.6\"\n  - \"3.7\"\n  - \"3.8\"\n  - \"3.9\"\n\ninstall:\n  - pip install -r test-requirements.txt\n  - pip install -r requirements.txt\n  - pip install tox-travis\n\nscript:\n  - tox\n\nafter_success:\n  - coveralls\n"
  },
  {
    "path": "Endpoints.md",
    "content": "> :warning: **Disclaimer**: \n\n > * Before using the endpoints, please check the [API documentation](https://binance-docs.github.io/apidocs/#change-log) to be informed about the latest changes or possible bugs/problems. \n\n > * Not all parameters are mandatory. Some parameters are only mandatory in specific conditions/types. Check the official documentation the type of each parameter and to know if a parameter is mandatory or optional. \n\n > * This documentation only includes methods in client.py file. Websocket methods haven't (yet) been covered.\n \n### [Spot/Margin/Saving/Mining Endpoints](https://binance-docs.github.io/apidocs/spot/en/)\n- *Wallet Endpoints*\n  - **GET /sapi/v1/system/status** (Fetch system status.)\n    ```python \n    client.get_system_status()\n    ```\n  - **GET /sapi/v1/capital/config/getall (HMAC SHA256)** (Get information of coins (available for deposit and withdraw) for user.)\n    ```python \n    client.get_all_coins_info()\n    ```\n  - **GET /sapi/v1/accountSnapshot (HMAC SHA256)** (Daily Account Snapshot (USER_DATA).)\n    ```python \n    client.get_account_snapshot(type='SPOT')\n    ```\n  - **POST /sapi/v1/account/disableFastWithdrawSwitch (HMAC SHA256)** (Disable Fast Withdraw Switch (USER_DATA).)\n    ```python \n    client.disable_fast_withdraw_switch(type='SPOT')\n    ``` \n  - **POST /sapi/v1/account/enableFastWithdrawSwitch (HMAC SHA256)** (Enable Fast Withdraw Switch (USER_DATA).)\n    ```python \n    client.enable_fast_withdraw_switch(type='SPOT')\n    ```\n  - **POST /sapi/v1/capital/withdraw/apply (HMAC SHA256)** (Withdraw: Submit a withdraw request.)\n    ```python \n    client.withdraw(coin, \n        withdrawOrderId, \n        network, \n        address, \n        addressTag, \n        amount, \n        transactionFeeFlag, \n        name, \n        recvWindow)\n    ```\n  - **GET /sapi/v1/capital/deposit/hisrec (HMAC SHA256)** (Fetch Deposit History(supporting network) (USER_DATA).)\n    ```python \n    client.get_deposit_history(coin, status, startTime, endTime, recvWindow)\n    ```\n  - **GET /sapi/v1/capital/withdraw/history (HMAC SHA256)** (Fetch Withdraw History (supporting network) (USER_DATA).)\n    ```python \n    client.get_withdraw_history(coin, status, startTime, endTime, recvWindow)\n    ```\n  - **GET /sapi/v1/capital/deposit/address (HMAC SHA256)** (Fetch deposit address with network.)\n    ```python \n    client.get_deposit_address(coin, status, recvWindow)\n    ```\n  - **GET /sapi/v1/account/status** (Fetch account status detail.)\n    ```python \n    client.get_account_status(recvWindow)\n    ```\n  - **GET /sapi/account/apiTradingStatus** (Fetch account api trading status detail.)\n    ```python \n    client.get_account_api_trading_status(recvWindow)\n    ```\n  - **GET /sapi/v1/asset/dribblet (HMAC SHA256)** (DustLog: Fetch small amounts of assets exchanged BNB records.)\n    ```python \n    client.get_dust_log(recvWindow)\n    ```\n  - **Post /sapi/v1/asset/dust (HMAC SHA256)** (Dust Transfer: Convert dust assets to BNB.)\n    ```python \n    client.transfer_dust(asset, recvWindow)\n    ```\n  - **Get /sapi/v1/asset/assetDividend (HMAC SHA256)** (Query asset dividend record.)\n    ```python \n    client.get_asset_dividend_history(asset, startTime, endTime, limit, recvWindow)\n    ```\n  - **GET /sapi/v1/asset/assetDetail (HMAC SHA256)** (Fetch details of assets supported on Binance.)\n    ```python \n    client.get_asset_details(recvWindow)\n    ```\n  - **GET /sapi/v1/asset/tradeFee (HMAC SHA256)** (Fetch trade fee, values in percentage.)\n    ```python \n    client.get_trade_fee(symbol, recvWindow)\n    ```\n- *Market Data Endpoints*\n  - **GET /api/v3/ping** (Test connectivity to the Rest API.)\n    ```python \n    client.ping()\n    ```\n  - **GET /api/v3/time** (Test connectivity to the Rest API and get the current server time.)\n    ```python \n    client.get_server_time()\n    ```\n  - **GET /api/v3/exchangeInfo** (Current exchange trading rules and symbol information.)\n    ```python \n    client.get_exchange_info()\n    ```\n  - **GET /api/v3/depth** (Get the Order Book for the market.)\n    ```python \n    client.get_order_book(symbol, limit)\n    ```\n  - **GET /api/v3/trades** (Get recent trades (up to last 500))\n    ```python \n    client.get_recent_trades(symbol, limit)\n    ```\n  - **GET /api/v3/historicalTrades** (Get older market trades.)\n    ```python \n    client.get_historical_trades(symbol, limit, fromId)\n    ``` \n  - **GET /api/v3/aggTrades** (Get compressed, aggregate trades. Trades that fill at the time, from the same order, with the same price will have the quantity aggregated.)\n    ```python \n    client.get_aggregate_trades(symbol, fromId, startTime, endTime, limit)\n    \n    # Wrapper function: Iterate over aggregate trade data from (start_time or last_id) the end of the history so far:\n    client.aggregate_trade_iter(symbol, start_str, last_id)\n    ```\n  - **GET /api/v3/klines** (Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time.)\n    ```python \n    client.get_klines(symbol, interval, startTime, endTime, limit)\n    \n    # Wrapper function: Iterate over klines data from client.get_klines()\n    client.get_historical_klines(symbol, interval, start_str, end_str, limit)\n    ```\n  - **GET /api/v3/avgPrice** (Current average price for a symbol.)\n    ```python \n    client.get_avg_price(symbol)\n    ```\n  - **GET /api/v3/ticker/24hr** (24 hour rolling window price change statistics. **Careful** when accessing this with no symbol.)\n    ```python \n    client.get_ticker(symbol)\n    ```\n  - **GET /api/v3/ticker/price** (Latest price for a symbol or symbols.)\n    ```python \n    client.get_symbol_ticker(symbol)\n    ```\n  - **GET /api/v3/ticker/bookTicker** (Best price/qty on the order book for a symbol or symbols.)\n    ```python \n    client.get_orderbook_ticker(symbol)\n    ```\n- *Spot Account/Trade Endpoints*\n  - **POST /api/v3/order/test (HMAC SHA256)** (Test new order creation and signature/recvWindow long. Creates and validates a new order but does not send it into the matching engine.)\n    ```python \n    client.create_test_order(symbol, \n        side, \n        type, \n        timeInForce, \n        quantity, \n        quoteOrderQty, \n        price, \n        newClientOrderId, \n        stopPrice, \n        icebergQty, \n        newOrderRespType, \n        recvWindow)\n    ```\n  - **POST /api/v3/order (HMAC SHA256)** (Send in a new order.)\n    ```python \n    client.create_order(symbol, \n        side, \n        type, \n        timeInForce, \n        quantity, \n        quoteOrderQty, \n        price, \n        newClientOrderId, \n        stopPrice, \n        icebergQty, \n        newOrderRespType, \n        recvWindow)\n        \n    ## Wrapper functions:\n    # Send in a new limit order. \n    # Default parameters: timeInForce=Client.TIME_IN_FORCE_GTC, type=Client.ORDER_TYPE_LIMIT\n    client.order_limit(symbol, \n        side,\n        quantity, \n        price, \n        newClientOrderId, \n        stopPrice, \n        icebergQty, \n        newOrderRespType, \n        recvWindow)\n    \n    # Send in a new limit buy order. \n    # Default parameters: timeInForce=Client.TIME_IN_FORCE_GTC, type=Client.ORDER_TYPE_LIMIT, side=Client.SIDE_BUY\n    client.order_limit_buy(symbol, \n        quantity, \n        price, \n        newClientOrderId, \n        stopPrice, \n        icebergQty, \n        newOrderRespType, \n        recvWindow) \n    \n    # Send in a new limit sell order. \n    # Default parameters: timeInForce=Client.TIME_IN_FORCE_GTC, type=Client.ORDER_TYPE_LIMIT, side= Client.SIDE_SELL\n    client.order_limit_sell(symbol, \n        quantity, \n        price, \n        newClientOrderId, \n        stopPrice, \n        icebergQty, \n        newOrderRespType, \n        recvWindow)\n        \n    # Send in a new market order. \n    # Default parameters: type=Client.ORDER_TYPE_MARKET\n    client.order_market(symbol, \n        side, \n        quantity, \n        quoteOrderQty, \n        newClientOrderId, \n        newOrderRespType, \n        recvWindow)\n        \n    # Send in a new market buy order. \n    # Default parameters: type=Client.ORDER_TYPE_MARKET, side=Client.SIDE_BUY\n    client.order_market_buy(symbol, \n        quantity, \n        quoteOrderQty, \n        newClientOrderId, \n        newOrderRespType, \n        recvWindow)\n    \n    # Send in a new market sell order. \n    # Default parameters: type=Client.ORDER_TYPE_MARKET, side=Client.SIDE_SELL\n    client.order_market_sell(symbol, \n        quantity, \n        quoteOrderQty, \n        newClientOrderId, \n        newOrderRespType, \n        recvWindow)\n    ```\n  - **DELETE /api/v3/order (HMAC SHA256)** (Cancel an active order.)\n    ```python \n    client.cancel_order(symbol, orderId, origClientOrderId, newClientOrderId, recvWindow)\n    ```\n  - **DELETE api/v3/openOrders** (Cancels all active orders on a symbol. This includes OCO orders.)\n  \n    > :warning: Not yet implemented\n  - **GET /api/v3/order (HMAC SHA256)** (Check an order's status.)\n    ```python \n    client.get_order(symbol, orderId, origClientOrderId, recvWindow)\n    ```\n  - **GET /api/v3/openOrders (HMAC SHA256)** (Get all open orders on a symbol. **Careful** when accessing this with no symbol.)\n    ```python \n    client.get_open_orders(symbol, recvWindow)\n    ```\n  - **GET /api/v3/allOrders (HMAC SHA256)** (Get all account orders; active, canceled, or filled.)\n    ```python \n    client.get_all_orders(symbol, orderId, startTime, endTime, limit, recvWindow)\n    ```\n  - **POST /api/v3/order/oco (HMAC SHA256)** (Send in a new OCO order)\n    ```python \n    client.create_oco_order(symbol, \n        listClientOrderId, \n        side, \n        quantity, \n        limitClientOrderId, \n        price, \n        limitIcebergQty, \n        stopClientOrderId, \n        stopPrice, \n        stopLimitPrice, \n        stopIcebergQty, \n        stopLimitTimeInForce, \n        newOrderRespType, \n        recvWindow)\n    \n    ## Wrapper Functions:\n    \n    # Send in a new OCO buy order. Default parameter: type=Client.SIDE_BUY\n    client.order_oco_buy(symbol, \n        listClientOrderId, \n        quantity, \n        limitClientOrderId, \n        price, \n        limitIcebergQty, \n        stopClientOrderId, \n        stopPrice, \n        stopLimitPrice, \n        stopIcebergQty, \n        stopLimitTimeInForce, \n        newOrderRespType, \n        recvWindow)\n        \n    # Send in a new OCO sell order. Default parameter: type=Client.SIDE_SELL\n    client.order_oco_sell(symbol, \n        listClientOrderId, \n        quantity, \n        limitClientOrderId, \n        price, \n        limitIcebergQty, \n        stopClientOrderId, \n        stopPrice, \n        stopLimitPrice, \n        stopIcebergQty, \n        stopLimitTimeInForce, \n        newOrderRespType, \n        recvWindow)\n    ```\n  - **DELETE /api/v3/orderList (HMAC SHA256)** (Cancel OCO: Cancel an entire Order List)\n   \n    > :warning: Not yet implemented\n  - **GET /api/v3/orderList (HMAC SHA256)** (Query OCO: Retrieves a specific OCO based on provided optional parameters)\n  \n    > :warning: Not yet implemented\n  - **GET /api/v3/allOrderList (HMAC SHA256)** (Retrieves all OCO based on provided optional parameters)\n  \n    > :warning: Not yet implemented\n  - **GET /api/v3/openOrderList (HMAC SHA256)** (Query Open OCO (USER_DATA))\n  \n    > :warning: Not yet implemented\n  - **GET /api/v3/account (HMAC SHA256)** (Get current account information.)\n    ```python \n    client.get_account(recvWindow)\n    ```\n  - **GET /api/v3/myTrades (HMAC SHA256)** (Get trades for a specific account and symbol.)\n    ```python \n    client.get_my_trades(symbol, startTime, endTime, fromId, limit, recvWindow)\n    ```\n- *Margin Account/Trade*\n  - **POST /sapi/v1/margin/transfer (HMAC SHA256)** (Execute transfer between margin account and spot account(MARGIN).)\n    ```python \n    client.transfer_margin_to_spot(asset, amount, recvWindow)\n    client.transfer_spot_to_margin(asset, amount, recvWindow)\n    ```\n  - **POST /sapi/v1/margin/loan (HMAC SHA256)** (Apply for a loan(MARGIN).)\n    ```python \n    client.create_margin_loan(asset, isIsolated, symbol, amount, recvWindow)\n    ```\n  - **POST /sapi/v1/margin/repay (HMAC SHA256)** (Repay loan for margin account (MARGIN).)\n    ```python \n    client.repay_margin_loan(asset, isIsolated, symbol, amount, recvWindow)\n    ```\n  - **GET /sapi/v1/margin/asset** (Query Margin Asset (MARKET_DATA).)\n    ```python \n    client.get_margin_asset(asset)\n    ```\n  - **GET /sapi/v1/margin/pair** (Query Cross Margin Pair (MARKET_DATA).)\n    ```python \n    client.get_margin_symbol(symbol)\n    ```\n  - **GET /sapi/v1/margin/allAssets** (Get All Cross Margin Assets (MARKET_DATA).)\n    ```python \n    client.get_margin_all_assets()\n    ```\n  - **GET /sapi/v1/margin/allPairs** (Get All Cross Margin Pairs (MARKET_DATA).)\n    ```python \n    client.get_margin_all_pairs()\n    ```\n  - **GET /sapi/v1/margin/priceIndex** (Query Margin PriceIndex (MARKET_DATA).)\n    ```python \n    client.get_margin_price_index(symbol)\n    ```\n  - **POST /sapi/v1/margin/order (HMAC SHA256)** (Post a new order for margin account.)\n    ```python \n    client.create_margin_order(symbol,\n        isIsolated,\n        side, \n        type, \n        quantity, \n        price, \n        stopPrice, \n        newClientOrderId,\n        icebergQty,\n        newOrderRespType,\n        sideEffectType,\n        timeInForce, \n        recvWindow)\n    ```\n  - **DELETE /sapi/v1/margin/order (HMAC SHA256)** (Cancel an active order for margin account.)\n    ```python \n    client.cancel_margin_order(symbol, \n        isIsolated, \n        orderId, \n        origClientOrderId, \n        newClientOrderId, \n        recvWindow)\n    ```\n  - **GET /sapi/v1/margin/transfer (HMAC SHA256)** (Get Cross Margin Transfer History (USER_DATA).)\n    ```python \n    client.transfer_margin_to_spot(asset, amount, recvWindow)\n    client.transfer_spot_to_margin(asset, amount, recvWindow)\n    ```\n  - **GET /sapi/v1/margin/loan (HMAC SHA256)** (Query Loan Record (USER_DATA).)\n    ```python \n    client.get_margin_loan_details(asset, isolatedSymbol, txId, startTime, endTime, current, size, recvWindow)\n    ```\n  - **GET /sapi/v1/margin/repay (HMAC SHA256)** (Query repay record (USER_DATA).)\n    ```python \n    client.get_margin_repay_details(asset, isolatedSymbol, txId, startTime, endTime, current, size, recvWindow)\n    ```\n  - **GET /sapi/v1/margin/interestHistory (HMAC SHA256)** (Get Interest History (USER_DATA).)\n    ```python \n    client.get_margin_interest_history(asset, isolatedSymbol, startTime, endTime, current, size, archived, recvWindow)\n    ```\n  - **GET /sapi/v1/margin/forceLiquidationRec (HMAC SHA256)** (Get Force Liquidation Record (USER_DATA).)\n    ```python \n    client.get_margin_force_liquidation_rec(isolatedSymbol, startTime, endTime, current, size, recvWindow)\n    ```\n  - **GET /sapi/v1/margin/account (HMAC SHA256)** (Query Cross Margin Account Details (USER_DATA).)\n    ```python \n    client.get_margin_account(recvWindow)\n    ```\n  - **GET /sapi/v1/margin/order (HMAC SHA256)** (Query Margin Account's Order (USER_DATA).)\n    ```python \n    client.get_margin_order(symbol, isIsolated, orderId, origClientOrderId, recvWindow)\n    ```\n  - **GET /sapi/v1/margin/openOrders (HMAC SHA256)** (Query Margin Account's Open Order (USER_DATA).)\n    ```python \n    client.get_open_margin_orders(symbol, isIsolated, recvWindow)\n    ```\n  - **GET /sapi/v1/margin/allOrders (HMAC SHA256)** (Query Margin Account's All Order (USER_DATA).)\n    ```python \n    client.get_all_margin_orders(symbol, isIsolated, orderId, startTime, endTime, limit, recvWindow)\n    ```\n  - **GET /sapi/v1/margin/myTrades (HMAC SHA256)** (Query Margin Account's Trade List (USER_DATA).)\n    ```python \n    client.get_margin_trades(symbol, isIsolated, startTime, endTime, fromId, limit, recvWindow)\n    ```\n  - **GET /sapi/v1/margin/maxBorrowable (HMAC SHA256)** (Query Max Borrow amount for an asset (USER_DATA).)\n    ```python \n    client.get_max_margin_loan(asset, isolatedSymbol, recvWindow)\n    ```\n  - **GET /sapi/v1/margin/maxTransferable (HMAC SHA256)** (Query Max Transfer-Out Amount (USER_DATA).)\n    ```python \n    client.get_max_margin_transfer(asset, isolatedSymbol, recvWindow)\n    ```\n  - **POST /sapi/v1/margin/isolated/create (HMAC SHA256)** (Create Isolated Margin Account (MARGIN).)\n    ```python \n    client.create_isolated_margin_account(base, quote, recvWindow)\n    ```\n  - **POST /sapi/v1/margin/isolated/transfer (HMAC SHA256)** (Isolated Margin Account Transfer (MARGIN).)\n    ```python \n    client.transfer_spot_to_isolated_margin(asset, symbol, amount, recvWindow)\n    client.transfer_isolated_margin_to_spot(asset, symbol, amount, recvWindow)\n    ```\n  - **GET /sapi/v1/margin/isolated/transfer (HMAC SHA256)** (Get Isolated Margin Transfer History (USER_DATA).)\n  \n    > :warning: Not yet implemented\n  - **GET /sapi/v1/margin/isolated/account (HMAC SHA256)** (Query Isolated Margin Account Info (USER_DATA).)\n    ```python \n    client.get_isolated_margin_account(symbols, recvWindow)\n    ```\n  - **GET /sapi/v1/margin/isolated/pair (HMAC SHA256)** (Query Isolated Margin Symbol (USER_DATA).)\n    ```python \n    client.get_isolated_margin_symbol(symbol, recvWindow)\n    ```\n  - **GET /sapi/v1/margin/isolated/allPairs (HMAC SHA256)** (Get All Isolated Margin Symbol (USER_DATA).)\n    ```python \n    client.get_all_isolated_margin_symbols(recvWindow)\n    ```\n  - **POST /sapi/v1/margin/manual-liquidation (HMAC SHA256)** (Margin manual liquidation (MARGIN).)\n    ```python \n    client.margin_manual_liquidation(type)\n    ```\n- *User Data Streams*\n  - **POST /api/v3/userDataStream** (Create a ListenKey (Spot) (USER_STREAM): Start a new user data stream.)\n    ```python \n    client.stream_get_listen_key()\n    ```\n  - **PUT /api/v3/userDataStream** (Ping/Keep-alive a ListenKey (Spot) (USER_STREAM).)\n    ```python \n    client.stream_keepalive(listenKey)\n    ```\n  - **DELETE /api/v3/userDataStream** (Close a ListenKey (Spot) (USER_STREAM).)\n    ```python \n    client.stream_close(listenKey)\n    ```\n  - **POST /sapi/v1/userDataStream** (Create a ListenKey (Margin).)\n    ```python \n    client.margin_stream_get_listen_key()\n    ```\n  - **PUT /sapi/v1/userDataStream** (Ping/Keep-alive a ListenKey (Margin).)\n    ```python \n    client.margin_stream_keepalive(listenKey)\n    ```\n  - **DELETE /sapi/v1/userDataStream** (Close a ListenKey (Margin).)\n    ```python \n    client.margin_stream_close(listenKey)\n    ```\n  - **POST /sapi/v1/userDataStream/isolated** (Create a ListenKey (Isolated).)\n    ```python \n    client.isolated_margin_stream_get_listen_key(symbol)\n    ```\n  - **PUT /sapi/v1/userDataStream/isolated** (Ping/Keep-alive a ListenKey (Isolated).)\n    ```python \n    client.isolated_margin_stream_keepalive(symbol, listenKey)\n    ```\n  - **DELETE /sapi/v1/userDataStream/isolated** (Close a ListenKey (Isolated).)\n    ```python \n    client.isolated_margin_stream_close(symbol, listenKey)\n    ```\n- *Savings Endpoints*\n  - **GET /sapi/v1/lending/daily/product/list (HMAC SHA256)** (Get Flexible Product List (USER_DATA).)\n    ```python \n    client.get_lending_product_list(status, featured, recvWindow)\n    ```\n  - **GET /sapi/v1/lending/daily/userLeftQuota (HMAC SHA256)** (Get Left Daily Purchase Quota of Flexible Product (USER_DATA).)\n    ```python \n    client.get_lending_daily_quota_left(productId, recvWindow)\n    ```\n  - **POST /sapi/v1/lending/daily/purchase (HMAC SHA256)** (Purchase Flexible Product (USER_DATA).)\n    ```python \n    client.purchase_lending_product(productId, amount, recvWindow)\n    ```\n  - **GET /sapi/v1/lending/daily/userRedemptionQuota (HMAC SHA256)** (Get Left Daily Redemption Quota of Flexible Product (USER_DATA).)\n    ```python \n    client.get_lending_daily_redemption_quota(productId, type, recvWindow)\n    ```\n  - **POST /sapi/v1/lending/daily/redeem (HMAC SHA256)** (Redeem Flexible Product (USER_DATA).)\n    ```python \n    client.redeem_lending_product(productId, amount, type, recvWindow)\n    ```\n  - **GET /sapi/v1/lending/daily/token/position (HMAC SHA256)** (Get Flexible Product Position (USER_DATA).)\n    ```python \n    client.get_lending_position(asset, recvWindow)\n    ```\n  - **GET /sapi/v1/lending/project/list (HMAC SHA256)** (Get Fixed and Activity Project List (USER_DATA).)\n    ```python \n    client.get_fixed_activity_project_list(asset, type, status, isSortAsc, sortBy, current, size, recvWindow)\n    ```\n  - **POST /sapi/v1/lending/customizedFixed/purchase (HMAC SHA256)** (Purchase Fixed/Activity Project (USER_DATA).)\n\n    > :warning: Not yet implemented\n  - **GET /sapi/v1/lending/project/position/list (HMAC SHA256)** (Get Fixed/Activity Project Position (USER_DATA).)\n\n    > :warning: Not yet implemented\n  - **GET /sapi/v1/lending/union/account (HMAC SHA256)** (Lending Account (USER_DATA).)\n    ```python \n    client.get_lending_account(recvWindow)\n    ```\n  - **GET /sapi/v1/lending/union/purchaseRecord (HMAC SHA256)** (Get Purchase Record (USER_DATA).)\n    ```python \n    client.get_lending_purchase_history(lendingType, asset, startTime, endTime, current, size, recvWindow)\n    ```\n  - **GET /sapi/v1/lending/union/redemptionRecord (HMAC SHA256)** (Get Redemption Record (USER_DATA).)\n    ```python \n    client.get_lending_redemption_history(lendingType, asset, startTime, endTime, current, size, recvWindow)\n    ```\n  - **GET /sapi/v1/lending/union/interestHistory (HMAC SHA256)** (Get Interest History (USER_DATA).)\n    ```python \n    client.get_lending_interest_history(lendingType, asset, startTime, endTime, current, size, recvWindow)\n    ```\n  - **POST /sapi/v1/lending/positionChanged (HMAC SHA256)** (Change Fixed/Activity Position to Daily Position (USER_DATA).)\n    ```python \n    client.change_fixed_activity_to_daily_position(projectId, lot, positionId, recvWindow)\n    ```\n- *Mining Endpoints*\n    > :warning: Not yet implemented\n- *Sub-Account Endpoints*\n  - **GET /sapi/v1/sub-account/list (HMAC SHA256)** (Query Sub-account List (For Master Account).)\n    ```python \n    client.get_sub_account_list(email, isFreeze, page, limit, recvWindow)\n    ```\n  - **GET /sapi/v1/sub-account/sub/transfer/history (HMAC SHA256)** (Query Sub-account Spot Asset Transfer History (For Master Account).)\n    ```python \n    client.get_sub_account_transfer_history(fromEmail, toEmail, startTime, endTime, page, limit, recvWindow)\n    ```\n  - **GET /sapi/v1/sub-account/assets (HMAC SHA256)** (Query Sub-account Assets (For Master Account).)\n    ```python \n    client.get_sub_account_assets(email, recvWindow)\n    ```\n  > :warning: The rest of methods for Sub-Account Endpoints are not yet implemented\n- *BLVT Endpoints*\n    > :warning: Not yet implemented\n- *BSwap Endpoints*\n    > :warning: Not yet implemented\n### [USDT-M Futures](https://binance-docs.github.io/apidocs/futures/en/)\n- *Market Data Endpoints*\n  - **GET /fapi/v1/ping** (Test connectivity to the Rest API.)\n    ```python \n    client.futures_ping()\n    ```\n  - **GET /fapi/v1/time** (Test connectivity to the Rest API and get the current server time.)\n    ```python \n    client.futures_time()\n    ```\n  - **GET /fapi/v1/exchangeInfo** (Current exchange trading rules and symbol information.)\n    ```python \n    client.futures_exchange_info()\n    ```\n  - **GET /fapi/v1/depth** (Get the Order Book for the market.)\n    ```python \n    client.futures_order_book(symbol, limit)\n    ```\n  - **GET /fapi/v1/trades** (Get recent trades.)\n    ```python \n    client.futures_recent_trades(symbol, limit)\n    ```\n  - **GET /fapi/v1/historicalTrades** (Get older market historical trades (MARKET_DATA).)\n    ```python \n    client.futures_historical_trades(symbol, limit, fromId)\n    ```\n  - **GET /fapi/v1/aggTrades** (Get compressed, aggregate trades. Trades that fill at the time, from the same order, with the same price will have the quantity aggregated.)\n    ```python \n    client.futures_aggregate_trades(symbol, fromId, startTime, endTime, limit)\n    ```\n  - **GET /fapi/v1/klines** (Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time.)\n    ```python \n    client.futures_klines(symbol, interval, startTime, endTime, limit)\n    ```\n  - **GET /fapi/v1/premiumIndex** (Get Mark Price and Funding Rate.)\n    ```python \n    client.futures_mark_price(symbol)\n    ```\n  - **GET /fapi/v1/fundingRate** (Get Funding Rate History.)\n    ```python \n    client.futures_funding_rate(symbol, startTime, endTime, limit)\n    ```\n  - **GET /fapi/v1/ticker/24hr** (24 hour rolling window price change statistics. **Careful** when accessing this with no symbol.)\n    ```python \n    client.futures_ticker(symbol)\n    ```\n  - **GET /fapi/v1/ticker/price** (Latest price for a symbol or symbols.)\n    ```python \n    client.futures_symbol_ticker(symbol)\n    ```\n  - **GET /fapi/v1/ticker/bookTicker** (Best price/qty on the order book for a symbol or symbols.)\n    ```python \n    client.futures_orderbook_ticker(symbol)\n    ``` \n  - **GET /fapi/v1/allForceOrders** (Get all Liquidation Orders.)\n    > :warning: Probably broken, python code below is implemented on v1/ticker/allForceOrders endpoint.\n    ```python \n    client.futures_liquidation_orders(symbol, startTime, endTime, limit)\n    ``` \n  - **GET /fapi/v1/openInterest** (Get present open interest of a specific symbol.)\n    ```python \n    client.futures_open_interest(symbol)\n    ``` \n  - **GET /futures/data/openInterestHist** (Open Interest Statistics.)\n    ```python \n    client.futures_open_interest_hist(symbol, period, limit, startTime, endTime)\n    ``` \n  - **GET /futures/data/topLongShortAccountRatio** (Top Trader Long/Short Ratio (Accounts) (MARKET_DATA).)\n    ```python \n    client.futures_top_longshort_account_ratio(symbol, period, limit, startTime, endTime)\n    ``` \n  - **GET /futures/data/topLongShortPositionRatio** (Top Trader Long/Short Ratio (Positions).)\n    ```python\n    client.futures_top_longshort_position_ratio(symbol, period, limit, startTime, endTime)\n    ```\n  - **GET /futures/data/globalLongShortAccountRatio** (Long/Short Ratio.)\n    ```python\n    client.futures_global_longshort_ratio(symbol, period, limit, startTime, endTime)\n    ```\n  - **GET /futures/data/takerlongshortRatio** (Taker Buy/Sell Volume.)\n    ```python\n    client.futures_taker_longshort_ratio(symbol, period, limit, startTime, endTime)\n    ```\n  - **GET /fapi/v1/lvtKlines** (Historical BLVT NAV Kline/Candlestick.)\n\n    > :warning: Not yet implemented\n  - **GET /fapi/v1/indexInfo** (Composite Index Symbol Information.)\n\n    > :warning: Not yet implemented\n- *Account/trades Endpoints*\n  - **POST /sapi/v1/futures/transfer (HMAC SHA256)** (New Future Account Transfer (FUTURES): Execute transfer between spot account and futures account.)\n    ```python \n    client.futures_account_transfer(asset, amount, type, recvWindow)\n    ```\n  - **GET /sapi/v1/futures/transfer (HMAC SHA256)** (Get Future Account Transaction History List (USER_DATA).)\n    ```python \n    client.transfer_history(asset, startTime, endTime, current, size, recvWindow)\n    ```\n  - **POST /fapi/v1/positionSide/dual (HMAC SHA256)** (Change user's position mode (Hedge Mode or One-way Mode ) on _**EVERY symbol**_.)\n    ```python \n    client.futures_change_position_mode(dualSidePosition, recvWindow)\n    ```\n  - **GET /fapi/v1/positionSide/dual (HMAC SHA256)** (Get user's position mode (Hedge Mode or One-way Mode ) on _**EVERY symbol**_.)\n    ```python \n    client.futures_get_position_mode(recvWindow)\n    ```\n  - **POST /fapi/v1/order (HMAC SHA256)** (Send in a new order (TRADE).)\n    ```python \n    client.futures_create_order(symbol, \n                                side,\n                                positionSide,\n                                type, \n                                timeInForce, \n                                quantity,\n                                reduceOnly,\n                                price, \n                                newClientOrderId, \n                                stopPrice,\n                                closePosition,\n                                activationPrice,\n                                callbackRate,\n                                workingType,\n                                priceProtect,\n                                newOrderRespType,\n                                recvWindow)\n    ```\n  - **POST /fapi/v1/batchOrders (HMAC SHA256)** (Place Multiple Orders (TRADE).)\n\n    > :warning: Not yet implemented\n  - **GET /fapi/v1/order (HMAC SHA256)** (Query Order (USER_DATA): Check an order's status.)\n    ```python \n    client.futures_get_order(symbol, orderId, origClientOrderId, recvWindow)\n    ```\n  - **DELETE /fapi/v1/order (HMAC SHA256)** (Cancel an active order (TRADE).)\n    ```python \n    client.futures_cancel_order(symbol, orderId, origClientOrderId, recvWindow)\n    ```\n  - **DELETE /fapi/v1/allOpenOrders (HMAC SHA256)** (Cancel All Open Orders (TRADE).)\n    ```python \n    client.futures_cancel_all_open_orders(symbol, recvWindow)\n    ```\n  - **DELETE /fapi/v1/batchOrders (HMAC SHA256)** (Cancel Multiple Orders (TRADE).)\n    ```python \n    client.futures_cancel_orders(symbol, orderIdList, origClientOrderIdList, recvWindow)\n    ```\n  - **POST /fapi/v1/countdownCancelAll (HMAC SHA256)** (Cancel all open orders of the specified symbol at the end of the specified countdown (TRADE).)\n\n    > :warning: Not yet implemented\n  - **GET /fapi/v1/openOrder (HMAC SHA256)** (Query Current Open Order (USER_DATA).)\n  \n    > :warning: Not yet implemented\n  - **GET /fapi/v1/openOrders (HMAC SHA256)** (Get all open orders on a symbol. **Careful** when accessing this with no symbol (USER_DATA).)\n    ```python \n    client.futures_get_open_orders(symbol, recvWindow)\n    ```\n  - **GET /fapi/v1/allOrders (HMAC SHA256)** (Get all account orders; active, canceled, or filled (USER_DATA).)\n    ```python \n    client.futures_get_all_orders(symbol, orderId, startTime, endTime, limit, recvWindow)\n    ```\n  - **GET /fapi/v2/balance (HMAC SHA256)** (Futures Account Balance V2 (USER_DATA).)\n    > :warning: Probably broken, python code below is implemented on v1 endpoint.\n    ```python \n    client.futures_account_balance(recvWindow)\n    ```\n  - **GET /fapi/v2/account (HMAC SHA256)** (Account Information V2: Get current account information (USER_DATA).)\n    > :warning: Probably broken, python code below is implemented on v1 endpoint.\n    ```python \n    client.futures_account(recvWindow)\n    ```\n  - **POST /fapi/v1/leverage (HMAC SHA256)** (Change user's initial leverage of specific symbol market (TRADE).)\n    ```python \n    client.futures_change_leverage(symbol, leverage, recvWindow)\n    ```\n  - **POST /fapi/v1/marginType (HMAC SHA256)** (Change the margin type for a symbol (TRADE).)\n    ```python \n    client.futures_change_margin_type(symbol, marginType, recvWindow)\n    ```\n  - **POST /fapi/v1/positionMargin (HMAC SHA256)** (Modify Isolated Position Margin (TRADE).)\n    ```python \n    client.futures_change_position_margin(symbol, positionSide, amount, type, recvWindow)\n    ```\n  - **GET /fapi/v1/positionMargin/history (HMAC SHA256)** (Get Position Margin Change History (TRADE).)\n    ```python \n    client.futures_position_margin_history(symbol, type, startTime, endTime, limit, recvWindow)\n    ```\n  - **GET /fapi/v2/positionRisk (HMAC SHA256)** (Position Information V2: Get current position information (USER_DATA).)\n    > :warning: Probably broken, python code below is implemented on v1 endpoint.\n    ```python \n    client.futures_position_information(symbol, recvWindow)\n    ```\n  - **GET /fapi/v1/userTrades (HMAC SHA256)** (Account Trade List: Get trades for a specific account and symbol (USER_DATA).)\n    ```python \n    client.futures_account_trades(symbol, startTime, endTime, fromId, limit, recvWindow)\n    ```\n  - **GET /fapi/v1/income (HMAC SHA256)** (Get Income History (USER_DATA).)\n    ```python \n    client.futures_income_history(symbol, incomeType, startTime, endTime, limit, recvWindow)\n    ```\n  - **GET /fapi/v1/leverageBracket** (Notional and Leverage Brackets (USER_DATA).)\n    > :warning: Probably broken, python code below is implemented on ticker/leverageBracket endpoint.\n    ```python \n    client.futures_leverage_bracket(symbol, recvWindow)\n    ```\n  - **GET /fapi/v1/adlQuantile** (Position ADL Quantile Estimation (USER_DATA).)\n\n    > :warning: Not yet implemented\n  - **GET /fapi/v1/forceOrders** (User's Force Orders (USER_DATA).)\n\n    > :warning: Not yet implemented\n  - **GET /fapi/v1/apiTradingStatus** (User API Trading Quantitative Rules Indicators (USER_DATA).)\n\n    > :warning: Not yet implemented\n- *User Data Streams*\n    > :warning: Not yet implemented\n### [Vanilla Options](https://binance-docs.github.io/apidocs/voptions/en/)\n- *Quoting interface*\n  - **GET /vapi/v1/ping** (Test connectivity)\n    ```python \n    client.options_ping()\n    ```\n  - **GET /vapi/v1/time** (Get server time)\n    ```python \n    client.options_time()\n    ```\n  - **GET /vapi/v1/optionInfo** (Get current trading pair info)\n    ```python \n    client.options_info()\n    ```\n  - **GET /vapi/v1/exchangeInfo** (Get current limit info and trading pair info)\n    ```python \n    client.options_exchange_info()\n    ```\n  - **GET /vapi/v1/index** (Get the spot index price)\n    ```python \n    client.options_index_price(underlying)\n    ```\n  - **GET /vapi/v1/ticker** (Get the latest price)\n    ```python \n    client.options_price(symbol)\n    ```\n  - **GET /vapi/v1/mark** (Get the latest mark price)\n    ```python \n    client.options_mark_price(symbol)\n    ```\n  - **GET /vapi/v1/depth** (Depth information)\n    ```python \n    client.options_order_book(symbol, limit)\n    ```\n  - **GET /vapi/v1/klines** (Candle data)\n    ```python \n    client.options_klines(symbol, interval, startTime, endTime, limit)\n    ```\n  - **GET /vapi/v1/trades** (Recently completed Option trades)\n    ```python \n    client.options_recent_trades(symbol, limit)\n    ```\n  - **GET /vapi/v1/historicalTrades** (Query trade history)\n    ```python \n    client.options_historical_trades(symbol, fromId, limit)\n    ```\n- *Account and trading interface*\n  - **GET /vapi/v1/account (HMAC SHA256)** (Account asset info (USER_DATA))\n    ```python \n    client.options_account_info(recvWindow)\n    ```\n  - **POST /vapi/v1/transfer (HMAC SHA256)** (Funds transfer (USER_DATA))\n    ```python \n    client.options_funds_transfer(currency, type, amount, recvWindow)\n    ```\n  - **GET /vapi/v1/position (HMAC SHA256)** (Option holdings info (USER_DATA))\n    ```python \n    client.options_positions(symbol, recvWindow)\n    ```\n  - **POST /vapi/v1/bill (HMAC SHA256)** (Account funding flow (USER_DATA))\n    ```python \n    client.options_bill(currency, recordId, startTime, endTime, limit, recvWindow)\n    ```\n  - **POST /vapi/v1/order (HMAC SHA256)** (Option order (TRADE))\n    ```python \n    client.options_place_order(symbol, side, type, quantity, price, timeInForce, reduceOnly, postOnly, \\\n        newOrderRespType, clientOrderId, recvWindow, recvWindow)\n    ```\n  - **POST /vapi/v1/batchOrders (HMAC SHA256)** (Place Multiple Option orders (TRADE))\n    ```python \n    client.options_place_batch_order(orders, recvWindow)\n    ```\n  - **DELETE /vapi/v1/order (HMAC SHA256)** (Cancel Option order (TRADE))\n    ```python \n    client.options_cancel_order(symbol, orderId, clientOrderId, recvWindow)\n    ```\n  - **DELETE /vapi/v1/batchOrders (HMAC SHA256)** (Cancel Multiple Option orders (TRADE))\n    ```python \n    client.options_cancel_batch_order(symbol, orderIds, clientOrderIds, recvWindow)\n    ```\n  - **DELETE /vapi/v1/allOpenOrders (HMAC SHA256)** (Cancel all Option orders (TRADE))\n    ```python \n    client.options_cancel_all_orders(symbol, recvWindow)\n    ```\n  - **GET /vapi/v1/order (HMAC SHA256)** (Query Option order (TRADE))\n    ```python \n    client.options_query_order(symbol, orderId, clientOrderId, recvWindow)\n    ```\n  - **GET /vapi/v1/openOrders (HMAC SHA256)** (Query current pending Option orders (TRADE))\n    ```python \n    client.options_query_pending_orders(symbol, orderId, startTime, endTime, limit, recvWindow)\n    ```\n  - **GET /vapi/v1/historyOrders (HMAC SHA256)** (Query Option order history (TRADE))\n    ```python \n    client.options_query_order_history(symbol, orderId, startTime, endTime, limit, recvWindow)\n    ```\n  - **GET /vapi/v1/userTrades (HMAC SHA256)** (Option Trade List (USER_DATA))\n    ```python \n    client.options_user_trades(symbol, fromId, startTime, endTime, limit, recvWindow)\n    ```\n### [COIN-M Futures](https://binance-docs.github.io/apidocs/delivery/en/)\n> :warning: Not yet implemented\n### [USDT-M Futures testnet](https://binance-docs.github.io/apidocs/testnet/en/)\n> :warning: Not yet implemented  \n### [COIN-M Futures testnet](https://binance-docs.github.io/apidocs/delivery_testnet/en/)\n> :warning: Not yet implemented  \n\t- **GET /sapi/v1/loan/vip/ongoing/orders**\n    ```python\n    client.margin_v1_get_loan_vip_ongoing_orders(**params)\n    ```\n\n\t- **GET /sapi/v1/mining/payment/other**\n    ```python\n    client.margin_v1_get_mining_payment_other(**params)\n    ```\n\n\t- **GET /dapi/v1/income/asyn/id**\n    ```python\n    client.futures_coin_v1_get_income_asyn_id(**params)\n    ```\n\n\t- **GET /sapi/v1/simple-earn/flexible/history/subscriptionRecord**\n    ```python\n    client.margin_v1_get_simple_earn_flexible_history_subscription_record(**params)\n    ```\n\n\t- **POST /sapi/v1/lending/auto-invest/one-off**\n    ```python\n    client.margin_v1_post_lending_auto_invest_one_off(**params)\n    ```\n\n\t- **POST /sapi/v1/broker/subAccountApi/commission/coinFutures**\n    ```python\n    client.margin_v1_post_broker_sub_account_api_commission_coin_futures(**params)\n    ```\n\n\t- **POST /papi/v1/repay-futures-negative-balance**\n    ```python\n    client.papi_v1_post_repay_futures_negative_balance(**params)\n    ```\n\n\t- **POST /eapi/v1/block/order/execute**\n    ```python\n    client.options_v1_post_block_order_execute(**params)\n    ```\n\n\t- **GET /sapi/v1/margin/dust**\n    ```python\n    client.margin_v1_get_margin_dust(**params)\n    ```\n\n\t- **GET /dapi/v1/trades**\n    ```python\n    client.futures_coin_v1_get_trades(**params)\n    ```\n\n\t- **POST /api/v3/orderList/otoco**\n    ```python\n    client.v3_post_order_list_otoco(**params)\n    ```\n\n\t- **GET /fapi/v1/order/asyn**\n    ```python\n    client.futures_v1_get_order_asyn(**params)\n    ```\n\n\t- **GET /sapi/v1/asset/custody/transfer-history**\n    ```python\n    client.margin_v1_get_asset_custody_transfer_history(**params)\n    ```\n\n\t- **POST /fapi/v1/order/test**\n    ```python\n    client.futures_v1_post_order_test(**params)\n    ```\n\n\t- **POST /sapi/v1/broker/subAccount/blvt**\n    ```python\n    client.margin_v1_post_broker_sub_account_blvt(**params)\n    ```\n\n\t- **POST /sapi/v1/sol-staking/sol/redeem**\n    ```python\n    client.margin_v1_post_sol_staking_sol_redeem(**params)\n    ```\n\n\t- **GET /eapi/v1/countdownCancelAll**\n    ```python\n    client.options_v1_get_countdown_cancel_all(**params)\n    ```\n\n\t- **GET /sapi/v1/margin/tradeCoeff**\n    ```python\n    client.margin_v1_get_margin_trade_coeff(**params)\n    ```\n\n\t- **GET /sapi/v1/sub-account/futures/positionRisk**\n    ```python\n    client.margin_v1_get_sub_account_futures_position_risk(**params)\n    ```\n\n\t- **GET /dapi/v1/orderAmendment**\n    ```python\n    client.futures_coin_v1_get_order_amendment(**params)\n    ```\n\n\t- **GET /papi/v1/margin/openOrders**\n    ```python\n    client.papi_v1_get_margin_open_orders(**params)\n    ```\n\n\t- **GET /sapi/v1/margin/available-inventory**\n    ```python\n    client.margin_v1_get_margin_available_inventory(**params)\n    ```\n\n\t- **POST /sapi/v1/account/apiRestrictions/ipRestriction/ipList**\n    ```python\n    client.margin_v1_post_account_api_restrictions_ip_restriction_ip_list(**params)\n    ```\n\n\t- **GET /sapi/v2/eth-staking/account**\n    ```python\n    client.margin_v2_get_eth_staking_account(**params)\n    ```\n\n\t- **POST /papi/v1/asset-collection**\n    ```python\n    client.papi_v1_post_asset_collection(**params)\n    ```\n\n\t- **GET /papi/v1/um/trade/asyn/id**\n    ```python\n    client.papi_v1_get_um_trade_asyn_id(**params)\n    ```\n\n\t- **POST /sapi/v1/staking/redeem**\n    ```python\n    client.margin_v1_post_staking_redeem(**params)\n    ```\n\n\t- **GET /sapi/v1/loan/income**\n    ```python\n    client.margin_v1_get_loan_income(**params)\n    ```\n\n\t- **GET /eapi/v1/depth**\n    ```python\n    client.options_v1_get_depth(**params)\n    ```\n\n\t- **GET /dapi/v1/pmAccountInfo**\n    ```python\n    client.futures_coin_v1_get_pm_account_info(**params)\n    ```\n\n\t- **GET /sapi/v1/managed-subaccount/queryTransLogForInvestor**\n    ```python\n    client.margin_v1_get_managed_subaccount_query_trans_log_for_investor(**params)\n    ```\n\n\t- **POST /sapi/v1/dci/product/auto_compound/edit-status**\n    ```python\n    client.margin_v1_post_dci_product_auto_compound_edit_status(**params)\n    ```\n\n\t- **GET /fapi/v1/trade/asyn**\n    ```python\n    client.futures_v1_get_trade_asyn(**params)\n    ```\n\n\t- **GET /sapi/v1/loan/vip/request/interestRate**\n    ```python\n    client.margin_v1_get_loan_vip_request_interest_rate(**params)\n    ```\n\n\t- **GET /fapi/v1/fundingInfo**\n    ```python\n    client.futures_v1_get_funding_info(**params)\n    ```\n\n\t- **GET /sapi/v2/loan/flexible/repay/rate**\n    ```python\n    client.margin_v2_get_loan_flexible_repay_rate(**params)\n    ```\n\n\t- **GET /sapi/v1/lending/auto-invest/plan/id**\n    ```python\n    client.margin_v1_get_lending_auto_invest_plan_id(**params)\n    ```\n\n\t- **POST /sapi/v1/loan/adjust/ltv**\n    ```python\n    client.margin_v1_post_loan_adjust_ltv(**params)\n    ```\n\n\t- **GET /sapi/v1/bnbBurn**\n    ```python\n    client.margin_v1_get_bnb_burn(**params)\n    ```\n\n\t- **GET /papi/v1/um/order**\n    ```python\n    client.papi_v1_get_um_order(**params)\n    ```\n\n\t- **GET /sapi/v1/mining/statistics/user/status**\n    ```python\n    client.margin_v1_get_mining_statistics_user_status(**params)\n    ```\n\n\t- **POST /sapi/v1/staking/purchase**\n    ```python\n    client.margin_v1_post_staking_purchase(**params)\n    ```\n\n\t- **POST /sapi/v1/giftcard/redeemCode**\n    ```python\n    client.margin_v1_post_giftcard_redeem_code(**params)\n    ```\n\n\t- **GET /eapi/v1/userTrades**\n    ```python\n    client.options_v1_get_user_trades(**params)\n    ```\n\n\t- **GET /sapi/v1/broker/transfer/futures**\n    ```python\n    client.margin_v1_get_broker_transfer_futures(**params)\n    ```\n\n\t- **POST /sapi/v1/algo/spot/newOrderTwap**\n    ```python\n    client.margin_v1_post_algo_spot_new_order_twap(**params)\n    ```\n\n\t- **GET /sapi/v1/lending/auto-invest/target-asset/list**\n    ```python\n    client.margin_v1_get_lending_auto_invest_target_asset_list(**params)\n    ```\n\n\t- **GET /sapi/v1/capital/deposit/address/list**\n    ```python\n    client.margin_v1_get_capital_deposit_address_list(**params)\n    ```\n\n\t- **POST /sapi/v1/broker/subAccount/bnbBurn/marginInterest**\n    ```python\n    client.margin_v1_post_broker_sub_account_bnb_burn_margin_interest(**params)\n    ```\n\n\t- **POST /sapi/v2/loan/flexible/repay**\n    ```python\n    client.margin_v2_post_loan_flexible_repay(**params)\n    ```\n\n\t- **GET /sapi/v2/loan/flexible/loanable/data**\n    ```python\n    client.margin_v2_get_loan_flexible_loanable_data(**params)\n    ```\n\n\t- **POST /sapi/v1/broker/subAccountApi/permission**\n    ```python\n    client.margin_v1_post_broker_sub_account_api_permission(**params)\n    ```\n\n\t- **GET /sapi/v1/dci/product/positions**\n    ```python\n    client.margin_v1_get_dci_product_positions(**params)\n    ```\n\n\t- **POST /sapi/v1/convert/limit/cancelOrder**\n    ```python\n    client.margin_v1_post_convert_limit_cancel_order(**params)\n    ```\n\n\t- **GET /sapi/v1/margin/exchange-small-liability-history**\n    ```python\n    client.margin_v1_get_margin_exchange_small_liability_history(**params)\n    ```\n\n\t- **GET /sapi/v1/mining/hash-transfer/config/details/list**\n    ```python\n    client.margin_v1_get_mining_hash_transfer_config_details_list(**params)\n    ```\n\n\t- **GET /sapi/v1/mining/hash-transfer/profit/details**\n    ```python\n    client.margin_v1_get_mining_hash_transfer_profit_details(**params)\n    ```\n\n\t- **GET /sapi/v1/broker/subAccount**\n    ```python\n    client.margin_v1_get_broker_sub_account(**params)\n    ```\n\n\t- **GET /sapi/v1/portfolio/balance**\n    ```python\n    client.margin_v1_get_portfolio_balance(**params)\n    ```\n\n\t- **POST /sapi/v1/sub-account/eoptions/enable**\n    ```python\n    client.margin_v1_post_sub_account_eoptions_enable(**params)\n    ```\n\n\t- **POST /papi/v1/ping**\n    ```python\n    client.papi_v1_post_ping(**params)\n    ```\n\n\t- **GET /sapi/v1/loan/loanable/data**\n    ```python\n    client.margin_v1_get_loan_loanable_data(**params)\n    ```\n\n\t- **POST /sapi/v1/eth-staking/wbeth/unwrap**\n    ```python\n    client.margin_v1_post_eth_staking_wbeth_unwrap(**params)\n    ```\n\n\t- **PUT /fapi/v1/order**\n    ```python\n    client.futures_v1_put_order(**params)\n    ```\n\n\t- **GET /sapi/v1/eth-staking/eth/history/stakingHistory**\n    ```python\n    client.margin_v1_get_eth_staking_eth_history_staking_history(**params)\n    ```\n\n\t- **GET /papi/v1/um/conditional/openOrder**\n    ```python\n    client.papi_v1_get_um_conditional_open_order(**params)\n    ```\n\n\t- **GET /dapi/v1/openOrders**\n    ```python\n    client.futures_coin_v1_get_open_orders(**params)\n    ```\n\n\t- **GET /eapi/v1/order**\n    ```python\n    client.options_v1_get_order(**params)\n    ```\n\n\t- **POST /sapi/v1/convert/acceptQuote**\n    ```python\n    client.margin_v1_post_convert_accept_quote(**params)\n    ```\n\n\t- **GET /sapi/v1/staking/stakingRecord**\n    ```python\n    client.margin_v1_get_staking_staking_record(**params)\n    ```\n\n\t- **GET /sapi/v1/broker/rebate/recentRecord**\n    ```python\n    client.margin_v1_get_broker_rebate_recent_record(**params)\n    ```\n\n\t- **GET /eapi/v1/block/order/orders**\n    ```python\n    client.options_v1_get_block_order_orders(**params)\n    ```\n\n\t- **GET /sapi/v1/asset/transfer**\n    ```python\n    client.margin_v1_get_asset_transfer(**params)\n    ```\n\n\t- **GET /sapi/v1/loan/vip/collateral/account**\n    ```python\n    client.margin_v1_get_loan_vip_collateral_account(**params)\n    ```\n\n\t- **GET /sapi/v1/algo/spot/openOrders**\n    ```python\n    client.margin_v1_get_algo_spot_open_orders(**params)\n    ```\n\n\t- **POST /sapi/v1/loan/repay**\n    ```python\n    client.margin_v1_post_loan_repay(**params)\n    ```\n\n\t- **POST /sapi/v1/margin/isolated/account**\n    ```python\n    client.margin_v1_post_margin_isolated_account(**params)\n    ```\n\n\t- **GET /dapi/v1/fundingInfo**\n    ```python\n    client.futures_coin_v1_get_funding_info(**params)\n    ```\n\n\t- **GET /papi/v1/cm/leverageBracket**\n    ```python\n    client.papi_v1_get_cm_leverage_bracket(**params)\n    ```\n\n\t- **POST /sapi/v1/simple-earn/locked/subscribe**\n    ```python\n    client.margin_v1_post_simple_earn_locked_subscribe(**params)\n    ```\n\n\t- **GET /sapi/v1/margin/leverageBracket**\n    ```python\n    client.margin_v1_get_margin_leverage_bracket(**params)\n    ```\n\n\t- **GET /sapi/v2/portfolio/collateralRate**\n    ```python\n    client.margin_v2_get_portfolio_collateral_rate(**params)\n    ```\n\n\t- **POST /sapi/v2/loan/flexible/adjust/ltv**\n    ```python\n    client.margin_v2_post_loan_flexible_adjust_ltv(**params)\n    ```\n\n\t- **GET /sapi/v1/convert/orderStatus**\n    ```python\n    client.margin_v1_get_convert_order_status(**params)\n    ```\n\n\t- **POST /sapi/v1/margin/dust**\n    ```python\n    client.margin_v1_post_margin_dust(**params)\n    ```\n\n\t- **GET /sapi/v1/broker/subAccountApi/ipRestriction**\n    ```python\n    client.margin_v1_get_broker_sub_account_api_ip_restriction(**params)\n    ```\n\n\t- **GET /papi/v1/um/conditional/allOrders**\n    ```python\n    client.papi_v1_get_um_conditional_all_orders(**params)\n    ```\n\n\t- **PUT /eapi/v1/block/order/create**\n    ```python\n    client.options_v1_put_block_order_create(**params)\n    ```\n\n\t- **POST /sapi/v1/dci/product/subscribe**\n    ```python\n    client.margin_v1_post_dci_product_subscribe(**params)\n    ```\n\n\t- **GET /fapi/v1/income/asyn/id**\n    ```python\n    client.futures_v1_get_income_asyn_id(**params)\n    ```\n\n\t- **GET /dapi/v1/positionRisk**\n    ```python\n    client.futures_coin_v1_get_position_risk(**params)\n    ```\n\n\t- **POST /eapi/v1/countdownCancelAll**\n    ```python\n    client.options_v1_post_countdown_cancel_all(**params)\n    ```\n\n\t- **POST /papi/v1/repay-futures-switch**\n    ```python\n    client.papi_v1_post_repay_futures_switch(**params)\n    ```\n\n\t- **POST /sapi/v1/mining/hash-transfer/config/cancel**\n    ```python\n    client.margin_v1_post_mining_hash_transfer_config_cancel(**params)\n    ```\n\n\t- **GET /sapi/v1/broker/subAccount/depositHist**\n    ```python\n    client.margin_v1_get_broker_sub_account_deposit_hist(**params)\n    ```\n\n\t- **POST /eapi/v1/block/order/create**\n    ```python\n    client.options_v1_post_block_order_create(**params)\n    ```\n\n\t- **GET /sapi/v1/capital/deposit/subAddress**\n    ```python\n    client.margin_v1_get_capital_deposit_sub_address(**params)\n    ```\n\n\t- **GET /sapi/v1/mining/payment/list**\n    ```python\n    client.margin_v1_get_mining_payment_list(**params)\n    ```\n\n\t- **GET /fapi/v1/pmAccountInfo**\n    ```python\n    client.futures_v1_get_pm_account_info(**params)\n    ```\n\n\t- **GET /dapi/v1/adlQuantile**\n    ```python\n    client.futures_coin_v1_get_adl_quantile(**params)\n    ```\n\n\t- **GET /eapi/v1/income/asyn/id**\n    ```python\n    client.options_v1_get_income_asyn_id(**params)\n    ```\n\n\t- **POST /api/v3/cancelReplace**\n    ```python\n    client.v3_post_cancel_replace(**params)\n    ```\n\n\t- **PUT /papi/v1/um/order**\n    ```python\n    client.papi_v1_put_um_order(**params)\n    ```\n\n\t- **GET /sapi/v1/sub-account/futures/accountSummary**\n    ```python\n    client.margin_v1_get_sub_account_futures_account_summary(**params)\n    ```\n\n\t- **GET /papi/v1/um/symbolConfig**\n    ```python\n    client.papi_v1_get_um_symbol_config(**params)\n    ```\n\n\t- **GET /papi/v1/um/userTrades**\n    ```python\n    client.papi_v1_get_um_user_trades(**params)\n    ```\n\n\t- **GET /sapi/v1/staking/productList**\n    ```python\n    client.margin_v1_get_staking_product_list(**params)\n    ```\n\n\t- **POST /sapi/v1/asset/get-funding-asset**\n    ```python\n    client.margin_v1_post_asset_get_funding_asset(**params)\n    ```\n\n\t- **POST /sapi/v1/bnbBurn**\n    ```python\n    client.margin_v1_post_bnb_burn(**params)\n    ```\n\n\t- **POST /papi/v1/um/order**\n    ```python\n    client.papi_v1_post_um_order(**params)\n    ```\n\n\t- **GET /dapi/v1/order/asyn**\n    ```python\n    client.futures_coin_v1_get_order_asyn(**params)\n    ```\n\n\t- **GET /sapi/v1/c2c/orderMatch/listUserOrderHistory**\n    ```python\n    client.margin_v1_get_c2c_order_match_list_user_order_history(**params)\n    ```\n\n\t- **POST /sapi/v1/simple-earn/flexible/subscribe**\n    ```python\n    client.margin_v1_post_simple_earn_flexible_subscribe(**params)\n    ```\n\n\t- **POST /sapi/v1/broker/transfer/futures**\n    ```python\n    client.margin_v1_post_broker_transfer_futures(**params)\n    ```\n\n\t- **POST /api/v3/order/cancelReplace**\n    ```python\n    client.v3_post_order_cancel_replace(**params)\n    ```\n\n\t- **POST /sapi/v1/sol-staking/sol/stake**\n    ```python\n    client.margin_v1_post_sol_staking_sol_stake(**params)\n    ```\n\n\t- **POST /sapi/v1/loan/borrow**\n    ```python\n    client.margin_v1_post_loan_borrow(**params)\n    ```\n\n\t- **GET /sapi/v1/managed-subaccount/info**\n    ```python\n    client.margin_v1_get_managed_subaccount_info(**params)\n    ```\n\n\t- **POST /sapi/v1/lending/auto-invest/plan/edit-status**\n    ```python\n    client.margin_v1_post_lending_auto_invest_plan_edit_status(**params)\n    ```\n\n\t- **GET /fapi/v1/symbolConfig**\n    ```python\n    client.futures_v1_get_symbol_config(**params)\n    ```\n\n\t- **GET /sapi/v1/sol-staking/sol/history/unclaimedRewards**\n    ```python\n    client.margin_v1_get_sol_staking_sol_history_unclaimed_rewards(**params)\n    ```\n\n\t- **POST /sapi/v1/asset/convert-transfer/queryByPage**\n    ```python\n    client.margin_v1_post_asset_convert_transfer_query_by_page(**params)\n    ```\n\n\t- **GET /sapi/v1/sub-account/universalTransfer**\n    ```python\n    client.margin_v1_get_sub_account_universal_transfer(**params)\n    ```\n\n\t- **GET /sapi/v1/sol-staking/sol/history/boostRewardsHistory**\n    ```python\n    client.margin_v1_get_sol_staking_sol_history_boost_rewards_history(**params)\n    ```\n\n\t- **GET /sapi/v1/lending/auto-invest/one-off/status**\n    ```python\n    client.margin_v1_get_lending_auto_invest_one_off_status(**params)\n    ```\n\n\t- **GET /sapi/v1/asset/ledger-transfer/cloud-mining/queryByPage**\n    ```python\n    client.margin_v1_get_asset_ledger_transfer_cloud_mining_query_by_page(**params)\n    ```\n\n\t- **DELETE /sapi/v1/margin/orderList**\n    ```python\n    client.margin_v1_delete_margin_order_list(**params)\n    ```\n\n\t- **GET /sapi/v1/mining/pub/coinList**\n    ```python\n    client.margin_v1_get_mining_pub_coin_list(**params)\n    ```\n\n\t- **GET /sapi/v2/loan/flexible/repay/history**\n    ```python\n    client.margin_v2_get_loan_flexible_repay_history(**params)\n    ```\n\n\t- **GET /fapi/v3/account**\n    ```python\n    client.futures_v3_get_account(**params)\n    ```\n\n\t- **POST /api/v3/sor/order**\n    ```python\n    client.v3_post_sor_order(**params)\n    ```\n\n\t- **POST /sapi/v1/capital/deposit/credit-apply**\n    ```python\n    client.margin_v1_post_capital_deposit_credit_apply(**params)\n    ```\n\n\t- **PUT /fapi/v1/batchOrder**\n    ```python\n    client.futures_v1_put_batch_order(**params)\n    ```\n\n\t- **GET /sapi/v1/fiat/payments**\n    ```python\n    client.margin_v1_get_fiat_payments(**params)\n    ```\n\n\t- **GET /api/v3/myPreventedMatches**\n    ```python\n    client.v3_get_my_prevented_matches(**params)\n    ```\n\n\t- **GET /dapi/v1/forceOrders**\n    ```python\n    client.futures_coin_v1_get_force_orders(**params)\n    ```\n\n\t- **POST /sapi/v1/asset/transfer**\n    ```python\n    client.margin_v1_post_asset_transfer(**params)\n    ```\n\n\t- **GET /sapi/v1/mining/statistics/user/list**\n    ```python\n    client.margin_v1_get_mining_statistics_user_list(**params)\n    ```\n\n\t- **GET /api/v3/ticker/tradingDay**\n    ```python\n    client.v3_get_ticker_trading_day(**params)\n    ```\n\n\t- **GET /sapi/v1/mining/worker/detail**\n    ```python\n    client.margin_v1_get_mining_worker_detail(**params)\n    ```\n\n\t- **GET /sapi/v1/managed-subaccount/fetch-future-asset**\n    ```python\n    client.margin_v1_get_managed_subaccount_fetch_future_asset(**params)\n    ```\n\n\t- **GET /dapi/v1/pmExchangeInfo**\n    ```python\n    client.futures_coin_v1_get_pm_exchange_info(**params)\n    ```\n\n\t- **POST /sapi/v1/convert/getQuote**\n    ```python\n    client.margin_v1_post_convert_get_quote(**params)\n    ```\n\n\t- **GET /api/v3/uiKlines**\n    ```python\n    client.v3_get_ui_klines(**params)\n    ```\n\n\t- **GET /sapi/v1/margin/rateLimit/order**\n    ```python\n    client.margin_v1_get_margin_rate_limit_order(**params)\n    ```\n\n\t- **GET /sapi/v1/localentity/vasp**\n    ```python\n    client.margin_v1_get_localentity_vasp(**params)\n    ```\n\n\t- **GET /fapi/v1/commissionRate**\n    ```python\n    client.futures_v1_get_commission_rate(**params)\n    ```\n\n\t- **GET /sapi/v1/sol-staking/sol/history/rateHistory**\n    ```python\n    client.margin_v1_get_sol_staking_sol_history_rate_history(**params)\n    ```\n\n\t- **POST /sapi/v1/broker/subAccountApi/ipRestriction**\n    ```python\n    client.margin_v1_post_broker_sub_account_api_ip_restriction(**params)\n    ```\n\n\t- **GET /eapi/v1/block/user-trades**\n    ```python\n    client.options_v1_get_block_user_trades(**params)\n    ```\n\n\t- **GET /dapi/v1/order/asyn/id**\n    ```python\n    client.futures_coin_v1_get_order_asyn_id(**params)\n    ```\n\n\t- **GET /sapi/v1/sol-staking/account**\n    ```python\n    client.margin_v1_get_sol_staking_account(**params)\n    ```\n\n\t- **GET /sapi/v1/account/info**\n    ```python\n    client.margin_v1_get_account_info(**params)\n    ```\n\n\t- **POST /sapi/v1/sub-account/transfer/subToMaster**\n    ```python\n    client.margin_v1_post_sub_account_transfer_sub_to_master(**params)\n    ```\n\n\t- **POST /sapi/v1/portfolio/repay-futures-switch**\n    ```python\n    client.margin_v1_post_portfolio_repay_futures_switch(**params)\n    ```\n\n\t- **GET /sapi/v1/giftcard/buyCode/token-limit**\n    ```python\n    client.margin_v1_get_giftcard_buy_code_token_limit(**params)\n    ```\n\n\t- **GET /sapi/v1/capital/deposit/subHisrec**\n    ```python\n    client.margin_v1_get_capital_deposit_sub_hisrec(**params)\n    ```\n\n\t- **POST /sapi/v1/loan/vip/borrow**\n    ```python\n    client.margin_v1_post_loan_vip_borrow(**params)\n    ```\n\n\t- **GET /papi/v1/um/order/asyn/id**\n    ```python\n    client.papi_v1_get_um_order_asyn_id(**params)\n    ```\n\n\t- **GET /papi/v1/cm/account**\n    ```python\n    client.papi_v1_get_cm_account(**params)\n    ```\n\n\t- **DELETE /papi/v1/um/conditional/order**\n    ```python\n    client.papi_v1_delete_um_conditional_order(**params)\n    ```\n\n\t- **GET /sapi/v2/loan/flexible/ltv/adjustment/history**\n    ```python\n    client.margin_v2_get_loan_flexible_ltv_adjustment_history(**params)\n    ```\n\n\t- **DELETE /eapi/v1/allOpenOrdersByUnderlying**\n    ```python\n    client.options_v1_delete_all_open_orders_by_underlying(**params)\n    ```\n\n\t- **PUT /papi/v1/cm/order**\n    ```python\n    client.papi_v1_put_cm_order(**params)\n    ```\n\n\t- **GET /sapi/v1/broker/subAccount/futuresSummary**\n    ```python\n    client.margin_v1_get_broker_sub_account_futures_summary(**params)\n    ```\n\n\t- **GET /dapi/v1/continuousKlines**\n    ```python\n    client.futures_coin_v1_get_continuous_klines(**params)\n    ```\n\n\t- **GET /fapi/v1/accountConfig**\n    ```python\n    client.futures_v1_get_account_config(**params)\n    ```\n\n\t- **DELETE /dapi/v1/batchOrders**\n    ```python\n    client.futures_coin_v1_delete_batch_orders(**params)\n    ```\n\n\t- **GET /sapi/v1/broker/subAccount/spotSummary**\n    ```python\n    client.margin_v1_get_broker_sub_account_spot_summary(**params)\n    ```\n\n\t- **GET /papi/v1/margin/openOrderList**\n    ```python\n    client.papi_v1_get_margin_open_order_list(**params)\n    ```\n\n\t- **POST /sapi/v1/sub-account/blvt/enable**\n    ```python\n    client.margin_v1_post_sub_account_blvt_enable(**params)\n    ```\n\n\t- **GET /dapi/v1/trade/asyn**\n    ```python\n    client.futures_coin_v1_get_trade_asyn(**params)\n    ```\n\n\t- **GET /sapi/v1/algo/spot/historicalOrders**\n    ```python\n    client.margin_v1_get_algo_spot_historical_orders(**params)\n    ```\n\n\t- **GET /sapi/v1/loan/vip/repay/history**\n    ```python\n    client.margin_v1_get_loan_vip_repay_history(**params)\n    ```\n\n\t- **GET /eapi/v1/openInterest**\n    ```python\n    client.options_v1_get_open_interest(**params)\n    ```\n\n\t- **GET /papi/v1/um/adlQuantile**\n    ```python\n    client.papi_v1_get_um_adl_quantile(**params)\n    ```\n\n\t- **GET /eapi/v1/account**\n    ```python\n    client.options_v1_get_account(**params)\n    ```\n\n\t- **POST /sapi/v1/sub-account/universalTransfer**\n    ```python\n    client.margin_v1_post_sub_account_universal_transfer(**params)\n    ```\n\n\t- **GET /papi/v1/margin/allOrderList**\n    ```python\n    client.papi_v1_get_margin_all_order_list(**params)\n    ```\n\n\t- **GET /fapi/v2/ticker/price**\n    ```python\n    client.futures_v2_get_ticker_price(**params)\n    ```\n\n\t- **GET /sapi/v1/loan/borrow/history**\n    ```python\n    client.margin_v1_get_loan_borrow_history(**params)\n    ```\n\n\t- **GET /papi/v1/um/account**\n    ```python\n    client.papi_v1_get_um_account(**params)\n    ```\n\n\t- **POST /sapi/v1/lending/auto-invest/redeem**\n    ```python\n    client.margin_v1_post_lending_auto_invest_redeem(**params)\n    ```\n\n\t- **POST /sapi/v1/managed-subaccount/deposit**\n    ```python\n    client.margin_v1_post_managed_subaccount_deposit(**params)\n    ```\n\n\t- **GET /dapi/v1/fundingRate**\n    ```python\n    client.futures_coin_v1_get_funding_rate(**params)\n    ```\n\n\t- **GET /fapi/v1/trade/asyn/id**\n    ```python\n    client.futures_v1_get_trade_asyn_id(**params)\n    ```\n\n\t- **DELETE /sapi/v1/sub-account/subAccountApi/ipRestriction/ipList**\n    ```python\n    client.margin_v1_delete_sub_account_sub_account_api_ip_restriction_ip_list(**params)\n    ```\n\n\t- **GET /sapi/v1/copyTrading/futures/userStatus**\n    ```python\n    client.margin_v1_get_copy_trading_futures_user_status(**params)\n    ```\n\n\t- **GET /papi/v1/um/income**\n    ```python\n    client.papi_v1_get_um_income(**params)\n    ```\n\n\t- **GET /papi/v1/um/openOrders**\n    ```python\n    client.papi_v1_get_um_open_orders(**params)\n    ```\n\n\t- **GET /eapi/v1/marginAccount**\n    ```python\n    client.options_v1_get_margin_account(**params)\n    ```\n\n\t- **GET /dapi/v1/premiumIndex**\n    ```python\n    client.futures_coin_v1_get_premium_index(**params)\n    ```\n\n\t- **POST /sapi/v1/localentity/withdraw/apply**\n    ```python\n    client.margin_v1_post_localentity_withdraw_apply(**params)\n    ```\n\n\t- **GET /sapi/v1/margin/orderList**\n    ```python\n    client.margin_v1_get_margin_order_list(**params)\n    ```\n\n\t- **GET /papi/v1/um/feeBurn**\n    ```python\n    client.papi_v1_get_um_fee_burn(**params)\n    ```\n\n\t- **GET /fapi/v1/multiAssetsMargin**\n    ```python\n    client.futures_v1_get_multi_assets_margin(**params)\n    ```\n\n\t- **GET /sapi/v1/giftcard/verify**\n    ```python\n    client.margin_v1_get_giftcard_verify(**params)\n    ```\n\n\t- **GET /sapi/v1/asset/wallet/balance**\n    ```python\n    client.margin_v1_get_asset_wallet_balance(**params)\n    ```\n\n\t- **POST /sapi/v1/algo/futures/newOrderTwap**\n    ```python\n    client.margin_v1_post_algo_futures_new_order_twap(**params)\n    ```\n\n\t- **GET /sapi/v1/margin/crossMarginCollateralRatio**\n    ```python\n    client.margin_v1_get_margin_cross_margin_collateral_ratio(**params)\n    ```\n\n\t- **POST /sapi/v2/eth-staking/eth/stake**\n    ```python\n    client.margin_v2_post_eth_staking_eth_stake(**params)\n    ```\n\n\t- **POST /sapi/v1/loan/flexible/repay/history**\n    ```python\n    client.margin_v1_post_loan_flexible_repay_history(**params)\n    ```\n\n\t- **GET /dapi/v1/exchangeInfo**\n    ```python\n    client.futures_coin_v1_get_exchange_info(**params)\n    ```\n\n\t- **POST /sapi/v1/sub-account/futures/enable**\n    ```python\n    client.margin_v1_post_sub_account_futures_enable(**params)\n    ```\n\n\t- **GET /sapi/v1/lending/auto-invest/index/info**\n    ```python\n    client.margin_v1_get_lending_auto_invest_index_info(**params)\n    ```\n\n\t- **GET /sapi/v2/sub-account/futures/positionRisk**\n    ```python\n    client.margin_v2_get_sub_account_futures_position_risk(**params)\n    ```\n\n\t- **GET /sapi/v1/sub-account/margin/account**\n    ```python\n    client.margin_v1_get_sub_account_margin_account(**params)\n    ```\n\n\t- **GET /papi/v1/rateLimit/order**\n    ```python\n    client.papi_v1_get_rate_limit_order(**params)\n    ```\n\n\t- **GET /sapi/v1/sol-staking/sol/history/redemptionHistory**\n    ```python\n    client.margin_v1_get_sol_staking_sol_history_redemption_history(**params)\n    ```\n\n\t- **GET /fapi/v1/markPriceKlines**\n    ```python\n    client.futures_v1_get_mark_price_klines(**params)\n    ```\n\n\t- **GET /sapi/v1/broker/rebate/futures/recentRecord**\n    ```python\n    client.margin_v1_get_broker_rebate_futures_recent_record(**params)\n    ```\n\n\t- **GET /sapi/v3/broker/subAccount/futuresSummary**\n    ```python\n    client.margin_v3_get_broker_sub_account_futures_summary(**params)\n    ```\n\n\t- **GET /dapi/v1/aggTrades**\n    ```python\n    client.futures_coin_v1_get_agg_trades(**params)\n    ```\n\n\t- **GET /eapi/v1/exchangeInfo**\n    ```python\n    client.options_v1_get_exchange_info(**params)\n    ```\n\n\t- **GET /sapi/v1/lending/auto-invest/target-asset/roi/list**\n    ```python\n    client.margin_v1_get_lending_auto_invest_target_asset_roi_list(**params)\n    ```\n\n\t- **GET /sapi/v1/broker/universalTransfer**\n    ```python\n    client.margin_v1_get_broker_universal_transfer(**params)\n    ```\n\n\t- **POST /sapi/v1/sub-account/futures/transfer**\n    ```python\n    client.margin_v1_post_sub_account_futures_transfer(**params)\n    ```\n\n\t- **PUT /fapi/v1/batchOrders**\n    ```python\n    client.futures_v1_put_batch_orders(**params)\n    ```\n\n\t- **POST /eapi/v1/countdownCancelAllHeartBeat**\n    ```python\n    client.options_v1_post_countdown_cancel_all_heart_beat(**params)\n    ```\n\n\t- **GET /sapi/v1/loan/collateral/data**\n    ```python\n    client.margin_v1_get_loan_collateral_data(**params)\n    ```\n\n\t- **GET /sapi/v1/margin/borrow-repay**\n    ```python\n    client.margin_v1_get_margin_borrow_repay(**params)\n    ```\n\n\t- **GET /sapi/v1/loan/repay/history**\n    ```python\n    client.margin_v1_get_loan_repay_history(**params)\n    ```\n\n\t- **GET /dapi/v2/leverageBracket**\n    ```python\n    client.futures_coin_v2_get_leverage_bracket(**params)\n    ```\n\n\t- **GET /fapi/v1/indexPriceKlines**\n    ```python\n    client.futures_v1_get_index_price_klines(**params)\n    ```\n\n\t- **POST /sapi/v1/convert/limit/placeOrder**\n    ```python\n    client.margin_v1_post_convert_limit_place_order(**params)\n    ```\n\n\t- **GET /fapi/v1/convert/exchangeInfo**\n    ```python\n    client.futures_v1_get_convert_exchange_info(**params)\n    ```\n\n\t- **GET /dapi/v1/historicalTrades**\n    ```python\n    client.futures_coin_v1_get_historical_trades(**params)\n    ```\n\n\t- **DELETE /sapi/v1/broker/subAccountApi/ipRestriction/ipList**\n    ```python\n    client.margin_v1_delete_broker_sub_account_api_ip_restriction_ip_list(**params)\n    ```\n\n\t- **GET /sapi/v1/staking/personalLeftQuota**\n    ```python\n    client.margin_v1_get_staking_personal_left_quota(**params)\n    ```\n\n\t- **POST /sapi/v1/sub-account/virtualSubAccount**\n    ```python\n    client.margin_v1_post_sub_account_virtual_sub_account(**params)\n    ```\n\n\t- **GET /sapi/v1/staking/position**\n    ```python\n    client.margin_v1_get_staking_position(**params)\n    ```\n\n\t- **GET /papi/v1/um/income/asyn/id**\n    ```python\n    client.papi_v1_get_um_income_asyn_id(**params)\n    ```\n\n\t- **PUT /sapi/v1/localentity/deposit/provide-info**\n    ```python\n    client.margin_v1_put_localentity_deposit_provide_info(**params)\n    ```\n\n\t- **POST /sapi/v1/portfolio/mint**\n    ```python\n    client.margin_v1_post_portfolio_mint(**params)\n    ```\n\n\t- **POST /sapi/v1/sub-account/transfer/subToSub**\n    ```python\n    client.margin_v1_post_sub_account_transfer_sub_to_sub(**params)\n    ```\n\n\t- **GET /fapi/v1/orderAmendment**\n    ```python\n    client.futures_v1_get_order_amendment(**params)\n    ```\n\n\t- **POST /sapi/v1/sol-staking/sol/claim**\n    ```python\n    client.margin_v1_post_sol_staking_sol_claim(**params)\n    ```\n\n\t- **GET /sapi/v1/account/apiRestrictions**\n    ```python\n    client.margin_v1_get_account_api_restrictions(**params)\n    ```\n\n\t- **GET /papi/v1/um/allOrders**\n    ```python\n    client.papi_v1_get_um_all_orders(**params)\n    ```\n\n\t- **POST /sapi/v1/giftcard/createCode**\n    ```python\n    client.margin_v1_post_giftcard_create_code(**params)\n    ```\n\n\t- **GET /sapi/v1/lending/auto-invest/rebalance/history**\n    ```python\n    client.margin_v1_get_lending_auto_invest_rebalance_history(**params)\n    ```\n\n\t- **GET /sapi/v1/loan/repay/collateral/rate**\n    ```python\n    client.margin_v1_get_loan_repay_collateral_rate(**params)\n    ```\n\n\t- **GET /sapi/v1/mining/payment/uid**\n    ```python\n    client.margin_v1_get_mining_payment_uid(**params)\n    ```\n\n\t- **GET /sapi/v2/loan/flexible/borrow/history**\n    ```python\n    client.margin_v2_get_loan_flexible_borrow_history(**params)\n    ```\n\n\t- **POST /sapi/v1/asset/dust**\n    ```python\n    client.margin_v1_post_asset_dust(**params)\n    ```\n\n\t- **GET /sapi/v1/capital/contract/convertible-coins**\n    ```python\n    client.margin_v1_get_capital_contract_convertible_coins(**params)\n    ```\n\n\t- **POST /sapi/v1/asset/dust-btc**\n    ```python\n    client.margin_v1_post_asset_dust_btc(**params)\n    ```\n\n\t- **GET /papi/v1/um/conditional/openOrders**\n    ```python\n    client.papi_v1_get_um_conditional_open_orders(**params)\n    ```\n\n\t- **GET /sapi/v1/sub-account/spotSummary**\n    ```python\n    client.margin_v1_get_sub_account_spot_summary(**params)\n    ```\n\n\t- **POST /sapi/v1/broker/subAccountApi/permission/vanillaOptions**\n    ```python\n    client.margin_v1_post_broker_sub_account_api_permission_vanilla_options(**params)\n    ```\n\n\t- **GET /sapi/v1/lending/auto-invest/redeem/history**\n    ```python\n    client.margin_v1_get_lending_auto_invest_redeem_history(**params)\n    ```\n\n\t- **GET /fapi/v3/positionRisk**\n    ```python\n    client.futures_v3_get_position_risk(**params)\n    ```\n\n\t- **GET /dapi/v1/klines**\n    ```python\n    client.futures_coin_v1_get_klines(**params)\n    ```\n\n\t- **GET /sapi/v2/localentity/withdraw/history**\n    ```python\n    client.margin_v2_get_localentity_withdraw_history(**params)\n    ```\n\n\t- **GET /sapi/v1/eth-staking/eth/history/redemptionHistory**\n    ```python\n    client.margin_v1_get_eth_staking_eth_history_redemption_history(**params)\n    ```\n\n\t- **POST /eapi/v1/transfer**\n    ```python\n    client.options_v1_post_transfer(**params)\n    ```\n\n\t- **GET /fapi/v1/feeBurn**\n    ```python\n    client.futures_v1_get_fee_burn(**params)\n    ```\n\n\t- **GET /sapi/v1/lending/auto-invest/index/user-summary**\n    ```python\n    client.margin_v1_get_lending_auto_invest_index_user_summary(**params)\n    ```\n\n\t- **POST /sapi/v2/loan/flexible/borrow**\n    ```python\n    client.margin_v2_post_loan_flexible_borrow(**params)\n    ```\n\n\t- **DELETE /dapi/v1/order**\n    ```python\n    client.futures_coin_v1_delete_order(**params)\n    ```\n\n\t- **POST /sapi/v3/asset/getUserAsset**\n    ```python\n    client.margin_v3_post_asset_get_user_asset(**params)\n    ```\n\n\t- **POST /sapi/v1/loan/vip/repay**\n    ```python\n    client.margin_v1_post_loan_vip_repay(**params)\n    ```\n\n\t- **GET /sapi/v2/sub-account/futures/accountSummary**\n    ```python\n    client.margin_v2_get_sub_account_futures_account_summary(**params)\n    ```\n\n\t- **GET /dapi/v1/commissionRate**\n    ```python\n    client.futures_coin_v1_get_commission_rate(**params)\n    ```\n\n\t- **GET /papi/v1/um/conditional/orderHistory**\n    ```python\n    client.papi_v1_get_um_conditional_order_history(**params)\n    ```\n\n\t- **GET /fapi/v3/balance**\n    ```python\n    client.futures_v3_get_balance(**params)\n    ```\n\n\t- **GET /sapi/v1/convert/assetInfo**\n    ```python\n    client.margin_v1_get_convert_asset_info(**params)\n    ```\n\n\t- **POST /api/v3/sor/order/test**\n    ```python\n    client.v3_post_sor_order_test(**params)\n    ```\n\n\t- **GET /sapi/v1/giftcard/cryptography/rsa-public-key**\n    ```python\n    client.margin_v1_get_giftcard_cryptography_rsa_public_key(**params)\n    ```\n\n\t- **POST /sapi/v1/broker/universalTransfer**\n    ```python\n    client.margin_v1_post_broker_universal_transfer(**params)\n    ```\n\n\t- **GET /dapi/v1/allOrders**\n    ```python\n    client.futures_coin_v1_get_all_orders(**params)\n    ```\n\n\t- **POST /sapi/v1/margin/borrow-repay**\n    ```python\n    client.margin_v1_post_margin_borrow_repay(**params)\n    ```\n\n\t- **GET /fapi/v1/assetIndex**\n    ```python\n    client.futures_v1_get_asset_index(**params)\n    ```\n\n\t- **GET /api/v3/rateLimit/order**\n    ```python\n    client.v3_get_rate_limit_order(**params)\n    ```\n\n\t- **GET /papi/v1/um/orderAmendment**\n    ```python\n    client.papi_v1_get_um_order_amendment(**params)\n    ```\n\n\t- **GET /sapi/v1/account/apiRestrictions/ipRestriction**\n    ```python\n    client.margin_v1_get_account_api_restrictions_ip_restriction(**params)\n    ```\n\n\t- **POST /sapi/v1/broker/subAccount/bnbBurn/spot**\n    ```python\n    client.margin_v1_post_broker_sub_account_bnb_burn_spot(**params)\n    ```\n\n\t- **POST /papi/v1/um/conditional/order**\n    ```python\n    client.papi_v1_post_um_conditional_order(**params)\n    ```\n\n\t- **PUT /dapi/v1/batchOrders**\n    ```python\n    client.futures_coin_v1_put_batch_orders(**params)\n    ```\n\n\t- **DELETE /api/v3/openOrders**\n    ```python\n    client.v3_delete_open_orders(**params)\n    ```\n\n\t- **GET /sapi/v1/margin/delist-schedule**\n    ```python\n    client.margin_v1_get_margin_delist_schedule(**params)\n    ```\n\n\t- **POST /sapi/v1/broker/subAccountApi/permission/universalTransfer**\n    ```python\n    client.margin_v1_post_broker_sub_account_api_permission_universal_transfer(**params)\n    ```\n\n\t- **GET /papi/v1/cm/positionRisk**\n    ```python\n    client.papi_v1_get_cm_position_risk(**params)\n    ```\n\n\t- **GET /papi/v1/cm/income**\n    ```python\n    client.papi_v1_get_cm_income(**params)\n    ```\n\n\t- **POST /sapi/v1/giftcard/buyCode**\n    ```python\n    client.margin_v1_post_giftcard_buy_code(**params)\n    ```\n\n\t- **GET /fapi/v1/balance**\n    ```python\n    client.futures_v1_get_balance(**params)\n    ```\n\n\t- **GET /api/v3/myAllocations**\n    ```python\n    client.v3_get_my_allocations(**params)\n    ```\n\n\t- **GET /papi/v1/margin/order**\n    ```python\n    client.papi_v1_get_margin_order(**params)\n    ```\n\n\t- **GET /sapi/v1/loan/ltv/adjustment/history**\n    ```python\n    client.margin_v1_get_loan_ltv_adjustment_history(**params)\n    ```\n\n\t- **POST /dapi/v1/batchOrders**\n    ```python\n    client.futures_coin_v1_post_batch_orders(**params)\n    ```\n\n\t- **GET /sapi/v1/localentity/withdraw/history**\n    ```python\n    client.margin_v1_get_localentity_withdraw_history(**params)\n    ```\n\n\t- **GET /sapi/v1/sub-account/status**\n    ```python\n    client.margin_v1_get_sub_account_status(**params)\n    ```\n\n\t- **POST /sapi/v2/sub-account/subAccountApi/ipRestriction**\n    ```python\n    client.margin_v2_post_sub_account_sub_account_api_ip_restriction(**params)\n    ```\n\n\t- **GET /dapi/v1/trade/asyn/id**\n    ```python\n    client.futures_coin_v1_get_trade_asyn_id(**params)\n    ```\n\n\t- **GET /fapi/v1/rateLimit/order**\n    ```python\n    client.futures_v1_get_rate_limit_order(**params)\n    ```\n\n\t- **GET /sapi/v1/broker/subAccountApi/commission/futures**\n    ```python\n    client.margin_v1_get_broker_sub_account_api_commission_futures(**params)\n    ```\n\n\t- **GET /sapi/v1/sol-staking/sol/history/stakingHistory**\n    ```python\n    client.margin_v1_get_sol_staking_sol_history_staking_history(**params)\n    ```\n\n\t- **DELETE /sapi/v1/algo/spot/order**\n    ```python\n    client.margin_v1_delete_algo_spot_order(**params)\n    ```\n\n\t- **GET /papi/v1/repay-futures-switch**\n    ```python\n    client.papi_v1_get_repay_futures_switch(**params)\n    ```\n\n\t- **POST /sapi/v1/margin/max-leverage**\n    ```python\n    client.margin_v1_post_margin_max_leverage(**params)\n    ```\n\n\t- **DELETE /sapi/v1/account/apiRestrictions/ipRestriction/ipList**\n    ```python\n    client.margin_v1_delete_account_api_restrictions_ip_restriction_ip_list(**params)\n    ```\n\n\t- **POST /sapi/v1/capital/contract/convertible-coins**\n    ```python\n    client.margin_v1_post_capital_contract_convertible_coins(**params)\n    ```\n\n\t- **GET /sapi/v1/managed-subaccount/marginAsset**\n    ```python\n    client.margin_v1_get_managed_subaccount_margin_asset(**params)\n    ```\n\n\t- **GET /sapi/v3/sub-account/assets**\n    ```python\n    client.margin_v3_get_sub_account_assets(**params)\n    ```\n\n\t- **GET /fapi/v1/continuousKlines**\n    ```python\n    client.futures_v1_get_continuous_klines(**params)\n    ```\n\n\t- **GET /sapi/v1/sub-account/futures/internalTransfer**\n    ```python\n    client.margin_v1_get_sub_account_futures_internal_transfer(**params)\n    ```\n\n\t- **GET /sapi/v1/capital/withdraw/apply**\n    ```python\n    client.margin_v1_get_capital_withdraw_apply(**params)\n    ```\n\n\t- **POST /sapi/v1/sub-account/subAccountApi/ipRestriction/ipList**\n    ```python\n    client.margin_v1_post_sub_account_sub_account_api_ip_restriction_ip_list(**params)\n    ```\n\n\t- **POST /sapi/v1/staking/setAutoStaking**\n    ```python\n    client.margin_v1_post_staking_set_auto_staking(**params)\n    ```\n\n\t- **POST /fapi/v1/feeBurn**\n    ```python\n    client.futures_v1_post_fee_burn(**params)\n    ```\n\n\t- **POST /sapi/v1/simple-earn/flexible/redeem**\n    ```python\n    client.margin_v1_post_simple_earn_flexible_redeem(**params)\n    ```\n\n\t- **GET /sapi/v1/broker/subAccount/marginSummary**\n    ```python\n    client.margin_v1_get_broker_sub_account_margin_summary(**params)\n    ```\n\n\t- **GET /sapi/v1/lending/auto-invest/plan/list**\n    ```python\n    client.margin_v1_get_lending_auto_invest_plan_list(**params)\n    ```\n\n\t- **GET /sapi/v1/loan/vip/loanable/data**\n    ```python\n    client.margin_v1_get_loan_vip_loanable_data(**params)\n    ```\n\n\t- **POST /sapi/v1/margin/exchange-small-liability**\n    ```python\n    client.margin_v1_post_margin_exchange_small_liability(**params)\n    ```\n\n\t- **GET /sapi/v2/loan/flexible/collateral/data**\n    ```python\n    client.margin_v2_get_loan_flexible_collateral_data(**params)\n    ```\n\n\t- **POST /papi/v1/margin/repay-debt**\n    ```python\n    client.papi_v1_post_margin_repay_debt(**params)\n    ```\n\n\t- **GET /sapi/v1/sol-staking/sol/history/bnsolRewardsHistory**\n    ```python\n    client.margin_v1_get_sol_staking_sol_history_bnsol_rewards_history(**params)\n    ```\n\n\t- **GET /sapi/v1/convert/limit/queryOpenOrders**\n    ```python\n    client.margin_v1_get_convert_limit_query_open_orders(**params)\n    ```\n\n\t- **GET /api/v3/account/commission**\n    ```python\n    client.v3_get_account_commission(**params)\n    ```\n\n\t- **GET /sapi/v1/margin/interestRateHistory**\n    ```python\n    client.margin_v1_get_margin_interest_rate_history(**params)\n    ```\n\n\t- **POST /api/v3/orderList/oco**\n    ```python\n    client.v3_post_order_list_oco(**params)\n    ```\n\n\t- **GET /sapi/v1/managed-subaccount/query-trans-log**\n    ```python\n    client.margin_v1_get_managed_subaccount_query_trans_log(**params)\n    ```\n\n\t- **POST /sapi/v2/broker/subAccountApi/ipRestriction**\n    ```python\n    client.margin_v2_post_broker_sub_account_api_ip_restriction(**params)\n    ```\n\n\t- **GET /papi/v1/um/positionRisk**\n    ```python\n    client.papi_v1_get_um_position_risk(**params)\n    ```\n\n\t- **POST /sapi/v1/sub-account/margin/transfer**\n    ```python\n    client.margin_v1_post_sub_account_margin_transfer(**params)\n    ```\n\n\t- **GET /fapi/v1/positionRisk**\n    ```python\n    client.futures_v1_get_position_risk(**params)\n    ```\n\n\t- **GET /sapi/v1/lending/auto-invest/all/asset**\n    ```python\n    client.margin_v1_get_lending_auto_invest_all_asset(**params)\n    ```\n\n\t- **POST /fapi/v1/convert/acceptQuote**\n    ```python\n    client.futures_v1_post_convert_accept_quote(**params)\n    ```\n\n\t- **GET /sapi/v1/spot/delist-schedule**\n    ```python\n    client.margin_v1_get_spot_delist_schedule(**params)\n    ```\n\n\t- **GET /sapi/v1/dci/product/accounts**\n    ```python\n    client.margin_v1_get_dci_product_accounts(**params)\n    ```\n\n\t- **GET /sapi/v1/sub-account/subAccountApi/ipRestriction**\n    ```python\n    client.margin_v1_get_sub_account_sub_account_api_ip_restriction(**params)\n    ```\n\n\t- **GET /papi/v1/um/accountConfig**\n    ```python\n    client.papi_v1_get_um_account_config(**params)\n    ```\n\n\t- **GET /papi/v1/cm/adlQuantile**\n    ```python\n    client.papi_v1_get_cm_adl_quantile(**params)\n    ```\n\n\t- **GET /sapi/v1/sub-account/transaction-statistics**\n    ```python\n    client.margin_v1_get_sub_account_transaction_statistics(**params)\n    ```\n\n\t- **PUT /fapi/v1/listenKey**\n    ```python\n    client.futures_v1_put_listen_key(**params)\n    ```\n\n\t- **GET /sapi/v1/margin/openOrderList**\n    ```python\n    client.margin_v1_get_margin_open_order_list(**params)\n    ```\n\n\t- **GET /api/v3/acccount**\n    ```python\n    client.v3_get_acccount(**params)\n    ```\n\n\t- **GET /sapi/v1/fiat/orders**\n    ```python\n    client.margin_v1_get_fiat_orders(**params)\n    ```\n\n\t- **GET /papi/v1/margin/allOrders**\n    ```python\n    client.papi_v1_get_margin_all_orders(**params)\n    ```\n\n\t- **POST /sapi/v1/sub-account/margin/enable**\n    ```python\n    client.margin_v1_post_sub_account_margin_enable(**params)\n    ```\n\n\t- **GET /sapi/v1/managed-subaccount/deposit/address**\n    ```python\n    client.margin_v1_get_managed_subaccount_deposit_address(**params)\n    ```\n\n\t- **DELETE /sapi/v1/margin/isolated/account**\n    ```python\n    client.margin_v1_delete_margin_isolated_account(**params)\n    ```\n\n\t- **GET /sapi/v2/portfolio/account**\n    ```python\n    client.margin_v2_get_portfolio_account(**params)\n    ```\n\n\t- **GET /sapi/v1/simple-earn/locked/history/redemptionRecord**\n    ```python\n    client.margin_v1_get_simple_earn_locked_history_redemption_record(**params)\n    ```\n\n\t- **GET /fapi/v1/order/asyn/id**\n    ```python\n    client.futures_v1_get_order_asyn_id(**params)\n    ```\n\n\t- **POST /sapi/v1/managed-subaccount/withdraw**\n    ```python\n    client.margin_v1_post_managed_subaccount_withdraw(**params)\n    ```\n\n\t- **GET /sapi/v1/convert/tradeFlow**\n    ```python\n    client.margin_v1_get_convert_trade_flow(**params)\n    ```\n\n\t- **GET /sapi/v1/localentity/deposit/history**\n    ```python\n    client.margin_v1_get_localentity_deposit_history(**params)\n    ```\n\n\t- **POST /sapi/v1/eth-staking/wbeth/wrap**\n    ```python\n    client.margin_v1_post_eth_staking_wbeth_wrap(**params)\n    ```\n\n\t- **POST /sapi/v1/simple-earn/locked/setRedeemOption**\n    ```python\n    client.margin_v1_post_simple_earn_locked_set_redeem_option(**params)\n    ```\n\n\t- **POST /sapi/v1/broker/subAccountApi/ipRestriction/ipList**\n    ```python\n    client.margin_v1_post_broker_sub_account_api_ip_restriction_ip_list(**params)\n    ```\n\n\t- **POST /sapi/v1/broker/subAccountApi/commission/futures**\n    ```python\n    client.margin_v1_post_broker_sub_account_api_commission_futures(**params)\n    ```\n\n\t- **GET /papi/v1/margin/myTrades**\n    ```python\n    client.papi_v1_get_margin_my_trades(**params)\n    ```\n\n\t- **GET /sapi/v1/pay/transactions**\n    ```python\n    client.margin_v1_get_pay_transactions(**params)\n    ```\n\n\t- **GET /papi/v1/um/leverageBracket**\n    ```python\n    client.papi_v1_get_um_leverage_bracket(**params)\n    ```\n\n\t- **GET /papi/v1/margin/orderList**\n    ```python\n    client.papi_v1_get_margin_order_list(**params)\n    ```\n\n\t- **GET /dapi/v1/allForceOrders**\n    ```python\n    client.futures_coin_v1_get_all_force_orders(**params)\n    ```\n\n\t- **GET /sapi/v1/margin/isolated/accountLimit**\n    ```python\n    client.margin_v1_get_margin_isolated_account_limit(**params)\n    ```\n\n\t- **GET /sapi/v1/lending/auto-invest/history/list**\n    ```python\n    client.margin_v1_get_lending_auto_invest_history_list(**params)\n    ```\n\n\t- **GET /dapi/v1/account**\n    ```python\n    client.futures_coin_v1_get_account(**params)\n    ```\n\n\t- **GET /dapi/v1/markPriceKlines**\n    ```python\n    client.futures_coin_v1_get_mark_price_klines(**params)\n    ```\n\n\t- **POST /sapi/v1/loan/customize/margin_call**\n    ```python\n    client.margin_v1_post_loan_customize_margin_call(**params)\n    ```\n\n\t- **GET /sapi/v1/broker/subAccount/bnbBurn/status**\n    ```python\n    client.margin_v1_get_broker_sub_account_bnb_burn_status(**params)\n    ```\n\n\t- **DELETE /eapi/v1/block/order/create**\n    ```python\n    client.options_v1_delete_block_order_create(**params)\n    ```\n\n\t- **GET /sapi/v1/managed-subaccount/accountSnapshot**\n    ```python\n    client.margin_v1_get_managed_subaccount_account_snapshot(**params)\n    ```\n\n\t- **GET /fapi/v1/constituents**\n    ```python\n    client.futures_v1_get_constituents(**params)\n    ```\n\n\t- **GET /dapi/v1/indexPriceKlines**\n    ```python\n    client.futures_coin_v1_get_index_price_klines(**params)\n    ```\n\n\t- **GET /sapi/v1/broker/subAccountApi/commission/coinFutures**\n    ```python\n    client.margin_v1_get_broker_sub_account_api_commission_coin_futures(**params)\n    ```\n\n\t- **GET /sapi/v2/broker/subAccount/futuresSummary**\n    ```python\n    client.margin_v2_get_broker_sub_account_futures_summary(**params)\n    ```\n\n\t- **GET /sapi/v1/sub-account/transfer/subUserHistory**\n    ```python\n    client.margin_v1_get_sub_account_transfer_sub_user_history(**params)\n    ```\n\n\t- **POST /sapi/v1/sub-account/futures/internalTransfer**\n    ```python\n    client.margin_v1_post_sub_account_futures_internal_transfer(**params)\n    ```\n\n\t- **GET /sapi/v1/loan/ongoing/orders**\n    ```python\n    client.margin_v1_get_loan_ongoing_orders(**params)\n    ```\n\n\t- **GET /sapi/v2/loan/flexible/ongoing/orders**\n    ```python\n    client.margin_v2_get_loan_flexible_ongoing_orders(**params)\n    ```\n\n\t- **GET /eapi/v1/block/order/execute**\n    ```python\n    client.options_v1_get_block_order_execute(**params)\n    ```\n\n\t- **GET /papi/v2/um/account**\n    ```python\n    client.papi_v2_get_um_account(**params)\n    ```\n\n\t- **POST /sapi/v1/margin/order/oco**\n    ```python\n    client.margin_v1_post_margin_order_oco(**params)\n    ```\n\n\t- **GET /api/v1/portfolio/negative-balance-exchange-record**\n    ```python\n    client.v1_get_portfolio_negative_balance_exchange_record(**params)\n    ```\n\n\t- **POST /sapi/v1/algo/futures/newOrderVp**\n    ```python\n    client.margin_v1_post_algo_futures_new_order_vp(**params)\n    ```\n\n\t- **DELETE /papi/v1/um/order**\n    ```python\n    client.papi_v1_delete_um_order(**params)\n    ```\n\n\t- **POST /fapi/v1/convert/getQuote**\n    ```python\n    client.futures_v1_post_convert_get_quote(**params)\n    ```\n\n\t- **GET /sapi/v1/algo/spot/subOrders**\n    ```python\n    client.margin_v1_get_algo_spot_sub_orders(**params)\n    ```\n\n\t- **GET /dapi/v1/userTrades**\n    ```python\n    client.futures_coin_v1_get_user_trades(**params)\n    ```\n\n\t- **POST /papi/v1/um/feeBurn**\n    ```python\n    client.papi_v1_post_um_fee_burn(**params)\n    ```\n\n\t- **POST /sapi/v1/portfolio/redeem**\n    ```python\n    client.margin_v1_post_portfolio_redeem(**params)\n    ```\n\n\t- **POST /fapi/v1/multiAssetsMargin**\n    ```python\n    client.futures_v1_post_multi_assets_margin(**params)\n    ```\n\n\t- **POST /sapi/v1/lending/auto-invest/plan/add**\n    ```python\n    client.margin_v1_post_lending_auto_invest_plan_add(**params)\n    ```\n\n\t- **GET /eapi/v1/historyOrders**\n    ```python\n    client.options_v1_get_history_orders(**params)\n    ```\n\n\t- **GET /sapi/v1/lending/auto-invest/source-asset/list**\n    ```python\n    client.margin_v1_get_lending_auto_invest_source_asset_list(**params)\n    ```\n\n\t- **GET /sapi/v1/margin/allOrderList**\n    ```python\n    client.margin_v1_get_margin_all_order_list(**params)\n    ```\n\n\t- **POST /sapi/v1/eth-staking/eth/redeem**\n    ```python\n    client.margin_v1_post_eth_staking_eth_redeem(**params)\n    ```\n\n\t- **GET /sapi/v1/broker/rebate/historicalRecord**\n    ```python\n    client.margin_v1_get_broker_rebate_historical_record(**params)\n    ```\n\n\t- **GET /sapi/v1/simple-earn/locked/history/subscriptionRecord**\n    ```python\n    client.margin_v1_get_simple_earn_locked_history_subscription_record(**params)\n    ```\n\n\t- **PUT /dapi/v1/order**\n    ```python\n    client.futures_coin_v1_put_order(**params)\n    ```\n\n\t- **GET /sapi/v1/managed-subaccount/asset**\n    ```python\n    client.margin_v1_get_managed_subaccount_asset(**params)\n    ```\n\n\t- **GET /sapi/v1/sol-staking/sol/quota**\n    ```python\n    client.margin_v1_get_sol_staking_sol_quota(**params)\n    ```\n\n\t- **POST /sapi/v1/loan/vip/renew**\n    ```python\n    client.margin_v1_post_loan_vip_renew(**params)\n    ```\n\n\t- **POST /dapi/v1/order**\n    ```python\n    client.futures_coin_v1_post_order(**params)\n    ```\n\n\t- **GET /sapi/v1/managed-subaccount/queryTransLogForTradeParent**\n    ```python\n    client.margin_v1_get_managed_subaccount_query_trans_log_for_trade_parent(**params)\n    ```\n\n\t- **GET /sapi/v1/simple-earn/flexible/history/redemptionRecord**\n    ```python\n    client.margin_v1_get_simple_earn_flexible_history_redemption_record(**params)\n    ```\n\n\t- **GET /sapi/v1/sub-account/margin/accountSummary**\n    ```python\n    client.margin_v1_get_sub_account_margin_account_summary(**params)\n    ```\n\n\t- **GET /sapi/v1/margin/dribblet**\n    ```python\n    client.margin_v1_get_margin_dribblet(**params)\n    ```\n\n\t- **GET /eapi/v1/exerciseHistory**\n    ```python\n    client.options_v1_get_exercise_history(**params)\n    ```\n\n\t- **GET /sapi/v1/convert/exchangeInfo**\n    ```python\n    client.margin_v1_get_convert_exchange_info(**params)\n    ```\n\n\t- **GET /sapi/v1/eth-staking/eth/history/wbethRewardsHistory**\n    ```python\n    client.margin_v1_get_eth_staking_eth_history_wbeth_rewards_history(**params)\n    ```\n\n\t- **GET /sapi/v1/simple-earn/locked/position**\n    ```python\n    client.margin_v1_get_simple_earn_locked_position(**params)\n    ```\n\n\t- **GET /sapi/v1/mining/pub/algoList**\n    ```python\n    client.margin_v1_get_mining_pub_algo_list(**params)\n    ```\n\n\t- **GET /dapi/v1/ticker/bookTicker**\n    ```python\n    client.futures_coin_v1_get_ticker_book_ticker(**params)\n    ```\n\n\t- **GET /eapi/v1/blockTrades**\n    ```python\n    client.options_v1_get_block_trades(**params)\n    ```\n\n\t- **GET /sapi/v1/copyTrading/futures/leadSymbol**\n    ```python\n    client.margin_v1_get_copy_trading_futures_lead_symbol(**params)\n    ```\n\n\t- **GET /papi/v1/cm/orderAmendment**\n    ```python\n    client.papi_v1_get_cm_order_amendment(**params)\n    ```\n\n\t- **GET /sapi/v4/sub-account/assets**\n    ```python\n    client.margin_v4_get_sub_account_assets(**params)\n    ```\n\n\t- **GET /sapi/v1/mining/worker/list**\n    ```python\n    client.margin_v1_get_mining_worker_list(**params)\n    ```\n\n\t- **DELETE /sapi/v1/margin/openOrders**\n    ```python\n    client.margin_v1_delete_margin_open_orders(**params)\n    ```\n\n\t- **GET /dapi/v1/constituents**\n    ```python\n    client.futures_coin_v1_get_constituents(**params)\n    ```\n\n\t- **GET /sapi/v1/dci/product/list**\n    ```python\n    client.margin_v1_get_dci_product_list(**params)\n    ```\n\n\t- **GET /fapi/v1/convert/orderStatus**\n    ```python\n    client.futures_v1_get_convert_order_status(**params)\n    ```\n\n"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2017 sammchardy\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "PYPIREADME.rst",
    "content": ".. image:: https://img.shields.io/pypi/v/python-binance.svg\n    :target: https://pypi.python.org/pypi/python-binance\n\n.. image:: https://img.shields.io/pypi/l/python-binance.svg\n    :target: https://pypi.python.org/pypi/python-binance\n\n.. image:: https://img.shields.io/travis/sammchardy/python-binance.svg\n    :target: https://travis-ci.org/sammchardy/python-binance\n\n.. image:: https://img.shields.io/coveralls/sammchardy/python-binance.svg\n    :target: https://coveralls.io/github/sammchardy/python-binance\n\n.. image:: https://img.shields.io/pypi/wheel/python-binance.svg\n    :target: https://pypi.python.org/pypi/python-binance\n\n.. image:: https://img.shields.io/pypi/pyversions/python-binance.svg\n    :target: https://pypi.python.org/pypi/python-binance\n\nThis is an unofficial Python wrapper for the `Binance exchange REST API v3 <https://binance-docs.github.io/apidocs/spot/en>`_. I am in no way affiliated with Binance, use at your own risk.\n\nIf you came here looking for the `Binance exchange <https://www.binance.com/?ref=10099792>`_ to purchase cryptocurrencies, then `go here <https://www.binance.com/?ref=10099792>`_.\nIf you want to automate interactions with Binance stick around.\n\nIf you're interested in Binance's new DEX Binance Chain see my `python-binance-chain library <https://github.com/sammchardy/python-binance-chain>`_\n\nSource code\n  https://github.com/sammchardy/python-binance\n\nDocumentation\n  https://python-binance.readthedocs.io/en/latest/\n\nBinance API Telegram\n  https://t.me/binance_api_english\n\nBlog with examples including async\n  https://sammchardy.github.io\n\n- `Async basics for Binance <https://sammchardy.github.io/binance/2021/05/01/async-binance-basics.html>`_\n- `Understanding Binance Order Filters <https://sammchardy.github.io/binance/2021/05/03/binance-order-filters.html>`_\n\nMake sure you update often and check the `Changelog <https://python-binance.readthedocs.io/en/latest/changelog.html>`_ for new features and bug fixes.\n\nFeatures\n--------\n\n- Implementation of all General, Market Data and Account endpoints.\n- Asyncio implementation\n- Testnet support for Spot, Futures and Vanilla Options\n- Simple handling of authentication include RSA keys\n- No need to generate timestamps yourself, the wrapper does it for you\n- Response exception handling\n- Websocket handling with reconnection and multiplexed connections\n- Symbol Depth Cache\n- Historical Kline/Candle fetching function\n- Withdraw functionality\n- Deposit addresses\n- Margin Trading\n- Futures Trading\n- Vanilla Options\n- Support other domains (.us, .jp, etc)\n\nUpgrading to v1.0.0+\n--------------------\n\nThe breaking changes include the migration from wapi to sapi endpoints which related to the\nwallet endpoints detailed in the `Binance Docs <https://binance-docs.github.io/apidocs/spot/en/#wallet-endpoints>`_\n\nThe other breaking change is for websocket streams and the Depth Cache Manager which have been\nconverted to use Asynchronous Context Managers. See examples in the Async section below or view the\n`websockets <https://python-binance.readthedocs.io/en/latest/websockets.html>`_ and\n`depth cache <https://python-binance.readthedocs.io/en/latest/depth_cache.html>`_ docs.\n\nQuick Start\n-----------\n\n`Register an account with Binance <https://accounts.binance.com/en/register?ref=10099792>`_.\n\n`Generate an API Key <https://www.binance.com/en/my/settings/api-management>`_ and assign relevant permissions.\n\nIf you are using an exchange from the US, Japan or other TLD then make sure pass `tld='us'` when creating the\nclient.\n\nTo use the `Spot <https://testnet.binance.vision/>`_ or `Vanilla Options <https://testnet.binanceops.com/>`_ Testnet,\npass `testnet=True` when creating the client.\n\n\n.. code:: bash\n\n    pip install python-binance\n\n\n.. code:: python\n\n    from binance import Client, ThreadedWebsocketManager, ThreadedDepthCacheManager\n    client = Client(api_key, api_secret)\n\n    # get market depth\n    depth = client.get_order_book(symbol='BNBBTC')\n\n    # place a test market buy order, to place an actual order use the create_order function\n    order = client.create_test_order(\n        symbol='BNBBTC',\n        side=Client.SIDE_BUY,\n        type=Client.ORDER_TYPE_MARKET,\n        quantity=100)\n\n    # get all symbol prices\n    prices = client.get_all_tickers()\n\n    # withdraw 100 ETH\n    # check docs for assumptions around withdrawals\n    from binance.exceptions import BinanceAPIException\n    try:\n        result = client.withdraw(\n            asset='ETH',\n            address='<eth_address>',\n            amount=100)\n    except BinanceAPIException as e:\n        print(e)\n    else:\n        print(\"Success\")\n\n    # fetch list of withdrawals\n    withdraws = client.get_withdraw_history()\n\n    # fetch list of ETH withdrawals\n    eth_withdraws = client.get_withdraw_history(coin='ETH')\n\n    # get a deposit address for BTC\n    address = client.get_deposit_address(coin='BTC')\n\n    # get historical kline data from any date range\n\n    # fetch 1 minute klines for the last day up until now\n    klines = client.get_historical_klines(\"BNBBTC\", Client.KLINE_INTERVAL_1MINUTE, \"1 day ago UTC\")\n\n    # fetch 30 minute klines for the last month of 2017\n    klines = client.get_historical_klines(\"ETHBTC\", Client.KLINE_INTERVAL_30MINUTE, \"1 Dec, 2017\", \"1 Jan, 2018\")\n\n    # fetch weekly klines since it listed\n    klines = client.get_historical_klines(\"NEOBTC\", Client.KLINE_INTERVAL_1WEEK, \"1 Jan, 2017\")\n\n    # socket manager using threads\n    twm = ThreadedWebsocketManager()\n    twm.start()\n\n    # depth cache manager using threads\n    dcm = ThreadedDepthCacheManager()\n    dcm.start()\n\n    def handle_socket_message(msg):\n        print(f\"message type: {msg['e']}\")\n        print(msg)\n\n    def handle_dcm_message(depth_cache):\n        print(f\"symbol {depth_cache.symbol}\")\n        print(\"top 5 bids\")\n        print(depth_cache.get_bids()[:5])\n        print(\"top 5 asks\")\n        print(depth_cache.get_asks()[:5])\n        print(\"last update time {}\".format(depth_cache.update_time))\n\n    twm.start_kline_socket(callback=handle_socket_message, symbol='BNBBTC')\n\n    dcm.start_depth_cache(callback=handle_dcm_message, symbol='ETHBTC')\n\n    # replace with a current options symbol\n    options_symbol = 'BTC-210430-36000-C'\n    dcm.start_options_depth_cache(callback=handle_dcm_message, symbol=options_symbol)\n\n\nFor more `check out the documentation <https://python-binance.readthedocs.io/en/latest/>`_.\n\nAsync Example\n-------------\n\nRead `Async basics for Binance <https://sammchardy.github.io/binance/2021/05/01/async-binance-basics.html>`_\nfor more information.\n\n.. code:: python\n\n    import asyncio\n    import json\n\n    from binance import AsyncClient, DepthCacheManager, BinanceSocketManager\n\n    async def main():\n\n        # initialise the client\n        client = await AsyncClient.create()\n\n        # run some simple requests\n        print(json.dumps(await client.get_exchange_info(), indent=2))\n\n        print(json.dumps(await client.get_symbol_ticker(symbol=\"BTCUSDT\"), indent=2))\n\n        # initialise websocket factory manager\n        bsm = BinanceSocketManager(client)\n\n        # create listener using async with\n        # this will exit and close the connection after 5 messages\n        async with bsm.trade_socket('ETHBTC') as ts:\n            for _ in range(5):\n                res = await ts.recv()\n                print(f'recv {res}')\n\n        # get historical kline data from any date range\n\n        # fetch 1 minute klines for the last day up until now\n        klines = client.get_historical_klines(\"BNBBTC\", AsyncClient.KLINE_INTERVAL_1MINUTE, \"1 day ago UTC\")\n\n        # use generator to fetch 1 minute klines for the last day up until now\n        async for kline in await client.get_historical_klines_generator(\"BNBBTC\", AsyncClient.KLINE_INTERVAL_1MINUTE, \"1 day ago UTC\"):\n            print(kline)\n\n        # fetch 30 minute klines for the last month of 2017\n        klines = client.get_historical_klines(\"ETHBTC\", Client.KLINE_INTERVAL_30MINUTE, \"1 Dec, 2017\", \"1 Jan, 2018\")\n\n        # fetch weekly klines since it listed\n        klines = client.get_historical_klines(\"NEOBTC\", Client.KLINE_INTERVAL_1WEEK, \"1 Jan, 2017\")\n\n        # setup an async context the Depth Cache and exit after 5 messages\n        async with DepthCacheManager(client, symbol='ETHBTC') as dcm_socket:\n            for _ in range(5):\n                depth_cache = await dcm_socket.recv()\n                print(f\"symbol {depth_cache.symbol} updated:{depth_cache.update_time}\")\n                print(\"Top 5 asks:\")\n                print(depth_cache.get_asks()[:5])\n                print(\"Top 5 bids:\")\n                print(depth_cache.get_bids()[:5])\n\n        # Vanilla options Depth Cache works the same, update the symbol to a current one\n        options_symbol = 'BTC-210430-36000-C'\n        async with OptionsDepthCacheManager(client, symbol=options_symbol) as dcm_socket:\n            for _ in range(5):\n                depth_cache = await dcm_socket.recv()\n                count += 1\n                print(f\"symbol {depth_cache.symbol} updated:{depth_cache.update_time}\")\n                print(\"Top 5 asks:\")\n                print(depth_cache.get_asks()[:5])\n                print(\"Top 5 bids:\")\n                print(depth_cache.get_bids()[:5])\n\n        await client.close_connection()\n\n    if __name__ == \"__main__\":\n\n        loop = asyncio.get_event_loop()\n        loop.run_until_complete(main())\n\n\nDonate\n------\n\nIf this library helped you out feel free to donate.\n\n- ETH: 0xD7a7fDdCfA687073d7cC93E9E51829a727f9fE70\n- LTC: LPC5vw9ajR1YndE1hYVeo3kJ9LdHjcRCUZ\n- NEO: AVJB4ZgN7VgSUtArCt94y7ZYT6d5NDfpBo\n- BTC: 1Dknp6L6oRZrHDECRedihPzx2sSfmvEBys\n\nOther Exchanges\n---------------\n\nIf you use `Binance Chain <https://testnet.binance.org/>`_ check out my `python-binance-chain <https://github.com/sammchardy/python-binance-chain>`_ library.\n\nIf you use `Kucoin <https://www.kucoin.com/?rcode=E42cWB>`_ check out my `python-kucoin <https://github.com/sammchardy/python-kucoin>`_ library.\n\nIf you use `IDEX <https://idex.market>`_ check out my `python-idex <https://github.com/sammchardy/python-idex>`_ library.\n\n.. image:: https://ga-beacon.appspot.com/UA-111417213-1/github/python-binance?pixel&useReferer\n"
  },
  {
    "path": "README.rst",
    "content": "=================================\nWelcome to python-binance v1.0.35\n=================================\n\n.. image:: https://img.shields.io/pypi/v/python-binance.svg\n    :target: https://pypi.python.org/pypi/python-binance\n\n.. image:: https://img.shields.io/pypi/l/python-binance.svg\n    :target: https://pypi.python.org/pypi/python-binance\n\n.. image:: https://img.shields.io/coveralls/sammchardy/python-binance.svg\n    :target: https://coveralls.io/github/sammchardy/python-binance\n\n.. image:: https://img.shields.io/pypi/wheel/python-binance.svg\n    :target: https://pypi.python.org/pypi/python-binance\n\n.. image:: https://img.shields.io/pypi/pyversions/python-binance.svg\n    :target: https://pypi.python.org/pypi/python-binance\n\n.. image:: https://img.shields.io/badge/Telegram-Join%20Us-blue?logo=Telegram\n    :target: https://t.me/python_binance\n\n\nThis is an unofficial Python wrapper for the `Binance exchange REST API v3 <https://binance-docs.github.io/apidocs/spot/en>`_.\n\nIf you came here looking for the `Binance exchange <https://accounts.binance.com/register?ref=PGDFCE46>`_ to purchase cryptocurrencies, then `go here <https://accounts.binance.com/register?ref=PGDFCE46>`_.\nIf you want to automate interactions with Binance stick around.\n\n.. |ico1| image:: https://avatars.githubusercontent.com/u/31901609?s=48&v=4\n    :target: https://github.com/ccxt/ccxt\n    :height: 3ex\n    :align: middle\n\n**This project is powered by** |ico1|\n\n*Please make sure your* `python-binance` *version is* **v.1.0.20** *or higher.*\n*The previous versions are no longer recommended because some endpoints have been deprecated.*\n\nSource code\n  https://github.com/sammchardy/python-binance\n\nDocumentation\n  https://python-binance.readthedocs.io/en/latest/\n\nCommunity Telegram Chat\n  https://t.me/python_binance\n\nAnnouncements Channel\n  https://t.me/python_binance_announcements\n\nExamples including async\n  https://github.com/sammchardy/python-binance/tree/master/examples\n\n- `Async basics for Binance <https://sammchardy.github.io/binance/2021/05/01/async-binance-basics.html>`_\n- `Understanding Binance Order Filters <https://sammchardy.github.io/binance/2021/05/03/binance-order-filters.html>`_\n\nMake sure you update often and check the `Changelog <https://python-binance.readthedocs.io/en/latest/changelog.html>`_ for new features and bug fixes.\n\nYour contributions, suggestions, and fixes are always welcome! Don't hesitate to open a GitHub issue or reach out to us on our Telegram chat\n\nFeatures\n--------\n\n- Implementation of all General, Market Data and Account endpoints.\n- Asyncio implementation\n- Demo trading support (by providing demo=True)\n- Testnet support for Spot, Futures and Vanilla Options (deprecated)\n- Simple handling of authentication include RSA and EDDSA keys\n- Verbose mode for inspecting requests (verbose=True)\n- No need to generate timestamps yourself, the wrapper does it for you\n- RecvWindow sent by default\n- Response exception handling\n- Customizable HTTP headers\n- Websocket handling with reconnection and multiplexed connections\n- CRUD over websockets, create/fetch/edit through websockets for minimum latency.\n- Symbol Depth Cache\n- Historical Kline/Candle fetching function\n- Withdraw functionality\n- Deposit addresses\n- Margin Trading\n- Futures Trading\n- Porfolio Margin Trading\n- Vanilla Options\n- Proxy support (REST and WS)\n- Orjson support for faster JSON parsing\n- Support other domains (.us, .jp, etc)\n- Support for the Gift Card API\n\nUpgrading to v1.0.0+\n--------------------\n\nThe breaking changes include the migration from wapi to sapi endpoints which related to the\nwallet endpoints detailed in the `Binance Docs <https://binance-docs.github.io/apidocs/spot/en/#wallet-endpoints>`_\n\nThe other breaking change is for websocket streams and the Depth Cache Manager which have been\nconverted to use Asynchronous Context Managers. See examples in the Async section below or view the\n`websockets <https://python-binance.readthedocs.io/en/latest/websockets.html>`_ and\n`depth cache <https://python-binance.readthedocs.io/en/latest/depth_cache.html>`_ docs.\n\nQuick Start\n-----------\n\n`Register an account with Binance <https://accounts.binance.com/register?ref=PGDFCE46>`_.\n\n`Generate an API Key <https://www.binance.com/en/my/settings/api-management>`_ and assign relevant permissions.\n\nIf you are using an exchange from the US, Japan or other TLD then make sure pass `tld='us'` when creating the\nclient.\n\nTo use the `Spot <https://testnet.binance.vision/>`_, `Vanilla Options <https://testnet.binanceops.com/>`_ , or `Futures <https://testnet.binancefuture.com>`_ Testnet\npass `testnet=True` when creating the client.\n\n\n.. code:: bash\n\n    pip install python-binance\n\n\n.. code:: python\n\n    from binance import Client, ThreadedWebsocketManager, ThreadedDepthCacheManager\n    client = Client(api_key, api_secret)\n\n    # get market depth\n    depth = client.get_order_book(symbol='BNBBTC')\n\n    # place a test market buy order, to place an actual order use the create_order function\n    order = client.create_test_order(\n        symbol='BNBBTC',\n        side=Client.SIDE_BUY,\n        type=Client.ORDER_TYPE_MARKET,\n        quantity=100)\n\n    # get all symbol prices\n    prices = client.get_all_tickers()\n\n    # withdraw 100 ETH\n    # check docs for assumptions around withdrawals\n    from binance.exceptions import BinanceAPIException\n    try:\n        result = client.withdraw(\n            asset='ETH',\n            address='<eth_address>',\n            amount=100)\n    except BinanceAPIException as e:\n        print(e)\n    else:\n        print(\"Success\")\n\n    # fetch list of withdrawals\n    withdraws = client.get_withdraw_history()\n\n    # fetch list of ETH withdrawals\n    eth_withdraws = client.get_withdraw_history(coin='ETH')\n\n    # get a deposit address for BTC\n    address = client.get_deposit_address(coin='BTC')\n\n    # get historical kline data from any date range\n\n    # fetch 1 minute klines for the last day up until now\n    klines = client.get_historical_klines(\"BNBBTC\", Client.KLINE_INTERVAL_1MINUTE, \"1 day ago UTC\")\n\n    # fetch 30 minute klines for the last month of 2017\n    klines = client.get_historical_klines(\"ETHBTC\", Client.KLINE_INTERVAL_30MINUTE, \"1 Dec, 2017\", \"1 Jan, 2018\")\n\n    # fetch weekly klines since it listed\n    klines = client.get_historical_klines(\"NEOBTC\", Client.KLINE_INTERVAL_1WEEK, \"1 Jan, 2017\")\n\n    # create conditional order using the dedicated method\n    algo_order = client.futures_create_algo_order(symbol=\"LTCUSDT\", side=\"BUY\", type=\"STOP_MARKET\", quantity=0.1, triggerPrice = 120)\n\n    # create conditional order using the create_order method (will redirect to the algoOrder as well)\n    order2 = await client.futures_create_order(symbol=\"LTCUSDT\", side=\"BUY\", type=\"STOP_MARKET\", quantity=0.1, triggerPrice = 120)\n\n    # cancel algo/conditional order\n    cancel2 = await client.futures_cancel_algo_order(orderId=order2[\"orderId\"], symbol=\"LTCUSDT\")\n\n    # fetch open algo/conditional orders\n    open_orders = await client.futures_get_open_algo_orders(symbol=\"LTCUSDT\")\n\n    # create order through websockets\n    order_ws = client.ws_create_order( symbol=\"LTCUSDT\", side=\"BUY\", type=\"MARKET\", quantity=0.1)\n\n    # get account using custom headers\n    account = client.get_account(headers={'MyCustomKey': 'MyCustomValue'})\n\n    # socket manager using threads\n    twm = ThreadedWebsocketManager()\n    twm.start()\n\n    # depth cache manager using threads\n    dcm = ThreadedDepthCacheManager()\n    dcm.start()\n\n    def handle_socket_message(msg):\n        print(f\"message type: {msg['e']}\")\n        print(msg)\n\n    def handle_dcm_message(depth_cache):\n        print(f\"symbol {depth_cache.symbol}\")\n        print(\"top 5 bids\")\n        print(depth_cache.get_bids()[:5])\n        print(\"top 5 asks\")\n        print(depth_cache.get_asks()[:5])\n        print(\"last update time {}\".format(depth_cache.update_time))\n\n    twm.start_kline_socket(callback=handle_socket_message, symbol='BNBBTC')\n\n    dcm.start_depth_cache(callback=handle_dcm_message, symbol='ETHBTC')\n\n    # replace with a current options symbol\n    options_symbol = 'BTC-241227-41000-C'\n    dcm.start_options_depth_cache(callback=handle_dcm_message, symbol=options_symbol)\n\n    # join the threaded managers to the main thread\n    twm.join()\n    dcm.join()\n\nFor more `check out the documentation <https://python-binance.readthedocs.io/en/latest/>`_.\n\nAsync Example\n-------------\n\nRead `Async basics for Binance <https://sammchardy.github.io/binance/2021/05/01/async-binance-basics.html>`_\nfor more information.\n\n.. code:: python\n\n    import asyncio\n    import json\n\n    from binance import AsyncClient, DepthCacheManager, BinanceSocketManager\n\n    async def main():\n\n        # initialise the client\n        client = await AsyncClient.create()\n\n        # run some simple requests\n        print(json.dumps(await client.get_exchange_info(), indent=2))\n\n        print(json.dumps(await client.get_symbol_ticker(symbol=\"BTCUSDT\"), indent=2))\n\n        # initialise websocket factory manager\n        bsm = BinanceSocketManager(client)\n\n        # create listener using async with\n        # this will exit and close the connection after 5 messages\n        async with bsm.trade_socket('ETHBTC') as ts:\n            for _ in range(5):\n                res = await ts.recv()\n                print(f'recv {res}')\n\n        # get historical kline data from any date range\n\n        # fetch 1 minute klines for the last day up until now\n        klines = client.get_historical_klines(\"BNBBTC\", AsyncClient.KLINE_INTERVAL_1MINUTE, \"1 day ago UTC\")\n\n        # use generator to fetch 1 minute klines for the last day up until now\n        async for kline in await client.get_historical_klines_generator(\"BNBBTC\", AsyncClient.KLINE_INTERVAL_1MINUTE, \"1 day ago UTC\"):\n            print(kline)\n\n        # fetch 30 minute klines for the last month of 2017\n        klines = await client.get_historical_klines(\"ETHBTC\", Client.KLINE_INTERVAL_30MINUTE, \"1 Dec, 2017\", \"1 Jan, 2018\")\n\n        # fetch weekly klines since it listed\n        klines = await client.get_historical_klines(\"NEOBTC\", Client.KLINE_INTERVAL_1WEEK, \"1 Jan, 2017\")\n\n\n        # create order through websockets\n        order_ws = await client.ws_create_order( symbol=\"LTCUSDT\", side=\"BUY\", type=\"MARKET\", quantity=0.1)\n\n        # setup an async context the Depth Cache and exit after 5 messages\n        async with DepthCacheManager(client, symbol='ETHBTC') as dcm_socket:\n            for _ in range(5):\n                depth_cache = await dcm_socket.recv()\n                print(f\"symbol {depth_cache.symbol} updated:{depth_cache.update_time}\")\n                print(\"Top 5 asks:\")\n                print(depth_cache.get_asks()[:5])\n                print(\"Top 5 bids:\")\n                print(depth_cache.get_bids()[:5])\n\n        # Vanilla options Depth Cache works the same, update the symbol to a current one\n        options_symbol = 'BTC-241227-41000-C'\n        async with OptionsDepthCacheManager(client, symbol=options_symbol) as dcm_socket:\n            for _ in range(5):\n                depth_cache = await dcm_socket.recv()\n                count += 1\n                print(f\"symbol {depth_cache.symbol} updated:{depth_cache.update_time}\")\n                print(\"Top 5 asks:\")\n                print(depth_cache.get_asks()[:5])\n                print(\"Top 5 bids:\")\n                print(depth_cache.get_bids()[:5])\n\n        await client.close_connection()\n\n    if __name__ == \"__main__\":\n        loop = asyncio.get_event_loop()\n        loop.run_until_complete(main())\n\n\nThe library is under `MIT license`, that means it's absolutely free for any developer to build commercial and opensource software on top of it, but use it at your own risk with no warranties, as is.\n\n\nOrjson support\n-------------------\n\nPython-binance also supports `orjson` for parsing JSON since it is much faster than the builtin library. This is especially important when using websockets because some exchanges return big messages that need to be parsed and dispatched as quickly as possible.\n\nHowever, `orjson` is not enabled by default because it is not supported by every python interpreter. If you want to opt-in, you just need to install it (`pip install orjson`) on your local environment. Python-binance will detect the installion and pick it up automatically.\n\nStar history\n------------\n\n.. image:: https://api.star-history.com/svg?repos=sammchardy/python-binance&type=Date\n    :target: https://api.star-history.com/svg?repos=sammchardy/python-binance&type=Date\n\nContact Us\n----------\n\nFor business inquiries: `info@ccxt.trade`\n\nOther Exchanges\n---------------\n- Check out `CCXT <https://github.com/ccxt/ccxt>`_ for more than 100 crypto exchanges with a unified trading API.\n- If you use `Kucoin <https://www.kucoin.com/ucenter/signup?rcode=E5wkqe>`_ check out my `python-kucoin <https://github.com/sammchardy/python-kucoin>`_ library.\n"
  },
  {
    "path": "binance/__init__.py",
    "content": "\"\"\"An unofficial Python wrapper for the Binance exchange API v3\n\n.. moduleauthor:: Sam McHardy\n\n\"\"\"\n\n__version__ = \"1.0.35\"\n\nfrom binance.async_client import AsyncClient  # noqa\nfrom binance.client import Client  # noqa\nfrom binance.ws.depthcache import (\n    DepthCacheManager,  # noqa\n    OptionsDepthCacheManager,  # noqa\n    ThreadedDepthCacheManager,  # noqa\n    FuturesDepthCacheManager,  # noqa\n)\nfrom binance.ws.streams import (\n    BinanceSocketManager,  # noqa\n    ThreadedWebsocketManager,  # noqa\n    BinanceSocketType,  # noqa\n)\n\nfrom binance.ws.keepalive_websocket import KeepAliveWebsocket  # noqa\n\nfrom binance.ws.reconnecting_websocket import ReconnectingWebsocket  # noqa\n\nfrom binance.ws.constants import *  # noqa\n\nfrom binance.exceptions import *  # noqa\n\nfrom binance.enums import *  # noqa\n"
  },
  {
    "path": "binance/async_client.py",
    "content": "import asyncio\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Optional, Union\nfrom urllib.parse import urlencode, quote\nimport time\nimport warnings\nimport aiohttp\nimport yarl\n\nfrom binance.enums import HistoricalKlinesType\nfrom binance.exceptions import (\n    BinanceAPIException,\n    BinanceRequestException,\n    NotImplementedException,\n)\nfrom binance.helpers import (\n    convert_list_to_json_array,\n    convert_ts_str,\n    get_loop,\n    interval_to_milliseconds,\n)\nfrom .base_client import BaseClient\nfrom .client import Client\n\n\nclass AsyncClient(BaseClient):\n    def __init__(\n        self,\n        api_key: Optional[str] = None,\n        api_secret: Optional[str] = None,\n        requests_params: Optional[Dict[str, Any]] = None,\n        tld: str = \"com\",\n        base_endpoint: str = BaseClient.BASE_ENDPOINT_DEFAULT,\n        testnet: bool = False,\n        demo: bool = False,\n        loop=None,\n        session_params: Optional[Dict[str, Any]] = None,\n        private_key: Optional[Union[str, Path]] = None,\n        private_key_pass: Optional[str] = None,\n        https_proxy: Optional[str] = None,\n        time_unit: Optional[str] = None,\n        verbose: bool = False,\n    ):\n        self.https_proxy = https_proxy\n        self.loop = loop or get_loop()\n        self._session_params: Dict[str, Any] = session_params or {}\n\n        # Convert https_proxy to requests_params format for BaseClient\n        if https_proxy and requests_params is None:\n            requests_params = {'proxies': {'http': https_proxy, 'https': https_proxy}}\n        elif https_proxy and requests_params is not None:\n            if 'proxies' not in requests_params:\n                requests_params['proxies'] = {}\n            requests_params['proxies'].update({'http': https_proxy, 'https': https_proxy})\n\n        super().__init__(\n            api_key,\n            api_secret,\n            requests_params,\n            tld,\n            base_endpoint,\n            testnet,\n            demo,\n            private_key,\n            private_key_pass,\n            time_unit=time_unit,\n            verbose=verbose,\n        )\n\n    @classmethod\n    async def create(\n        cls,\n        api_key: Optional[str] = None,\n        api_secret: Optional[str] = None,\n        requests_params: Optional[Dict[str, Any]] = None,\n        tld: str = \"com\",\n        base_endpoint: str = BaseClient.BASE_ENDPOINT_DEFAULT,\n        testnet: bool = False,\n        demo: bool = False,\n        loop=None,\n        session_params: Optional[Dict[str, Any]] = None,\n        private_key: Optional[Union[str, Path]] = None,\n        private_key_pass: Optional[str] = None,\n        https_proxy: Optional[str] = None,\n        time_unit: Optional[str] = None,\n        verbose: bool = False,\n    ):\n        self = cls(\n            api_key,\n            api_secret,\n            requests_params,\n            tld,\n            base_endpoint,\n            testnet,\n            demo,\n            loop,\n            session_params,\n            private_key,\n            private_key_pass,\n            https_proxy,\n            time_unit,\n            verbose\n        )\n        self.https_proxy = https_proxy  # move this to the constructor\n\n        try:\n            await self.ping()\n\n            # calculate timestamp offset between local and binance server\n            res = await self.get_server_time()\n            self.timestamp_offset = res[\"serverTime\"] - int(time.time() * 1000)\n\n            return self\n        except Exception:\n            # If ping throw an exception, the current self must be cleaned\n            # else, we can receive a \"asyncio:Unclosed client session\"\n            await self.close_connection()\n            raise\n\n    def _init_session(self) -> aiohttp.ClientSession:\n        session = aiohttp.ClientSession(\n            loop=self.loop, headers=self._get_headers(), **self._session_params\n        )\n        return session\n\n    async def close_connection(self):\n        if self.session:\n            assert self.session\n            await self.session.close()\n        if self.ws_api:\n            await self.ws_api.close()\n            self._ws_api = None\n\n    close_connection.__doc__ = Client.close_connection.__doc__\n\n    async def _request(\n        self, method, uri: str, signed: bool, force_params: bool = False, **kwargs\n    ):\n        # this check needs to be done before __get_request_kwargs to avoid\n        # polluting the signature\n        headers = {}\n        if method.upper() in [\"POST\", \"PUT\", \"DELETE\"]:\n            headers.update({\"Content-Type\": \"application/x-www-form-urlencoded\"})\n\n        if \"data\" in kwargs:\n            for key in kwargs[\"data\"]:\n                if key == \"headers\":\n                    headers.update(kwargs[\"data\"][key])\n                    del kwargs[\"data\"][key]\n                    break\n\n        kwargs = self._get_request_kwargs(method, signed, force_params, **kwargs)\n\n        if method == \"get\":\n            # url encode the query string\n            if \"params\" in kwargs:\n                uri = f\"{uri}?{kwargs['params']}\"\n                kwargs.pop(\"params\")\n\n        data = kwargs.get(\"data\")\n        if data is not None:\n            del kwargs[\"data\"]\n\n        if (\n            signed and self.PRIVATE_KEY and data\n        ):  # handle issues with signing using eddsa/rsa and POST requests\n            dict_data = Client.convert_to_dict(data)\n            signature = dict_data[\"signature\"] if \"signature\" in dict_data else None\n            if signature:\n                del dict_data[\"signature\"]\n            url_encoded_data = urlencode(dict_data)\n            data = f\"{url_encoded_data}&signature={signature}\"\n\n        # Remove proxies from kwargs since aiohttp uses 'proxy' parameter instead\n        kwargs.pop('proxies', None)\n\n        async with getattr(self.session, method)(\n            yarl.URL(uri, encoded=True),\n            proxy=self.https_proxy,\n            headers=headers,\n            data=data,\n            **kwargs,\n        ) as response:\n            self.response = response\n\n            if self.verbose:\n                response_text = await response.text()\n                self.logger.debug(\n                    \"\\nRequest: %s %s\\nRequestHeaders: %s\\nRequestBody: %s\\nResponse: %s\\nResponseHeaders: %s\\nResponseBody: %s\",\n                    method.upper(),\n                    uri,\n                    headers,\n                    data,\n                    response.status,\n                    dict(response.headers),\n                    response_text[:1000] if response_text else None\n                )\n\n            return await self._handle_response(response)\n\n    async def _handle_response(self, response: aiohttp.ClientResponse):\n        \"\"\"Internal helper for handling API responses from the Binance server.\n        Raises the appropriate exceptions when necessary; otherwise, returns the\n        response.\n        \"\"\"\n        if not str(response.status).startswith(\"2\"):\n            raise BinanceAPIException(response, response.status, await response.text())\n        \n        text = await response.text()\n        if text == \"\":\n            return {}\n\n        try:\n            return await response.json()\n        except ValueError:\n            txt = await response.text()\n            raise BinanceRequestException(f\"Invalid Response: {txt}\")\n\n    async def _request_api(\n        self,\n        method,\n        path,\n        signed=False,\n        version=BaseClient.PUBLIC_API_VERSION,\n        **kwargs,\n    ):\n        uri = self._create_api_uri(path, signed, version)\n        force_params = kwargs.pop(\"force_params\", False)\n        return await self._request(method, uri, signed, force_params, **kwargs)\n\n    async def _request_futures_api(\n        self, method, path, signed=False, version=1, **kwargs\n    ) -> Dict:\n        version = self._get_version(version, **kwargs)\n        uri = self._create_futures_api_uri(path, version=version)\n        force_params = kwargs.pop(\"force_params\", False)\n        return await self._request(method, uri, signed, force_params, **kwargs)\n\n    async def _request_futures_data_api(\n        self, method, path, signed=False, **kwargs\n    ) -> Dict:\n        uri = self._create_futures_data_api_uri(path)\n        force_params = kwargs.pop(\"force_params\", True)\n        return await self._request(method, uri, signed, force_params, **kwargs)\n\n    async def _request_futures_coin_api(\n        self, method, path, signed=False, version=1, **kwargs\n    ) -> Dict:\n        version = self._get_version(version, **kwargs)\n        uri = self._create_futures_coin_api_url(path, version=version)\n        force_params = kwargs.pop(\"force_params\", False)\n        return await self._request(method, uri, signed, force_params, **kwargs)\n\n    async def _request_futures_coin_data_api(\n        self, method, path, signed=False, version=1, **kwargs\n    ) -> Dict:\n        version = self._get_version(version, **kwargs)\n        uri = self._create_futures_coin_data_api_url(path, version=version)\n\n        force_params = kwargs.pop(\"force_params\", True)\n        return await self._request(method, uri, signed, force_params, **kwargs)\n\n    async def _request_options_api(self, method, path, signed=False, **kwargs) -> Dict:\n        uri = self._create_options_api_uri(path)\n        force_params = kwargs.pop(\"force_params\", True)\n\n        return await self._request(method, uri, signed, force_params, **kwargs)\n\n    async def _request_margin_api(\n        self, method, path, signed=False, version=1, **kwargs\n    ) -> Dict:\n        version = self._get_version(version, **kwargs)\n        uri = self._create_margin_api_uri(path, version)\n\n        force_params = kwargs.pop(\"force_params\", False)\n        return await self._request(method, uri, signed, force_params, **kwargs)\n\n    async def _request_papi_api(\n        self, method, path, signed=False, version=1, **kwargs\n    ) -> Dict:\n        version = self._get_version(version, **kwargs)\n        uri = self._create_papi_api_uri(path, version)\n\n        force_params = kwargs.pop(\"force_params\", False)\n        return await self._request(method, uri, signed, force_params, **kwargs)\n\n    async def _request_website(self, method, path, signed=False, **kwargs) -> Dict:\n        uri = self._create_website_uri(path)\n        return await self._request(method, uri, signed, **kwargs)\n\n    async def _get(\n        self, path, signed=False, version=BaseClient.PUBLIC_API_VERSION, **kwargs\n    ):\n        return await self._request_api(\"get\", path, signed, version, **kwargs)\n\n    async def _post(\n        self, path, signed=False, version=BaseClient.PUBLIC_API_VERSION, **kwargs\n    ) -> Dict:\n        return await self._request_api(\"post\", path, signed, version, **kwargs)\n\n    async def _put(\n        self, path, signed=False, version=BaseClient.PUBLIC_API_VERSION, **kwargs\n    ) -> Dict:\n        return await self._request_api(\"put\", path, signed, version, **kwargs)\n\n    async def _delete(\n        self, path, signed=False, version=BaseClient.PUBLIC_API_VERSION, **kwargs\n    ) -> Dict:\n        return await self._request_api(\"delete\", path, signed, version, **kwargs)\n\n    # Exchange Endpoints\n\n    async def get_products(self) -> Dict:\n        products = await self._request_website(\n            \"get\",\n            \"bapi/asset/v2/public/asset-service/product/get-products?includeEtf=true\",\n        )\n        return products\n\n    get_products.__doc__ = Client.get_products.__doc__\n\n    async def get_exchange_info(self) -> Dict:\n        return await self._get(\"exchangeInfo\")\n\n    get_exchange_info.__doc__ = Client.get_exchange_info.__doc__\n\n    async def get_symbol_info(self, symbol) -> Optional[Dict]:\n        res = await self.get_exchange_info()\n\n        for item in res[\"symbols\"]:\n            if item[\"symbol\"] == symbol.upper():\n                return item\n\n        return None\n\n    get_symbol_info.__doc__ = Client.get_symbol_info.__doc__\n\n    # General Endpoints\n\n    async def ping(self) -> Dict:\n        return await self._get(\"ping\")\n\n    ping.__doc__ = Client.ping.__doc__\n\n    async def get_server_time(self) -> Dict:\n        return await self._get(\"time\")\n\n    get_server_time.__doc__ = Client.get_server_time.__doc__\n\n    # Market Data Endpoints\n\n    async def get_all_tickers(\n        self, symbol: Optional[str] = None\n    ) -> List[Dict[str, str]]:\n        params = {}\n        if symbol:\n            params[\"symbol\"] = symbol\n        response = await self._get(\n            \"ticker/price\", data=params\n        )\n        if isinstance(response, list) and all(isinstance(item, dict) for item in response):\n            return response\n        raise TypeError(\"Expected a list of dictionaries\")\n\n    get_all_tickers.__doc__ = Client.get_all_tickers.__doc__\n\n    async def get_orderbook_tickers(self, **params) -> Dict:\n        data = {}\n        if \"symbol\" in params:\n            data[\"symbol\"] = params[\"symbol\"]\n        elif \"symbols\" in params:\n            data[\"symbols\"] = params[\"symbols\"]\n        return await self._get(\n            \"ticker/bookTicker\", data=data\n        )\n\n    get_orderbook_tickers.__doc__ = Client.get_orderbook_tickers.__doc__\n\n    async def get_order_book(self, **params) -> Dict:\n        return await self._get(\"depth\", data=params)\n\n    get_order_book.__doc__ = Client.get_order_book.__doc__\n\n    async def get_recent_trades(self, **params) -> Dict:\n        return await self._get(\"trades\", data=params)\n\n    get_recent_trades.__doc__ = Client.get_recent_trades.__doc__\n\n    async def get_historical_trades(self, **params) -> Dict:\n        return await self._get(\n            \"historicalTrades\", data=params\n        )\n\n    get_historical_trades.__doc__ = Client.get_historical_trades.__doc__\n\n    async def get_aggregate_trades(self, **params) -> Dict:\n        return await self._get(\n            \"aggTrades\", data=params\n        )\n\n    get_aggregate_trades.__doc__ = Client.get_aggregate_trades.__doc__\n\n    async def aggregate_trade_iter(self, symbol, start_str=None, last_id=None):\n        if start_str is not None and last_id is not None:\n            raise ValueError(\n                \"start_time and last_id may not be simultaneously specified.\"\n            )\n\n        # If there's no last_id, get one.\n        if last_id is None:\n            # Without a last_id, we actually need the first trade.  Normally,\n            # we'd get rid of it. See the next loop.\n            if start_str is None:\n                trades = await self.get_aggregate_trades(symbol=symbol, fromId=0)\n            else:\n                # The difference between startTime and endTime should be less\n                # or equal than an hour and the result set should contain at\n                # least one trade.\n                start_ts = convert_ts_str(start_str)\n                # If the resulting set is empty (i.e. no trades in that interval)\n                # then we just move forward hour by hour until we find at least one\n                # trade or reach present moment\n                while True:\n                    end_ts = start_ts + (60 * 60 * 1000)\n                    trades = await self.get_aggregate_trades(\n                        symbol=symbol, startTime=start_ts, endTime=end_ts\n                    )\n                    if len(trades) > 0:\n                        break\n                    # If we reach present moment and find no trades then there is\n                    # nothing to iterate, so we're done\n                    if end_ts > int(time.time() * 1000):\n                        return\n                    start_ts = end_ts\n            for t in trades:\n                yield t\n            last_id = trades[-1][self.AGG_ID]\n\n        while True:\n            # There is no need to wait between queries, to avoid hitting the\n            # rate limit. We're using blocking IO, and as long as we're the\n            # only thread running calls like this, Binance will automatically\n            # add the right delay time on their end, forcing us to wait for\n            # data. That really simplifies this function's job. Binance is\n            # fucking awesome.\n            trades = await self.get_aggregate_trades(symbol=symbol, fromId=last_id)\n            # fromId=n returns a set starting with id n, but we already have\n            # that one. So get rid of the first item in the result set.\n            trades = trades[1:]\n            if len(trades) == 0:\n                return\n            for t in trades:\n                yield t\n            last_id = trades[-1][self.AGG_ID]\n\n    aggregate_trade_iter.__doc__ = Client.aggregate_trade_iter.__doc__\n\n    async def get_ui_klines(self, **params) -> Dict:\n        return await self._get(\"uiKlines\", data=params)\n\n    get_ui_klines.__doc__ = Client.get_ui_klines.__doc__\n\n    async def get_klines(self, **params) -> Dict:\n        return await self._get(\"klines\", data=params)\n\n    get_klines.__doc__ = Client.get_klines.__doc__\n\n    async def _klines(\n        self, klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT, **params\n    ) -> Dict:\n        if \"endTime\" in params and not params[\"endTime\"]:\n            del params[\"endTime\"]\n        if HistoricalKlinesType.SPOT == klines_type:\n            return await self.get_klines(**params)\n        elif HistoricalKlinesType.FUTURES == klines_type:\n            return await self.futures_klines(**params)\n        elif HistoricalKlinesType.FUTURES_COIN == klines_type:\n            return await self.futures_coin_klines(**params)\n        elif HistoricalKlinesType.FUTURES_MARK_PRICE == klines_type:\n            return await self.futures_mark_price_klines(**params)\n        elif HistoricalKlinesType.FUTURES_INDEX_PRICE == klines_type:\n            return await self.futures_index_price_klines(**params)\n        elif HistoricalKlinesType.FUTURES_COIN_MARK_PRICE == klines_type:\n            return await self.futures_coin_mark_price_klines(**params)\n        elif HistoricalKlinesType.FUTURES_COIN_INDEX_PRICE == klines_type:\n            return await self.futures_coin_index_price_klines(**params)\n        else:\n            raise NotImplementedException(klines_type)\n\n    _klines.__doc__ = Client._klines.__doc__\n\n    async def _get_earliest_valid_timestamp(\n        self,\n        symbol,\n        interval,\n        klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT,\n    ):\n        kline = await self._klines(\n            klines_type=klines_type,\n            symbol=symbol,\n            interval=interval,\n            limit=1,\n            startTime=0,\n            endTime=int(time.time() * 1000),\n        )\n        return kline[0][0]\n\n    _get_earliest_valid_timestamp.__doc__ = Client._get_earliest_valid_timestamp.__doc__\n\n    async def get_historical_klines(\n        self,\n        symbol,\n        interval,\n        start_str=None,\n        end_str=None,\n        limit=None,\n        klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT,\n    ):\n        return await self._historical_klines(\n            symbol,\n            interval,\n            start_str,\n            end_str=end_str,\n            limit=limit,\n            klines_type=klines_type,\n        )\n\n    get_historical_klines.__doc__ = Client.get_historical_klines.__doc__\n\n    async def _historical_klines(\n        self,\n        symbol,\n        interval,\n        start_str=None,\n        end_str=None,\n        limit=None,\n        klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT,\n    ):\n        initial_limit_set = True\n        if limit is None:\n            limit = 1000\n            initial_limit_set = False\n\n        # init our list\n        output_data = []\n\n        # convert interval to useful value in seconds\n        timeframe = interval_to_milliseconds(interval)\n\n        # establish first available start timestamp\n        start_ts = convert_ts_str(start_str)\n        if start_ts is not None:\n            first_valid_ts = await self._get_earliest_valid_timestamp(\n                symbol, interval, klines_type\n            )\n            start_ts = max(start_ts, first_valid_ts)\n\n        # if an end time was passed convert it\n        end_ts = convert_ts_str(end_str)\n        if end_ts and start_ts and end_ts <= start_ts:\n            return output_data\n\n        idx = 0\n        while True:\n            # fetch the klines from start_ts up to max 500 entries or the end_ts if set\n            temp_data = await self._klines(\n                klines_type=klines_type,\n                symbol=symbol,\n                interval=interval,\n                limit=limit,\n                startTime=start_ts,\n                endTime=end_ts,\n            )\n\n            # append this loops data to our output data\n            if temp_data:\n                output_data += temp_data\n\n            # check if output_data is greater than limit and truncate if needed and break loop\n            if initial_limit_set and len(output_data) > limit:\n                output_data = output_data[:limit]\n                break\n\n            # handle the case where exactly the limit amount of data was returned last loop\n            # or check if we received less than the required limit and exit the loop\n            if not len(temp_data) or len(temp_data) < limit:\n                # exit the while loop\n                break\n\n            # set our start timestamp using the last value in the array\n            # and increment next call by our timeframe\n            start_ts = temp_data[-1][0] + timeframe\n\n            # exit loop if we reached end_ts before reaching <limit> klines\n            if end_ts and start_ts >= end_ts:\n                break\n\n            # sleep after every 3rd call to be kind to the API\n            idx += 1\n            if idx % 3 == 0:\n                await asyncio.sleep(1)\n\n        return output_data\n\n    _historical_klines.__doc__ = Client._historical_klines.__doc__\n\n    async def get_historical_klines_generator(\n        self,\n        symbol,\n        interval,\n        start_str=None,\n        end_str=None,\n        limit=1000,\n        klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT,\n    ):\n        return self._historical_klines_generator(\n            symbol,\n            interval,\n            start_str,\n            end_str=end_str,\n            limit=limit,\n            klines_type=klines_type,\n        )\n\n    get_historical_klines_generator.__doc__ = (\n        Client.get_historical_klines_generator.__doc__\n    )\n\n    async def _historical_klines_generator(\n        self,\n        symbol,\n        interval,\n        start_str=None,\n        end_str=None,\n        limit=1000,\n        klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT,\n    ):\n        # convert interval to useful value in seconds\n        timeframe = interval_to_milliseconds(interval)\n\n        # if a start time was passed convert it\n        start_ts = convert_ts_str(start_str)\n\n        # establish first available start timestamp\n        if start_ts is not None:\n            first_valid_ts = await self._get_earliest_valid_timestamp(\n                symbol, interval, klines_type\n            )\n            start_ts = max(start_ts, first_valid_ts)\n\n        # if an end time was passed convert it\n        end_ts = convert_ts_str(end_str)\n        if end_ts and start_ts and end_ts <= start_ts:\n            return\n\n        idx = 0\n        while True:\n            # fetch the klines from start_ts up to max 500 entries or the end_ts if set\n            output_data = await self._klines(\n                klines_type=klines_type,\n                symbol=symbol,\n                interval=interval,\n                limit=limit,\n                startTime=start_ts,\n                endTime=end_ts,\n            )\n\n            # yield data\n            if output_data:\n                for o in output_data:\n                    yield o\n\n            # handle the case where exactly the limit amount of data was returned last loop\n            # check if we received less than the required limit and exit the loop\n            if not len(output_data) or len(output_data) < limit:\n                # exit the while loop\n                break\n\n            # increment next call by our timeframe\n            start_ts = output_data[-1][0] + timeframe\n\n            # exit loop if we reached end_ts before reaching <limit> klines\n            if end_ts and start_ts >= end_ts:\n                break\n\n            # sleep after every 3rd call to be kind to the API\n            idx += 1\n            if idx % 3 == 0:\n                await asyncio.sleep(1)\n\n    _historical_klines_generator.__doc__ = Client._historical_klines_generator.__doc__\n\n    async def get_avg_price(self, **params):\n        return await self._get(\n            \"avgPrice\", data=params\n        )\n\n    get_avg_price.__doc__ = Client.get_avg_price.__doc__\n\n    async def get_ticker(self, **params):\n        return await self._get(\n            \"ticker/24hr\", data=params\n        )\n\n    get_ticker.__doc__ = Client.get_ticker.__doc__\n\n    async def get_symbol_ticker(self, **params):\n        return await self._get(\n            \"ticker/price\", data=params\n        )\n\n    get_symbol_ticker.__doc__ = Client.get_symbol_ticker.__doc__\n\n    async def get_symbol_ticker_window(self, **params):\n        return await self._get(\"ticker\", data=params)\n\n    get_symbol_ticker_window.__doc__ = Client.get_symbol_ticker_window.__doc__\n\n    async def get_orderbook_ticker(self, **params):\n        return await self._get(\n            \"ticker/bookTicker\", data=params\n        )\n\n    get_orderbook_ticker.__doc__ = Client.get_orderbook_ticker.__doc__\n\n    # Account Endpoints\n\n    async def create_order(self, **params):\n        if \"newClientOrderId\" not in params:\n            params[\"newClientOrderId\"] = self.SPOT_ORDER_PREFIX + self.uuid22()\n        return await self._post(\"order\", True, data=params)\n\n    create_order.__doc__ = Client.create_order.__doc__\n\n    async def order_limit(self, timeInForce=BaseClient.TIME_IN_FORCE_GTC, **params):\n        params.update({\"type\": self.ORDER_TYPE_LIMIT, \"timeInForce\": timeInForce})\n        return await self.create_order(**params)\n\n    order_limit.__doc__ = Client.order_limit.__doc__\n\n    async def order_limit_buy(self, timeInForce=BaseClient.TIME_IN_FORCE_GTC, **params):\n        params.update({\n            \"side\": self.SIDE_BUY,\n        })\n        return await self.order_limit(timeInForce=timeInForce, **params)\n\n    order_limit_buy.__doc__ = Client.order_limit_buy.__doc__\n\n    async def order_limit_sell(\n        self, timeInForce=BaseClient.TIME_IN_FORCE_GTC, **params\n    ):\n        params.update({\"side\": self.SIDE_SELL})\n        return await self.order_limit(timeInForce=timeInForce, **params)\n\n    order_limit_sell.__doc__ = Client.order_limit_sell.__doc__\n\n    async def order_market(self, **params):\n        params.update({\"type\": self.ORDER_TYPE_MARKET})\n        return await self.create_order(**params)\n\n    order_market.__doc__ = Client.order_market.__doc__\n\n    async def order_market_buy(self, **params):\n        params.update({\"side\": self.SIDE_BUY})\n        return await self.order_market(**params)\n\n    order_market_buy.__doc__ = Client.order_market_buy.__doc__\n\n    async def order_market_sell(self, **params):\n        params.update({\"side\": self.SIDE_SELL})\n        return await self.order_market(**params)\n\n    order_market_sell.__doc__ = Client.order_market_sell.__doc__\n\n    async def order_oco_buy(self, **params):\n        params.update({\"side\": self.SIDE_BUY})\n        return await self.create_oco_order(**params)\n\n    order_oco_buy.__doc__ = Client.order_oco_buy.__doc__\n\n    async def order_oco_sell(self, **params):\n        params.update({\"side\": self.SIDE_SELL})\n        return await self.create_oco_order(**params)\n\n    order_oco_sell.__doc__ = Client.order_oco_sell.__doc__\n\n    async def create_test_order(self, **params):\n        return await self._post(\"order/test\", True, data=params)\n\n    create_test_order.__doc__ = Client.create_test_order.__doc__\n\n    async def get_order(self, **params):\n        return await self._get(\"order\", True, data=params)\n\n    get_order.__doc__ = Client.get_order.__doc__\n\n    async def get_all_orders(self, **params):\n        return await self._get(\"allOrders\", True, data=params)\n\n    get_all_orders.__doc__ = Client.get_all_orders.__doc__\n\n    async def cancel_order(self, **params):\n        return await self._delete(\"order\", True, data=params)\n\n    cancel_order.__doc__ = Client.cancel_order.__doc__\n\n    async def get_open_orders(self, **params):\n        return await self._get(\"openOrders\", True, data=params)\n\n    get_open_orders.__doc__ = Client.get_open_orders.__doc__\n\n    async def get_open_oco_orders(self, **params):\n        return await self._get(\"openOrderList\", True, data=params)\n\n    get_open_oco_orders.__doc__ = Client.get_open_oco_orders.__doc__\n\n    # User Stream Endpoints\n    async def get_account(self, **params):\n        return await self._get(\"account\", True, data=params)\n\n    get_account.__doc__ = Client.get_account.__doc__\n\n    async def get_asset_balance(self, asset=None, **params):\n        res = await self.get_account(**params)\n        # find asset balance in list of balances\n        if \"balances\" in res:\n            if asset:\n                for bal in res[\"balances\"]:\n                    if bal[\"asset\"].lower() == asset.lower():\n                        return bal\n            else:\n                return res[\"balances\"]\n        return None\n\n    get_asset_balance.__doc__ = Client.get_asset_balance.__doc__\n\n    async def get_my_trades(self, **params):\n        return await self._get(\"myTrades\", True, data=params)\n\n    get_my_trades.__doc__ = Client.get_my_trades.__doc__\n\n    async def get_current_order_count(self, **params):\n        return await self._get(\"rateLimit/order\", True, data=params)\n\n    get_current_order_count.__doc__ = Client.get_current_order_count.__doc__\n\n    async def get_prevented_matches(self, **params):\n        return await self._get(\"myPreventedMatches\", True, data=params)\n\n    get_prevented_matches.__doc__ = Client.get_prevented_matches.__doc__\n\n    async def get_allocations(self, **params):\n        return await self._get(\"myAllocations\", True, data=params)\n\n    get_allocations.__doc__ = Client.get_allocations.__doc__\n\n    async def get_system_status(self):\n        return await self._request_margin_api(\"get\", \"system/status\")\n\n    get_system_status.__doc__ = Client.get_system_status.__doc__\n\n    async def get_account_status(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"account/status\", True, data=params\n        )\n\n    get_account_status.__doc__ = Client.get_account_status.__doc__\n\n    async def get_account_api_trading_status(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"account/apiTradingStatus\", True, data=params\n        )\n\n    get_account_api_trading_status.__doc__ = (\n        Client.get_account_api_trading_status.__doc__\n    )\n\n    async def get_account_api_permissions(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"account/apiRestrictions\", True, data=params\n        )\n\n    get_account_api_permissions.__doc__ = Client.get_account_api_permissions.__doc__\n\n    async def get_dust_assets(self, **params):\n        return await self._request_margin_api(\n            \"post\", \"asset/dust-btc\", True, data=params\n        )\n\n    get_dust_assets.__doc__ = Client.get_dust_assets.__doc__\n\n    async def get_dust_log(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"asset/dribblet\", True, data=params\n        )\n\n    get_dust_log.__doc__ = Client.get_dust_log.__doc__\n\n    async def transfer_dust(self, **params):\n        return await self._request_margin_api(\"post\", \"asset/dust\", True, data=params)\n\n    transfer_dust.__doc__ = Client.transfer_dust.__doc__\n\n    async def get_asset_dividend_history(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"asset/assetDividend\", True, data=params\n        )\n\n    get_asset_dividend_history.__doc__ = Client.get_asset_dividend_history.__doc__\n\n    async def make_universal_transfer(self, **params):\n        return await self._request_margin_api(\n            \"post\", \"asset/transfer\", signed=True, data=params\n        )\n\n    make_universal_transfer.__doc__ = Client.make_universal_transfer.__doc__\n\n    async def query_universal_transfer_history(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"asset/transfer\", signed=True, data=params\n        )\n\n    query_universal_transfer_history.__doc__ = (\n        Client.query_universal_transfer_history.__doc__\n    )\n\n    async def get_trade_fee(self, **params):\n        if self.tld == \"us\":\n            endpoint = \"asset/query/trading-fee\"\n        else:\n            endpoint = \"asset/tradeFee\"\n        return await self._request_margin_api(\"get\", endpoint, True, data=params)\n\n    get_trade_fee.__doc__ = Client.get_trade_fee.__doc__\n\n    async def get_asset_details(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"asset/assetDetail\", True, data=params\n        )\n\n    get_asset_details.__doc__ = Client.get_asset_details.__doc__\n\n    async def get_spot_delist_schedule(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"/spot/delist-schedule\", signed=False, data=params\n        )\n\n    get_spot_delist_schedule.__doc__ = Client.get_spot_delist_schedule.__doc__\n\n    # Withdraw Endpoints\n\n    async def withdraw(self, **params):\n        # force a name for the withdrawal if one not set\n        if \"coin\" in params and \"name\" not in params:\n            params[\"name\"] = params[\"coin\"]\n        return await self._request_margin_api(\n            \"post\", \"capital/withdraw/apply\", True, data=params\n        )\n\n    withdraw.__doc__ = Client.withdraw.__doc__\n\n    async def get_deposit_history(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"capital/deposit/hisrec\", True, data=params\n        )\n\n    get_deposit_history.__doc__ = Client.get_deposit_history.__doc__\n\n    async def get_withdraw_history(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"capital/withdraw/history\", True, data=params\n        )\n\n    get_withdraw_history.__doc__ = Client.get_withdraw_history.__doc__\n\n    async def get_withdraw_history_id(self, withdraw_id, **params):\n        result = await self.get_withdraw_history(**params)\n\n        for entry in result:\n            if \"id\" in entry and entry[\"id\"] == withdraw_id:\n                return entry\n\n        raise Exception(\"There is no entry with withdraw id\", result)\n\n    get_withdraw_history_id.__doc__ = Client.get_withdraw_history_id.__doc__\n\n    async def get_deposit_address(\n        self, coin: str, network: Optional[str] = None, **params\n    ):\n        params[\"coin\"] = coin\n        if network:\n            params[\"network\"] = network\n        return await self._request_margin_api(\n            \"get\", \"capital/deposit/address\", True, data=params\n        )\n\n    get_deposit_address.__doc__ = Client.get_deposit_address.__doc__\n\n    # User Stream Endpoints\n\n    async def stream_get_listen_key(self):\n        res = await self._post(\"userDataStream\", False, data={})\n        return res[\"listenKey\"]\n\n    stream_get_listen_key.__doc__ = Client.stream_get_listen_key.__doc__\n\n    async def stream_keepalive(self, listenKey):\n        params = {\"listenKey\": listenKey}\n        return await self._put(\"userDataStream\", False, data=params)\n\n    stream_keepalive.__doc__ = Client.stream_keepalive.__doc__\n\n    async def stream_close(self, listenKey):\n        params = {\"listenKey\": listenKey}\n        return await self._delete(\"userDataStream\", False, data=params)\n\n    stream_close.__doc__ = Client.stream_close.__doc__\n\n    # Margin Trading Endpoints\n    async def get_margin_account(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"margin/account\", True, data=params\n        )\n\n    get_margin_account.__doc__ = Client.get_margin_account.__doc__\n\n    async def get_isolated_margin_account(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"margin/isolated/account\", True, data=params\n        )\n\n    get_isolated_margin_account.__doc__ = Client.get_isolated_margin_account.__doc__\n\n    async def enable_isolated_margin_account(self, **params):\n        return await self._request_margin_api(\n            \"post\", \"margin/isolated/account\", True, data=params\n        )\n\n    enable_isolated_margin_account.__doc__ = (\n        Client.enable_isolated_margin_account.__doc__\n    )\n\n    async def disable_isolated_margin_account(self, **params):\n        return await self._request_margin_api(\n            \"delete\", \"margin/isolated/account\", True, data=params\n        )\n\n    disable_isolated_margin_account.__doc__ = (\n        Client.disable_isolated_margin_account.__doc__\n    )\n\n    async def get_enabled_isolated_margin_account_limit(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"margin/isolated/accountLimit\", True, data=params\n        )\n\n    get_enabled_isolated_margin_account_limit.__doc__ = (\n        Client.get_enabled_isolated_margin_account_limit.__doc__\n    )\n\n    async def get_margin_dustlog(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"margin/dribblet\", True, data=params\n        )\n\n    get_margin_dustlog.__doc__ = Client.get_margin_dustlog.__doc__\n\n    async def get_margin_dust_assets(self, **params):\n        return await self._request_margin_api(\"get\", \"margin/dust\", True, data=params)\n\n    get_margin_dust_assets.__doc__ = Client.get_margin_dust_assets.__doc__\n\n    async def transfer_margin_dust(self, **params):\n        return await self._request_margin_api(\"post\", \"margin/dust\", True, data=params)\n\n    transfer_margin_dust.__doc__ = Client.transfer_margin_dust.__doc__\n\n    async def get_cross_margin_collateral_ratio(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"margin/crossMarginCollateralRatio\", True, data=params\n        )\n\n    get_cross_margin_collateral_ratio.__doc__ = (\n        Client.get_cross_margin_collateral_ratio.__doc__\n    )\n\n    async def get_small_liability_exchange_assets(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"margin/exchange-small-liability\", True, data=params\n        )\n\n    get_small_liability_exchange_assets.__doc__ = (\n        Client.get_small_liability_exchange_assets.__doc__\n    )\n\n    async def exchange_small_liability_assets(self, **params):\n        return await self._request_margin_api(\n            \"post\", \"margin/exchange-small-liability\", True, data=params\n        )\n\n    exchange_small_liability_assets.__doc__ = (\n        Client.exchange_small_liability_assets.__doc__\n    )\n\n    async def get_small_liability_exchange_history(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"margin/exchange-small-liability-history\", True, data=params\n        )\n\n    get_small_liability_exchange_history.__doc__ = (\n        Client.get_small_liability_exchange_history.__doc__\n    )\n\n    async def get_future_hourly_interest_rate(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"margin/next-hourly-interest-rate\", True, data=params\n        )\n\n    get_future_hourly_interest_rate.__doc__ = (\n        Client.get_future_hourly_interest_rate.__doc__\n    )\n\n    async def get_margin_capital_flow(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"margin/capital-flow\", True, data=params\n        )\n\n    get_margin_capital_flow.__doc__ = Client.get_margin_capital_flow.__doc__\n\n    async def get_margin_delist_schedule(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"margin/delist-schedule\", True, data=params\n        )\n\n    get_margin_delist_schedule.__doc__ = Client.get_margin_delist_schedule.__doc__\n\n    async def get_margin_asset(self, **params):\n        return await self._request_margin_api(\"get\", \"margin/asset\", data=params)\n\n    get_margin_asset.__doc__ = Client.get_margin_asset.__doc__\n\n    async def get_margin_symbol(self, **params):\n        return await self._request_margin_api(\"get\", \"margin/pair\", data=params)\n\n    get_margin_symbol.__doc__ = Client.get_margin_symbol.__doc__\n\n    async def get_margin_all_assets(self, **params):\n        return await self._request_margin_api(\"get\", \"margin/allAssets\", data=params)\n\n    get_margin_all_assets.__doc__ = Client.get_margin_all_assets.__doc__\n\n    async def get_margin_all_pairs(self, **params):\n        return await self._request_margin_api(\"get\", \"margin/allPairs\", data=params)\n\n    get_margin_all_pairs.__doc__ = Client.get_margin_all_pairs.__doc__\n\n    async def create_isolated_margin_account(self, **params):\n        return await self._request_margin_api(\n            \"post\", \"margin/isolated/create\", signed=True, data=params\n        )\n\n    create_isolated_margin_account.__doc__ = (\n        Client.create_isolated_margin_account.__doc__\n    )\n\n    async def get_isolated_margin_symbol(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"margin/isolated/pair\", signed=True, data=params\n        )\n\n    get_isolated_margin_symbol.__doc__ = Client.get_isolated_margin_symbol.__doc__\n\n    async def get_all_isolated_margin_symbols(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"margin/isolated/allPairs\", signed=True, data=params\n        )\n\n    get_all_isolated_margin_symbols.__doc__ = (\n        Client.get_all_isolated_margin_symbols.__doc__\n    )\n\n    async def get_isolated_margin_fee_data(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"margin/isolatedMarginData\", True, data=params\n        )\n\n    get_isolated_margin_fee_data.__doc__ = Client.get_isolated_margin_fee_data.__doc__\n\n    async def get_isolated_margin_tier_data(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"margin/isolatedMarginTier\", True, data=params\n        )\n\n    get_isolated_margin_tier_data.__doc__ = Client.get_isolated_margin_tier_data.__doc__\n\n    async def margin_manual_liquidation(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"margin/manual-liquidation\", True, data=params\n        )\n\n    margin_manual_liquidation.__doc__ = Client.margin_manual_liquidation.__doc__\n\n    async def toggle_bnb_burn_spot_margin(self, **params):\n        return await self._request_margin_api(\n            \"post\", \"bnbBurn\", signed=True, data=params\n        )\n\n    toggle_bnb_burn_spot_margin.__doc__ = Client.toggle_bnb_burn_spot_margin.__doc__\n\n    async def get_bnb_burn_spot_margin(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"bnbBurn\", signed=True, data=params\n        )\n\n    get_bnb_burn_spot_margin.__doc__ = Client.get_bnb_burn_spot_margin.__doc__\n\n    async def get_margin_price_index(self, **params):\n        return await self._request_margin_api(\"get\", \"margin/priceIndex\", data=params)\n\n    get_margin_price_index.__doc__ = Client.get_margin_price_index.__doc__\n\n    async def transfer_margin_to_spot(self, **params):\n        params[\"type\"] = 2\n        return await self._request_margin_api(\n            \"post\", \"margin/transfer\", signed=True, data=params\n        )\n\n    transfer_margin_to_spot.__doc__ = Client.transfer_margin_to_spot.__doc__\n\n    async def transfer_spot_to_margin(self, **params):\n        params[\"type\"] = 1\n        return await self._request_margin_api(\n            \"post\", \"margin/transfer\", signed=True, data=params\n        )\n\n    transfer_spot_to_margin.__doc__ = Client.transfer_spot_to_margin.__doc__\n\n    async def transfer_isolated_margin_to_spot(self, **params):\n        params[\"transFrom\"] = \"ISOLATED_MARGIN\"\n        params[\"transTo\"] = \"SPOT\"\n        return await self._request_margin_api(\n            \"post\", \"margin/isolated/transfer\", signed=True, data=params\n        )\n\n    transfer_isolated_margin_to_spot.__doc__ = (\n        Client.transfer_isolated_margin_to_spot.__doc__\n    )\n\n    async def transfer_spot_to_isolated_margin(self, **params):\n        params[\"transFrom\"] = \"SPOT\"\n        params[\"transTo\"] = \"ISOLATED_MARGIN\"\n        return await self._request_margin_api(\n            \"post\", \"margin/isolated/transfer\", signed=True, data=params\n        )\n\n    transfer_spot_to_isolated_margin.__doc__ = (\n        Client.transfer_spot_to_isolated_margin.__doc__\n    )\n\n    async def create_margin_loan(self, **params):\n        return await self._request_margin_api(\n            \"post\", \"margin/loan\", signed=True, data=params\n        )\n\n    create_margin_loan.__doc__ = Client.create_margin_loan.__doc__\n\n    async def repay_margin_loan(self, **params):\n        return await self._request_margin_api(\n            \"post\", \"margin/repay\", signed=True, data=params\n        )\n\n    repay_margin_loan.__doc__ = Client.repay_margin_loan.__doc__\n\n    async def create_margin_order(self, **params):\n        if \"newClientOrderId\" not in params:\n            params[\"newClientOrderId\"] = self.SPOT_ORDER_PREFIX + self.uuid22()\n        return await self._request_margin_api(\n            \"post\", \"margin/order\", signed=True, data=params\n        )\n\n    create_margin_order.__doc__ = Client.create_margin_order.__doc__\n\n    async def cancel_margin_order(self, **params):\n        return await self._request_margin_api(\n            \"delete\", \"margin/order\", signed=True, data=params\n        )\n\n    cancel_margin_order.__doc__ = Client.cancel_margin_order.__doc__\n\n    async def cancel_all_open_margin_orders(self, **params):\n        return await self._request_margin_api(\n            \"delete\", \"margin/openOrders\", signed=True, data=params\n        )\n\n    cancel_all_open_margin_orders.__doc__ = Client.cancel_all_open_margin_orders.__doc__\n\n    async def set_margin_max_leverage(self, **params):\n        return await self._request_margin_api(\n            \"post\", \"margin/max-leverage\", signed=True, data=params\n        )\n\n    set_margin_max_leverage.__doc__ = Client.set_margin_max_leverage.__doc__\n\n    async def get_margin_transfer_history(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"margin/transfer\", signed=True, data=params\n        )\n\n    get_margin_transfer_history.__doc__ = Client.get_margin_transfer_history.__doc__\n\n    async def get_margin_loan_details(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"margin/loan\", signed=True, data=params\n        )\n\n    get_margin_loan_details.__doc__ = Client.get_margin_loan_details.__doc__\n\n    async def get_margin_repay_details(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"margin/repay\", signed=True, data=params\n        )\n\n    get_margin_repay_details.__doc__ = Client.get_margin_repay_details.__doc__\n\n    async def get_cross_margin_data(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"margin/crossMarginData\", signed=True, data=params\n        )\n\n    get_cross_margin_data.__doc__ = Client.get_cross_margin_data.__doc__\n\n    async def get_margin_interest_history(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"margin/interestHistory\", signed=True, data=params\n        )\n\n    get_margin_interest_history.__doc__ = Client.get_margin_interest_history.__doc__\n\n    async def get_margin_force_liquidation_rec(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"margin/forceLiquidationRec\", signed=True, data=params\n        )\n\n    get_margin_force_liquidation_rec.__doc__ = Client.get_margin_force_liquidation_rec.__doc__\n\n    async def get_margin_order(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"margin/order\", signed=True, data=params\n        )\n\n    get_margin_order.__doc__ = Client.get_margin_order.__doc__\n\n    async def get_open_margin_orders(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"margin/openOrders\", signed=True, data=params\n        )\n\n    get_open_margin_orders.__doc__ = Client.get_open_margin_orders.__doc__\n\n    async def get_all_margin_orders(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"margin/allOrders\", signed=True, data=params\n        )\n\n    get_all_margin_orders.__doc__ = Client.get_all_margin_orders.__doc__\n\n    async def get_margin_trades(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"margin/myTrades\", signed=True, data=params\n        )\n\n    get_margin_trades.__doc__ = Client.get_margin_trades.__doc__\n\n    async def get_max_margin_loan(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"margin/maxBorrowable\", signed=True, data=params\n        )\n\n    get_max_margin_loan.__doc__ = Client.get_max_margin_loan.__doc__\n\n    async def get_max_margin_transfer(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"margin/maxTransferable\", signed=True, data=params\n        )\n\n    # Margin OCO\n\n    get_max_margin_transfer.__doc__ = Client.get_max_margin_transfer.__doc__\n\n    async def create_margin_oco_order(self, **params):\n        return await self._request_margin_api(\n            \"post\", \"margin/order/oco\", signed=True, data=params\n        )\n\n    create_margin_oco_order.__doc__ = Client.create_margin_oco_order.__doc__\n\n    async def cancel_margin_oco_order(self, **params):\n        return await self._request_margin_api(\n            \"delete\", \"margin/orderList\", signed=True, data=params\n        )\n\n    cancel_margin_oco_order.__doc__ = Client.cancel_margin_oco_order.__doc__\n\n    async def get_margin_oco_order(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"margin/orderList\", signed=True, data=params\n        )\n\n    get_margin_oco_order.__doc__ = Client.get_margin_oco_order.__doc__\n\n    async def get_open_margin_oco_orders(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"margin/openOrderList\", signed=True, data=params\n        )\n\n    # Cross-margin\n\n    get_open_margin_oco_orders.__doc__ = Client.get_open_margin_oco_orders.__doc__\n\n    async def margin_stream_get_listen_key(self):\n        warnings.warn(\n            \"POST /sapi/v1/userDataStream is deprecated and will be removed on 2026-02-20. \"\n            \"Use the WebSocket API subscription method instead (create listenToken via POST /sapi/v1/userListenToken, \"\n            \"then subscribe with userDataStream.subscribe.listenToken). \"\n            \"The margin_socket() method now uses WebSocket API by default.\",\n            DeprecationWarning,\n            stacklevel=2\n        )\n        res = await self._request_margin_api(\n            \"post\", \"userDataStream\", signed=False, data={}\n        )\n        return res[\"listenKey\"]\n\n    margin_stream_get_listen_key.__doc__ = Client.margin_stream_get_listen_key.__doc__\n\n    async def margin_stream_keepalive(self, listenKey):\n        warnings.warn(\n            \"PUT /sapi/v1/userDataStream is deprecated and will be removed on 2026-02-20. \"\n            \"Use the WebSocket API subscription method instead (create listenToken via POST /sapi/v1/userListenToken, \"\n            \"then subscribe with userDataStream.subscribe.listenToken). \"\n            \"The margin_socket() method now uses WebSocket API by default.\",\n            DeprecationWarning,\n            stacklevel=2\n        )\n        params = {\"listenKey\": listenKey}\n        return await self._request_margin_api(\n            \"put\", \"userDataStream\", signed=False, data=params\n        )\n\n    margin_stream_keepalive.__doc__ = Client.margin_stream_keepalive.__doc__\n\n    async def margin_stream_close(self, listenKey):\n        warnings.warn(\n            \"DELETE /sapi/v1/userDataStream is deprecated and will be removed on 2026-02-20. \"\n            \"Use the WebSocket API subscription method instead (create listenToken via POST /sapi/v1/userListenToken, \"\n            \"then subscribe with userDataStream.subscribe.listenToken). \"\n            \"The margin_socket() method now uses WebSocket API by default.\",\n            DeprecationWarning,\n            stacklevel=2\n        )\n        params = {\"listenKey\": listenKey}\n        return await self._request_margin_api(\n            \"delete\", \"userDataStream\", signed=False, data=params\n        )\n\n    async def margin_create_listen_token(self, symbol: Optional[str] = None, is_isolated: bool = False, validity: Optional[int] = None):\n        \"\"\"Create a listenToken for margin account user data stream\n\n        https://developers.binance.com/docs/margin_trading/trade-data-stream/Create-Margin-Account-listenToken\n\n        :param symbol: Trading pair symbol (required when is_isolated=True)\n        :type symbol: str\n        :param is_isolated: Whether it is isolated margin (default: False for cross-margin)\n        :type is_isolated: bool\n        :param validity: Validity in milliseconds (default: 24 hours, max: 24 hours)\n        :type validity: int\n        :returns: API response with token and expirationTime\n\n        .. code-block:: python\n\n            {\n                \"token\": \"6xXxePXwZRjVSHKhzUCCGnmN3fkvMTXru+pYJS8RwijXk9Vcyr3rkwfVOTcP2OkONqciYA\",\n                \"expirationTime\": 1758792204196\n            }\n        \"\"\"\n        params = {}\n        if is_isolated:\n            if not symbol:\n                raise ValueError(\"symbol is required when is_isolated=True\")\n            params[\"symbol\"] = symbol\n            params[\"isIsolated\"] = \"true\"\n        if validity is not None:\n            params[\"validity\"] = validity\n\n        return await self._request_margin_api(\n            \"post\", \"userListenToken\", signed=True, data=params\n        )\n\n        # Isolated margin\n\n    margin_stream_close.__doc__ = Client.margin_stream_close.__doc__\n\n    async def isolated_margin_stream_get_listen_key(self, symbol):\n        warnings.warn(\n            \"POST /sapi/v1/userDataStream/isolated is deprecated and will be removed on 2026-02-20. \"\n            \"Use the WebSocket API subscription method instead (create listenToken via POST /sapi/v1/userListenToken \"\n            \"with isIsolated=true, then subscribe with userDataStream.subscribe.listenToken). \"\n            \"The isolated_margin_socket() method now uses WebSocket API by default.\",\n            DeprecationWarning,\n            stacklevel=2\n        )\n        params = {\"symbol\": symbol}\n        res = await self._request_margin_api(\n            \"post\", \"userDataStream/isolated\", signed=False, data=params\n        )\n        return res[\"listenKey\"]\n\n    isolated_margin_stream_get_listen_key.__doc__ = Client.isolated_margin_stream_get_listen_key.__doc__\n\n    async def isolated_margin_stream_keepalive(self, symbol, listenKey):\n        warnings.warn(\n            \"PUT /sapi/v1/userDataStream/isolated is deprecated and will be removed on 2026-02-20. \"\n            \"Use the WebSocket API subscription method instead (create listenToken via POST /sapi/v1/userListenToken \"\n            \"with isIsolated=true, then subscribe with userDataStream.subscribe.listenToken). \"\n            \"The isolated_margin_socket() method now uses WebSocket API by default.\",\n            DeprecationWarning,\n            stacklevel=2\n        )\n        params = {\"symbol\": symbol, \"listenKey\": listenKey}\n        return await self._request_margin_api(\n            \"put\", \"userDataStream/isolated\", signed=False, data=params\n        )\n\n    isolated_margin_stream_keepalive.__doc__ = Client.isolated_margin_stream_keepalive.__doc__\n\n    async def isolated_margin_stream_close(self, symbol, listenKey):\n        warnings.warn(\n            \"DELETE /sapi/v1/userDataStream/isolated is deprecated and will be removed on 2026-02-20. \"\n            \"Use the WebSocket API subscription method instead (create listenToken via POST /sapi/v1/userListenToken \"\n            \"with isIsolated=true, then subscribe with userDataStream.subscribe.listenToken). \"\n            \"The isolated_margin_socket() method now uses WebSocket API by default.\",\n            DeprecationWarning,\n            stacklevel=2\n        )\n        params = {\"symbol\": symbol, \"listenKey\": listenKey}\n        return await self._request_margin_api(\n            \"delete\", \"userDataStream/isolated\", signed=False, data=params\n        )\n\n    # Simple Earn Endpoints\n\n    isolated_margin_stream_close.__doc__ = Client.isolated_margin_stream_close.__doc__\n\n    async def get_simple_earn_flexible_product_list(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"simple-earn/flexible/list\", signed=True, data=params\n        )\n\n    get_simple_earn_flexible_product_list.__doc__ = (\n        Client.get_simple_earn_flexible_product_list.__doc__\n    )\n\n    async def get_simple_earn_locked_product_list(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"simple-earn/locked/list\", signed=True, data=params\n        )\n\n    get_simple_earn_locked_product_list.__doc__ = (\n        Client.get_simple_earn_locked_product_list.__doc__\n    )\n\n    async def subscribe_simple_earn_flexible_product(self, **params):\n        return await self._request_margin_api(\n            \"post\", \"simple-earn/flexible/subscribe\", signed=True, data=params\n        )\n\n    subscribe_simple_earn_flexible_product.__doc__ = (\n        Client.subscribe_simple_earn_flexible_product.__doc__\n    )\n\n    async def subscribe_simple_earn_locked_product(self, **params):\n        return await self._request_margin_api(\n            \"post\", \"simple-earn/locked/subscribe\", signed=True, data=params\n        )\n\n    subscribe_simple_earn_locked_product.__doc__ = (\n        Client.subscribe_simple_earn_locked_product.__doc__\n    )\n\n    async def redeem_simple_earn_flexible_product(self, **params):\n        return await self._request_margin_api(\n            \"post\", \"simple-earn/flexible/redeem\", signed=True, data=params\n        )\n\n    redeem_simple_earn_flexible_product.__doc__ = (\n        Client.redeem_simple_earn_flexible_product.__doc__\n    )\n\n    async def redeem_simple_earn_locked_product(self, **params):\n        return await self._request_margin_api(\n            \"post\", \"simple-earn/locked/redeem\", signed=True, data=params\n        )\n\n    redeem_simple_earn_locked_product.__doc__ = (\n        Client.redeem_simple_earn_locked_product.__doc__\n    )\n\n    async def get_simple_earn_flexible_product_position(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"simple-earn/flexible/position\", signed=True, data=params\n        )\n\n    get_simple_earn_flexible_product_position.__doc__ = (\n        Client.get_simple_earn_flexible_product_position.__doc__\n    )\n\n    async def get_simple_earn_locked_product_position(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"simple-earn/locked/position\", signed=True, data=params\n        )\n\n    get_simple_earn_locked_product_position.__doc__ = (\n        Client.get_simple_earn_locked_product_position.__doc__\n    )\n\n    async def get_simple_earn_account(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"simple-earn/account\", signed=True, data=params\n        )\n\n    get_simple_earn_account.__doc__ = Client.get_simple_earn_account.__doc__\n\n    # Lending Endpoints\n\n    async def get_fixed_activity_project_list(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"lending/project/list\", signed=True, data=params\n        )\n\n    get_fixed_activity_project_list.__doc__ = Client.get_fixed_activity_project_list.__doc__\n\n    async def change_fixed_activity_to_daily_position(self, **params):\n        return await self._request_margin_api(\n            \"post\", \"lending/positionChanged\", signed=True, data=params\n        )\n\n    # Staking Endpoints\n\n    change_fixed_activity_to_daily_position.__doc__ = Client.change_fixed_activity_to_daily_position.__doc__\n\n    async def get_staking_product_list(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"staking/productList\", signed=True, data=params\n        )\n\n    get_staking_product_list.__doc__ = Client.get_staking_product_list.__doc__\n\n    async def purchase_staking_product(self, **params):\n        return await self._request_margin_api(\n            \"post\", \"staking/purchase\", signed=True, data=params\n        )\n\n    purchase_staking_product.__doc__ = Client.purchase_staking_product.__doc__\n\n    async def redeem_staking_product(self, **params):\n        return await self._request_margin_api(\n            \"post\", \"staking/redeem\", signed=True, data=params\n        )\n\n    redeem_staking_product.__doc__ = Client.redeem_staking_product.__doc__\n\n    async def get_staking_position(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"staking/position\", signed=True, data=params\n        )\n\n    get_staking_position.__doc__ = Client.get_staking_position.__doc__\n\n    async def get_staking_purchase_history(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"staking/purchaseRecord\", signed=True, data=params\n        )\n\n    get_staking_purchase_history.__doc__ = Client.get_staking_purchase_history.__doc__\n\n    async def set_auto_staking(self, **params):\n        return await self._request_margin_api(\n            \"post\", \"staking/setAutoStaking\", signed=True, data=params\n        )\n\n    set_auto_staking.__doc__ = Client.set_auto_staking.__doc__\n\n    async def get_personal_left_quota(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"staking/personalLeftQuota\", signed=True, data=params\n        )\n\n    # US Staking Endpoints\n\n    get_personal_left_quota.__doc__ = Client.get_personal_left_quota.__doc__\n\n    async def get_staking_asset_us(self, **params):\n        self._require_tld(\"us\", \"get_staking_asset_us\")\n        return await self._request_margin_api(\"get\", \"staking/asset\", True, data=params)\n\n    get_staking_asset_us.__doc__ = Client.get_staking_asset_us.__doc__\n\n    async def stake_asset_us(self, **params):\n        self._require_tld(\"us\", \"stake_asset_us\")\n        return await self._request_margin_api(\n            \"post\", \"staking/stake\", True, data=params\n        )\n\n    stake_asset_us.__doc__ = Client.stake_asset_us.__doc__\n\n    async def unstake_asset_us(self, **params):\n        self._require_tld(\"us\", \"unstake_asset_us\")\n        return await self._request_margin_api(\n            \"post\", \"staking/unstake\", True, data=params\n        )\n\n    unstake_asset_us.__doc__ = Client.unstake_asset_us.__doc__\n\n    async def get_staking_balance_us(self, **params):\n        self._require_tld(\"us\", \"get_staking_balance_us\")\n        return await self._request_margin_api(\n            \"get\", \"staking/stakingBalance\", True, data=params\n        )\n\n    get_staking_balance_us.__doc__ = Client.get_staking_balance_us.__doc__\n\n    async def get_staking_history_us(self, **params):\n        self._require_tld(\"us\", \"get_staking_history_us\")\n        return await self._request_margin_api(\n            \"get\", \"staking/history\", True, data=params\n        )\n\n    get_staking_history_us.__doc__ = Client.get_staking_history_us.__doc__\n\n    async def get_staking_rewards_history_us(self, **params):\n        self._require_tld(\"us\", \"get_staking_rewards_history_us\")\n        return await self._request_margin_api(\n            \"get\", \"staking/stakingRewardsHistory\", True, data=params\n        )\n\n    get_staking_rewards_history_us.__doc__ = (\n        Client.get_staking_rewards_history_us.__doc__\n    )\n\n    # Sub Accounts\n\n    async def get_sub_account_list(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"sub-account/list\", True, data=params\n        )\n\n    get_sub_account_list.__doc__ = Client.get_sub_account_list.__doc__\n\n    async def get_sub_account_transfer_history(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"sub-account/sub/transfer/history\", True, data=params\n        )\n\n    get_sub_account_transfer_history.__doc__ = Client.get_sub_account_transfer_history.__doc__\n\n    async def get_sub_account_futures_transfer_history(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"sub-account/futures/internalTransfer\", True, data=params\n        )\n\n    get_sub_account_futures_transfer_history.__doc__ = Client.get_sub_account_futures_transfer_history.__doc__\n\n    async def create_sub_account_futures_transfer(self, **params):\n        return await self._request_margin_api(\n            \"post\", \"sub-account/futures/internalTransfer\", True, data=params\n        )\n\n    create_sub_account_futures_transfer.__doc__ = Client.create_sub_account_futures_transfer.__doc__\n\n    async def get_sub_account_assets(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"sub-account/assets\", True, data=params, version=4\n        )\n\n    get_sub_account_assets.__doc__ = Client.get_sub_account_assets.__doc__\n\n    async def query_subaccount_spot_summary(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"sub-account/spotSummary\", True, data=params\n        )\n\n    query_subaccount_spot_summary.__doc__ = Client.query_subaccount_spot_summary.__doc__\n\n    async def get_subaccount_deposit_address(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"capital/deposit/subAddress\", True, data=params\n        )\n\n    get_subaccount_deposit_address.__doc__ = Client.get_subaccount_deposit_address.__doc__\n\n    async def get_subaccount_deposit_history(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"capital/deposit/subHisrec\", True, data=params\n        )\n\n    get_subaccount_deposit_history.__doc__ = Client.get_subaccount_deposit_history.__doc__\n\n    async def get_subaccount_futures_margin_status(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"sub-account/status\", True, data=params\n        )\n\n    get_subaccount_futures_margin_status.__doc__ = Client.get_subaccount_futures_margin_status.__doc__\n\n    async def enable_subaccount_margin(self, **params):\n        return await self._request_margin_api(\n            \"post\", \"sub-account/margin/enable\", True, data=params\n        )\n\n    enable_subaccount_margin.__doc__ = Client.enable_subaccount_margin.__doc__\n\n    async def get_subaccount_margin_details(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"sub-account/margin/account\", True, data=params\n        )\n\n    get_subaccount_margin_details.__doc__ = Client.get_subaccount_margin_details.__doc__\n\n    async def get_subaccount_margin_summary(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"sub-account/margin/accountSummary\", True, data=params\n        )\n\n    get_subaccount_margin_summary.__doc__ = Client.get_subaccount_margin_summary.__doc__\n\n    async def enable_subaccount_futures(self, **params):\n        return await self._request_margin_api(\n            \"post\", \"sub-account/futures/enable\", True, data=params\n        )\n\n    enable_subaccount_futures.__doc__ = Client.enable_subaccount_futures.__doc__\n\n    async def get_subaccount_futures_details(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"sub-account/futures/account\", True, data=params, version=2\n        )\n\n    get_subaccount_futures_details.__doc__ = Client.get_subaccount_futures_details.__doc__\n\n    async def get_subaccount_futures_summary(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"sub-account/futures/accountSummary\", True, data=params, version=2\n        )\n\n    get_subaccount_futures_summary.__doc__ = Client.get_subaccount_futures_summary.__doc__\n\n    async def get_subaccount_futures_positionrisk(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"sub-account/futures/positionRisk\", True, data=params, version=2\n        )\n\n    get_subaccount_futures_positionrisk.__doc__ = Client.get_subaccount_futures_positionrisk.__doc__\n\n    async def make_subaccount_futures_transfer(self, **params):\n        return await self._request_margin_api(\n            \"post\", \"sub-account/futures/transfer\", True, data=params\n        )\n\n    make_subaccount_futures_transfer.__doc__ = Client.make_subaccount_futures_transfer.__doc__\n\n    async def make_subaccount_margin_transfer(self, **params):\n        return await self._request_margin_api(\n            \"post\", \"sub-account/margin/transfer\", True, data=params\n        )\n\n    make_subaccount_margin_transfer.__doc__ = Client.make_subaccount_margin_transfer.__doc__\n\n    async def make_subaccount_to_subaccount_transfer(self, **params):\n        return await self._request_margin_api(\n            \"post\", \"sub-account/transfer/subToSub\", True, data=params\n        )\n\n    make_subaccount_to_subaccount_transfer.__doc__ = Client.make_subaccount_to_subaccount_transfer.__doc__\n\n    async def make_subaccount_to_master_transfer(self, **params):\n        return await self._request_margin_api(\n            \"post\", \"sub-account/transfer/subToMaster\", True, data=params\n        )\n\n    make_subaccount_to_master_transfer.__doc__ = Client.make_subaccount_to_master_transfer.__doc__\n\n    async def get_subaccount_transfer_history(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"sub-account/transfer/subUserHistory\", True, data=params\n        )\n\n    get_subaccount_transfer_history.__doc__ = Client.get_subaccount_transfer_history.__doc__\n\n    async def make_subaccount_universal_transfer(self, **params):\n        return await self._request_margin_api(\n            \"post\", \"sub-account/universalTransfer\", True, data=params\n        )\n\n    make_subaccount_universal_transfer.__doc__ = Client.make_subaccount_universal_transfer.__doc__\n\n    async def get_universal_transfer_history(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"sub-account/universalTransfer\", True, data=params\n        )\n\n    # Futures API\n\n    get_universal_transfer_history.__doc__ = Client.get_universal_transfer_history.__doc__\n\n    async def futures_ping(self):\n        return await self._request_futures_api(\"get\", \"ping\")\n\n    futures_ping.__doc__ = Client.futures_ping.__doc__\n\n    async def futures_time(self):\n        return await self._request_futures_api(\"get\", \"time\")\n\n    futures_time.__doc__ = Client.futures_time.__doc__\n\n    async def futures_exchange_info(self):\n        return await self._request_futures_api(\"get\", \"exchangeInfo\")\n\n    futures_exchange_info.__doc__ = Client.futures_exchange_info.__doc__\n\n    async def futures_order_book(self, **params):\n        return await self._request_futures_api(\"get\", \"depth\", data=params)\n\n    futures_order_book.__doc__ = Client.futures_order_book.__doc__\n\n    async def futures_rpi_depth(self, **params):\n        return await self._request_futures_api(\"get\", \"rpiDepth\", data=params)\n\n    futures_rpi_depth.__doc__ = Client.futures_rpi_depth.__doc__\n\n    async def futures_recent_trades(self, **params):\n        return await self._request_futures_api(\"get\", \"trades\", data=params)\n\n    futures_recent_trades.__doc__ = Client.futures_recent_trades.__doc__\n\n    async def futures_historical_trades(self, **params):\n        return await self._request_futures_api(\"get\", \"historicalTrades\", data=params)\n\n    futures_historical_trades.__doc__ = Client.futures_historical_trades.__doc__\n\n    async def futures_aggregate_trades(self, **params):\n        return await self._request_futures_api(\"get\", \"aggTrades\", data=params)\n\n    futures_aggregate_trades.__doc__ = Client.futures_aggregate_trades.__doc__\n\n    async def futures_klines(self, **params):\n        return await self._request_futures_api(\"get\", \"klines\", data=params)\n\n    futures_klines.__doc__ = Client.futures_klines.__doc__\n\n    async def futures_mark_price_klines(self, **params):\n        return await self._request_futures_api(\"get\", \"markPriceKlines\", data=params)\n\n    futures_mark_price_klines.__doc__ = Client.futures_mark_price_klines.__doc__\n\n    async def futures_index_price_klines(self, **params):\n        return await self._request_futures_api(\"get\", \"indexPriceKlines\", data=params)\n\n    futures_index_price_klines.__doc__ = Client.futures_index_price_klines.__doc__\n\n    async def futures_premium_index_klines(self, **params):\n        return await self._request_futures_api(\"get\", \"premiumIndexKlines\", data=params)\n\n    futures_premium_index_klines.__doc__ = Client.futures_index_price_klines.__doc__\n\n    async def futures_continuous_klines(self, **params):\n        return await self._request_futures_api(\"get\", \"continuousKlines\", data=params)\n\n    futures_continuous_klines.__doc__ = Client.futures_continuous_klines.__doc__\n\n    async def futures_historical_klines(\n        self, symbol: str, interval: str, start_str, end_str=None, limit=None\n    ):\n        return await self._historical_klines(\n            symbol,\n            interval,\n            start_str,\n            end_str=end_str,\n            limit=limit,\n            klines_type=HistoricalKlinesType.FUTURES,\n        )\n\n    futures_historical_klines.__doc__ = Client.futures_historical_klines.__doc__\n\n    async def futures_historical_klines_generator(\n        self, symbol, interval, start_str, end_str=None\n    ):\n        return self._historical_klines_generator(\n            symbol,\n            interval,\n            start_str,\n            end_str=end_str,\n            klines_type=HistoricalKlinesType.FUTURES,\n        )\n\n    futures_historical_klines_generator.__doc__ = Client.futures_historical_klines_generator.__doc__\n\n    async def futures_mark_price(self, **params):\n        return await self._request_futures_api(\"get\", \"premiumIndex\", data=params)\n\n    futures_mark_price.__doc__ = Client.futures_mark_price.__doc__\n\n    async def futures_funding_rate(self, **params):\n        return await self._request_futures_api(\"get\", \"fundingRate\", data=params)\n\n    futures_funding_rate.__doc__ = Client.futures_funding_rate.__doc__\n\n    async def futures_top_longshort_account_ratio(self, **params):\n        return await self._request_futures_data_api(\n            \"get\", \"topLongShortAccountRatio\", data=params\n        )\n\n    futures_top_longshort_account_ratio.__doc__ = Client.futures_top_longshort_account_ratio.__doc__\n\n    async def futures_top_longshort_position_ratio(self, **params):\n        return await self._request_futures_data_api(\n            \"get\", \"topLongShortPositionRatio\", data=params\n        )\n\n    futures_top_longshort_position_ratio.__doc__ = Client.futures_top_longshort_position_ratio.__doc__\n\n    async def futures_global_longshort_ratio(self, **params):\n        return await self._request_futures_data_api(\n            \"get\", \"globalLongShortAccountRatio\", data=params\n        )\n\n    futures_global_longshort_ratio.__doc__ = Client.futures_global_longshort_ratio.__doc__\n        \n    async def futures_taker_longshort_ratio(self, **params):\n        return await self._request_futures_data_api(\n            \"get\", \"takerlongshortRatio\", data=params\n        )\n\n    futures_taker_longshort_ratio.__doc__ = Client.futures_taker_longshort_ratio.__doc__\n\n    async def futures_ticker(self, **params):\n        return await self._request_futures_api(\"get\", \"ticker/24hr\", data=params)\n\n    futures_ticker.__doc__ = Client.futures_ticker.__doc__\n\n    async def futures_symbol_ticker(self, **params):\n        return await self._request_futures_api(\"get\", \"ticker/price\", version=2, data=params)\n    \n    futures_symbol_ticker.__doc__ = Client.futures_symbol_ticker.__doc__\n\n    futures_symbol_ticker.__doc__ = Client.futures_symbol_ticker.__doc__\n\n    futures_symbol_ticker.__doc__ = Client.futures_symbol_ticker.__doc__\n\n    async def futures_orderbook_ticker(self, **params):\n        return await self._request_futures_api(\"get\", \"ticker/bookTicker\", data=params)\n\n    futures_orderbook_ticker.__doc__ = Client.futures_orderbook_ticker.__doc__\n\n    async def futures_index_price_constituents(self, **params):\n        return await self._request_futures_api(\"get\", \"constituents\", data=params)\n\n    futures_index_price_constituents.__doc__ = (\n        Client.futures_index_price_constituents.__doc__\n    )\n\n    async def futures_liquidation_orders(self, **params):\n        return await self._request_futures_api(\n            \"get\", \"forceOrders\", signed=True, data=params\n        )\n\n    futures_liquidation_orders.__doc__ = Client.futures_liquidation_orders.__doc__\n\n    async def futures_api_trading_status(self, **params):\n        return await self._request_futures_api(\n            \"get\", \"apiTradingStatus\", signed=True, data=params\n        )\n\n    futures_api_trading_status.__doc__ = Client.futures_api_trading_status.__doc__\n\n    async def futures_commission_rate(self, **params):\n        return await self._request_futures_api(\n            \"get\", \"commissionRate\", signed=True, data=params\n        )\n\n    futures_commission_rate.__doc__ = Client.futures_commission_rate.__doc__\n\n    async def futures_adl_quantile_estimate(self, **params):\n        return await self._request_futures_api(\n            \"get\", \"adlQuantile\", signed=True, data=params\n        )\n\n    futures_adl_quantile_estimate.__doc__ = Client.futures_adl_quantile_estimate.__doc__\n\n    async def futures_open_interest(self, **params):\n        return await self._request_futures_api(\"get\", \"openInterest\", data=params)\n\n    futures_open_interest.__doc__ = Client.futures_open_interest.__doc__\n\n    async def futures_index_info(self, **params):\n        return await self._request_futures_api(\"get\", \"indexInfo\", data=params)\n\n    futures_index_info.__doc__ = Client.futures_index_info.__doc__\n\n    async def futures_open_interest_hist(self, **params):\n        return await self._request_futures_data_api(\n            \"get\", \"openInterestHist\", data=params\n        )\n\n    futures_open_interest_hist.__doc__ = Client.futures_open_interest_hist.__doc__\n\n    async def futures_leverage_bracket(self, **params):\n        return await self._request_futures_api(\n            \"get\", \"leverageBracket\", True, data=params\n        )\n\n    futures_leverage_bracket.__doc__ = Client.futures_leverage_bracket.__doc__\n\n    async def futures_account_transfer(self, **params):\n        return await self._request_margin_api(\n            \"post\", \"futures/transfer\", True, data=params\n        )\n\n    futures_account_transfer.__doc__ = Client.futures_account_transfer.__doc__\n\n    async def transfer_history(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"futures/transfer\", True, data=params\n        )\n\n    transfer_history.__doc__ = Client.transfer_history.__doc__\n\n    async def futures_loan_borrow_history(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"futures/loan/borrow/history\", True, data=params\n        )\n\n    futures_loan_borrow_history.__doc__ = Client.futures_loan_borrow_history.__doc__\n\n    async def futures_loan_repay_history(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"futures/loan/repay/history\", True, data=params\n        )\n\n    futures_loan_repay_history.__doc__ = Client.futures_loan_repay_history.__doc__\n\n    async def futures_loan_wallet(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"futures/loan/wallet\", True, data=params, version=2\n        )\n\n    futures_loan_wallet.__doc__ = Client.futures_loan_wallet.__doc__\n\n    async def futures_cross_collateral_adjust_history(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"futures/loan/adjustCollateral/history\", True, data=params\n        )\n\n    futures_cross_collateral_adjust_history.__doc__ = Client.futures_cross_collateral_adjust_history.__doc__\n\n    async def futures_cross_collateral_liquidation_history(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"futures/loan/liquidationHistory\", True, data=params\n        )\n\n    futures_cross_collateral_liquidation_history.__doc__ = Client.futures_cross_collateral_liquidation_history.__doc__\n\n    async def futures_loan_interest_history(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"futures/loan/interestHistory\", True, data=params\n        )\n\n    futures_loan_interest_history.__doc__ = Client.futures_loan_interest_history.__doc__\n\n    async def futures_create_order(self, **params):\n        # Check if this is a conditional order type that needs to use algo endpoint\n        order_type = params.get(\"type\", \"\").upper()\n        conditional_types = [\n            \"STOP\",\n            \"STOP_MARKET\",\n            \"TAKE_PROFIT\",\n            \"TAKE_PROFIT_MARKET\",\n            \"TRAILING_STOP_MARKET\",\n        ]\n\n        if order_type in conditional_types:\n            # Route to algo order endpoint\n            if \"clientAlgoId\" not in params:\n                params[\"clientAlgoId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n            # Remove newClientOrderId if it was added by default\n            params.pop(\"newClientOrderId\", None)\n            params[\"algoType\"] = \"CONDITIONAL\"\n            # Convert stopPrice to triggerPrice for algo orders (camelCase per API docs)\n            if \"stopPrice\" in params and \"triggerPrice\" not in params:\n                params[\"triggerPrice\"] = params.pop(\"stopPrice\")\n            return await self._request_futures_api(\"post\", \"algoOrder\", True, data=params)\n        else:\n            # Use regular order endpoint\n            if \"newClientOrderId\" not in params:\n                params[\"newClientOrderId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n            return await self._request_futures_api(\"post\", \"order\", True, data=params)\n\n    futures_create_order.__doc__ = Client.futures_create_order.__doc__\n\n    async def futures_limit_order(self, **params):\n        \"\"\"Send in a new futures limit order.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api\n\n        \"\"\"\n        if \"newClientOrderId\" not in params:\n            params[\"newClientOrderId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n        params[\"type\"] = \"LIMIT\"\n        return await self._request_futures_api(\"post\", \"order\", True, data=params)\n\n    async def futures_market_order(self, **params):\n        \"\"\"Send in a new futures market order.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api\n\n        \"\"\"\n        if \"newClientOrderId\" not in params:\n            params[\"newClientOrderId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n        params[\"type\"] = \"MARKET\"\n        return await self._request_futures_api(\"post\", \"order\", True, data=params)\n\n\n    async def futures_limit_buy_order(self, **params):\n        \"\"\"Send in a new futures limit buy order.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api\n\n        \"\"\"\n        if \"newClientOrderId\" not in params:\n            params[\"newClientOrderId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n        params[\"side\"] = \"BUY\"\n        params[\"type\"] = \"LIMIT\"\n        return await self._request_futures_api(\"post\", \"order\", True, data=params)\n\n    async def futures_limit_sell_order(self, **params):\n        \"\"\"Send in a new futures limit sell order.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api\n\n        \"\"\"\n        if \"newClientOrderId\" not in params:\n            params[\"newClientOrderId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n        params[\"side\"] = \"SELL\"\n        params[\"type\"] = \"LIMIT\"\n        return await self._request_futures_api(\"post\", \"order\", True, data=params)\n\n    async def futures_market_buy_order(self, **params):\n        \"\"\"Send in a new futures market buy order.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api\n\n        \"\"\"\n        if \"newClientOrderId\" not in params:\n            params[\"newClientOrderId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n        params[\"side\"] = \"BUY\"\n        params[\"type\"] = \"MARKET\"\n        return await self._request_futures_api(\"post\", \"order\", True, data=params)\n\n    async def futures_market_sell_order(self, **params):\n        \"\"\"Send in a new futures market sell order.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api\n\n        \"\"\"\n        if \"newClientOrderId\" not in params:\n            params[\"newClientOrderId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n        params[\"side\"] = \"SELL\"\n        params[\"type\"] = \"MARKET\"\n        return await self._request_futures_api(\"post\", \"order\", True, data=params)\n\n    async def futures_modify_order(self, **params):\n        \"\"\"Modify an existing order. Currently only LIMIT order modification is supported.\n\n        https://binance-docs.github.io/apidocs/futures/en/#modify-order-trade\n\n        \"\"\"\n        return await self._request_futures_api(\"put\", \"order\", True, data=params)\n\n    futures_modify_order.__doc__ = Client.futures_modify_order.__doc__\n\n    async def futures_create_test_order(self, **params):\n        return await self._request_futures_api(\"post\", \"order/test\", True, data=params)\n\n    futures_create_test_order.__doc__ = Client.futures_create_test_order.__doc__\n\n    async def futures_place_batch_order(self, **params):\n        for order in params[\"batchOrders\"]:\n            if \"newClientOrderId\" not in order:\n                order[\"newClientOrderId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n                order = self._order_params(order)\n        query_string = urlencode(params).replace(\"%40\", \"@\").replace(\"%27\", \"%22\")\n        params[\"batchOrders\"] = query_string[12:]\n\n        return await self._request_futures_api(\n            \"post\", \"batchOrders\", True, data=params, force_params=True\n        )\n\n    futures_place_batch_order.__doc__ = Client.futures_place_batch_order.__doc__\n\n    async def futures_get_order(self, **params):\n        # Check if this is a request for a conditional/algo order\n        is_conditional = params.pop(\"conditional\", False)\n        # Also check if algoId or clientAlgoId is provided\n        if \"algoId\" in params or \"clientAlgoId\" in params:\n            is_conditional = True\n\n        if is_conditional:\n            return await self._request_futures_api(\"get\", \"algoOrder\", True, data=params)\n        else:\n            return await self._request_futures_api(\"get\", \"order\", True, data=params)\n\n    futures_get_order.__doc__ = Client.futures_get_order.__doc__\n\n    async def futures_get_open_orders(self, **params):\n        is_conditional = params.pop(\"conditional\", False)\n\n        if is_conditional:\n            return await self._request_futures_api(\"get\", \"openAlgoOrders\", True, data=params)\n        else:\n            return await self._request_futures_api(\"get\", \"openOrders\", True, data=params)\n\n    futures_get_open_orders.__doc__ = Client.futures_get_open_orders.__doc__\n\n    async def futures_get_all_orders(self, **params):\n        is_conditional = params.pop(\"conditional\", False)\n\n        if is_conditional:\n            return await self._request_futures_api(\"get\", \"allAlgoOrders\", True, data=params)\n        else:\n            return await self._request_futures_api(\"get\", \"allOrders\", True, data=params)\n\n    futures_get_all_orders.__doc__ = Client.futures_get_all_orders.__doc__\n\n    async def futures_cancel_order(self, **params):\n        # Check if this is a request for a conditional/algo order\n        is_conditional = params.pop(\"conditional\", False)\n        # Also check if algoId or clientAlgoId is provided\n        if \"algoId\" in params or \"clientAlgoId\" in params:\n            is_conditional = True\n\n        if is_conditional:\n            return await self._request_futures_api(\"delete\", \"algoOrder\", True, data=params)\n        else:\n            return await self._request_futures_api(\"delete\", \"order\", True, data=params)\n\n    futures_cancel_order.__doc__ = Client.futures_cancel_order.__doc__\n\n    async def futures_cancel_all_open_orders(self, **params):\n        is_conditional = params.pop(\"conditional\", False)\n\n        if is_conditional:\n            return await self._request_futures_api(\n                \"delete\", \"algoOpenOrders\", True, data=params\n            )\n        else:\n            return await self._request_futures_api(\n                \"delete\", \"allOpenOrders\", True, data=params\n            )\n            \n    futures_cancel_all_open_orders.__doc__ = Client.futures_cancel_all_open_orders.__doc__\n\n    async def futures_cancel_orders(self, **params):\n        if params.get(\"orderidlist\"):\n            params[\"orderidlist\"] = quote(\n                convert_list_to_json_array(params[\"orderidlist\"])\n            )\n        if params.get(\"origclientorderidlist\"):\n            params[\"origclientorderidlist\"] = quote(\n                convert_list_to_json_array(params[\"origclientorderidlist\"])\n            )\n        return await self._request_futures_api(\n            \"delete\", \"batchOrders\", True, data=params, force_params=True\n        )\n\n    futures_cancel_orders.__doc__ = Client.futures_cancel_orders.__doc__\n\n    async def futures_countdown_cancel_all(self, **params):\n        return await self._request_futures_api(\n            \"post\", \"countdownCancelAll\", True, data=params\n        )\n\n    # Algo Orders (Conditional Orders)\n\n    futures_countdown_cancel_all.__doc__ = Client.futures_countdown_cancel_all.__doc__\n\n    async def futures_create_algo_order(self, **params):\n        if \"clientAlgoId\" not in params:\n            params[\"clientAlgoId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n        if \"algoType\" not in params:\n            params[\"algoType\"] = \"CONDITIONAL\"\n        return await self._request_futures_api(\"post\", \"algoOrder\", True, data=params)\n\n    futures_create_algo_order.__doc__ = Client.futures_create_algo_order.__doc__\n\n    async def futures_cancel_algo_order(self, **params):\n        return await self._request_futures_api(\"delete\", \"algoOrder\", True, data=params)\n\n    futures_cancel_algo_order.__doc__ = Client.futures_cancel_algo_order.__doc__\n\n    async def futures_cancel_all_algo_open_orders(self, **params):\n        return await self._request_futures_api(\n            \"delete\", \"algoOpenOrders\", True, data=params\n        )\n    \n    futures_cancel_all_algo_open_orders.__doc__ = Client.futures_cancel_all_algo_open_orders.__doc__\n\n    async def futures_get_algo_order(self, **params):\n        return await self._request_futures_api(\"get\", \"algoOrder\", True, data=params)\n\n    futures_get_algo_order.__doc__ = Client.futures_get_algo_order.__doc__\n\n    async def futures_get_open_algo_orders(self, **params):\n        return await self._request_futures_api(\"get\", \"openAlgoOrders\", True, data=params)\n    \n    futures_get_open_algo_orders.__doc__ = Client.futures_get_open_algo_orders.__doc__\n\n    async def futures_get_all_algo_orders(self, **params):\n        return await self._request_futures_api(\"get\", \"allAlgoOrders\", True, data=params)\n\n    futures_get_all_algo_orders.__doc__ = Client.futures_get_all_algo_orders.__doc__\n\n    async def futures_account_balance(self, **params):\n        return await self._request_futures_api(\n            \"get\", \"balance\", True, version=3, data=params\n        )\n\n    futures_account_balance.__doc__ = Client.futures_account_balance.__doc__\n\n    async def futures_account(self, **params):\n        return await self._request_futures_api(\n            \"get\", \"account\", True, version=2, data=params\n        )\n\n    futures_account.__doc__ = Client.futures_account.__doc__\n\n    async def futures_symbol_adl_risk(self, **params):\n        return await self._request_futures_api(\"get\", \"symbolAdlRisk\", True, data=params)\n\n    futures_symbol_adl_risk.__doc__ = Client.futures_symbol_adl_risk.__doc__\n\n    async def futures_change_leverage(self, **params):\n        return await self._request_futures_api(\"post\", \"leverage\", True, data=params)\n\n    futures_change_leverage.__doc__ = Client.futures_change_leverage.__doc__\n\n    async def futures_change_margin_type(self, **params):\n        return await self._request_futures_api(\"post\", \"marginType\", True, data=params)\n\n    futures_change_margin_type.__doc__ = Client.futures_change_margin_type.__doc__\n\n    async def futures_change_position_margin(self, **params):\n        return await self._request_futures_api(\n            \"post\", \"positionMargin\", True, data=params\n        )\n\n    futures_change_position_margin.__doc__ = Client.futures_change_position_margin.__doc__\n\n    async def futures_position_margin_history(self, **params):\n        return await self._request_futures_api(\n            \"get\", \"positionMargin/history\", True, data=params\n        )\n\n    futures_position_margin_history.__doc__ = Client.futures_position_margin_history.__doc__\n\n    async def futures_position_information(self, **params):\n        return await self._request_futures_api(\n            \"get\", \"positionRisk\", True, version=3, data=params\n        )\n\n    futures_position_information.__doc__ = Client.futures_position_information.__doc__\n\n    async def futures_account_trades(self, **params):\n        return await self._request_futures_api(\"get\", \"userTrades\", True, data=params)\n\n    futures_account_trades.__doc__ = Client.futures_account_trades.__doc__\n\n    async def futures_income_history(self, **params):\n        return await self._request_futures_api(\"get\", \"income\", True, data=params)\n\n    futures_income_history.__doc__ = Client.futures_income_history.__doc__\n\n    async def futures_change_position_mode(self, **params):\n        return await self._request_futures_api(\n            \"post\", \"positionSide/dual\", True, data=params\n        )\n\n    futures_change_position_mode.__doc__ = Client.futures_change_position_mode.__doc__\n\n    async def futures_get_position_mode(self, **params):\n        return await self._request_futures_api(\n            \"get\", \"positionSide/dual\", True, data=params\n        )\n\n    futures_get_position_mode.__doc__ = Client.futures_get_position_mode.__doc__\n\n    async def futures_change_multi_assets_mode(self, multiAssetsMargin: bool):\n        params = {\"multiAssetsMargin\": \"true\" if multiAssetsMargin else \"false\"}\n        return await self._request_futures_api(\n            \"post\", \"multiAssetsMargin\", True, data=params\n        )\n\n    futures_change_multi_assets_mode.__doc__ = Client.futures_change_multi_assets_mode.__doc__\n\n    async def futures_get_multi_assets_mode(self):\n        return await self._request_futures_api(\n            \"get\", \"multiAssetsMargin\", True, data={}\n        )\n\n    futures_get_multi_assets_mode.__doc__ = Client.futures_get_multi_assets_mode.__doc__\n\n    async def futures_stream_get_listen_key(self):\n        res = await self._request_futures_api(\n            \"post\", \"listenKey\", signed=False, data={}\n        )\n        return res[\"listenKey\"]\n\n    futures_stream_get_listen_key.__doc__ = Client.futures_stream_get_listen_key.__doc__\n\n    async def futures_stream_keepalive(self, listenKey):\n        params = {\"listenKey\": listenKey}\n        return await self._request_futures_api(\n            \"put\", \"listenKey\", signed=False, data=params\n        )\n\n    futures_stream_keepalive.__doc__ = Client.futures_stream_keepalive.__doc__\n\n    async def futures_stream_close(self, listenKey):\n        params = {\"listenKey\": listenKey}\n        return await self._request_futures_api(\n            \"delete\", \"listenKey\", signed=False, data=params\n        )\n\n    # new methods\n\n    futures_stream_close.__doc__ = Client.futures_stream_close.__doc__\n    async def futures_account_config(self, **params):\n        return await self._request_futures_api(\n            \"get\", \"accountConfig\", signed=True, version=1, data=params\n        )\n\n    futures_account_config.__doc__ = Client.futures_account_config.__doc__\n\n    async def futures_symbol_config(self, **params):\n        return await self._request_futures_api(\n            \"get\", \"symbolConfig\", signed=True, version=1, data=params\n        )\n\n    # COIN Futures API\n\n    futures_symbol_config.__doc__ = Client.futures_symbol_config.__doc__\n\n    async def futures_coin_ping(self):\n        return await self._request_futures_coin_api(\"get\", \"ping\")\n\n    futures_coin_ping.__doc__ = Client.futures_coin_ping.__doc__\n\n    async def futures_coin_time(self):\n        return await self._request_futures_coin_api(\"get\", \"time\")\n\n    futures_coin_time.__doc__ = Client.futures_coin_time.__doc__\n\n    async def futures_coin_exchange_info(self):\n        return await self._request_futures_coin_api(\"get\", \"exchangeInfo\")\n\n    futures_coin_exchange_info.__doc__ = Client.futures_coin_exchange_info.__doc__\n\n    async def futures_coin_order_book(self, **params):\n        return await self._request_futures_coin_api(\"get\", \"depth\", data=params)\n\n    futures_coin_order_book.__doc__ = Client.futures_coin_order_book.__doc__\n\n    async def futures_coin_recent_trades(self, **params):\n        return await self._request_futures_coin_api(\"get\", \"trades\", data=params)\n\n    futures_coin_recent_trades.__doc__ = Client.futures_coin_recent_trades.__doc__\n\n    async def futures_coin_historical_trades(self, **params):\n        return await self._request_futures_coin_api(\n            \"get\", \"historicalTrades\", data=params\n        )\n\n    futures_coin_historical_trades.__doc__ = Client.futures_coin_historical_trades.__doc__\n\n    async def futures_coin_aggregate_trades(self, **params):\n        return await self._request_futures_coin_api(\"get\", \"aggTrades\", data=params)\n\n    futures_coin_aggregate_trades.__doc__ = Client.futures_coin_aggregate_trades.__doc__\n\n    async def futures_coin_klines(self, **params):\n        return await self._request_futures_coin_api(\"get\", \"klines\", data=params)\n\n    futures_coin_klines.__doc__ = Client.futures_coin_klines.__doc__\n\n    async def futures_coin_continous_klines(self, **params):\n        return await self._request_futures_coin_api(\n            \"get\", \"continuousKlines\", data=params\n        )\n\n    futures_coin_continous_klines.__doc__ = Client.futures_coin_continous_klines.__doc__\n\n    async def futures_coin_index_price_klines(self, **params):\n        return await self._request_futures_coin_api(\n            \"get\", \"indexPriceKlines\", data=params\n        )\n\n    futures_coin_index_price_klines.__doc__ = Client.futures_coin_index_price_klines.__doc__\n\n    async def futures_coin_mark_price_klines(self, **params):\n        return await self._request_futures_coin_api(\n            \"get\", \"markPriceKlines\", data=params\n        )\n\n    futures_coin_mark_price_klines.__doc__ = Client.futures_mark_price_klines.__doc__\n\n    async def futures_coin_premium_index_klines(self, **params):\n        return await self._request_futures_coin_api(\n            \"get\", \"premiumIndexKlines\", data=params\n        )\n\n    futures_coin_premium_index_klines.__doc__ = (\n        Client.futures_premium_index_klines.__doc__\n    )\n\n    async def futures_coin_mark_price(self, **params):\n        return await self._request_futures_coin_api(\"get\", \"premiumIndex\", data=params)\n\n    futures_coin_mark_price.__doc__ = Client.futures_coin_mark_price.__doc__\n\n    async def futures_coin_funding_rate(self, **params):\n        return await self._request_futures_coin_api(\"get\", \"fundingRate\", data=params)\n\n    futures_coin_funding_rate.__doc__ = Client.futures_coin_funding_rate.__doc__\n\n    async def futures_coin_ticker(self, **params):\n        return await self._request_futures_coin_api(\"get\", \"ticker/24hr\", data=params)\n\n    futures_coin_ticker.__doc__ = Client.futures_coin_ticker.__doc__\n\n    async def futures_coin_symbol_ticker(self, **params):\n        return await self._request_futures_coin_api(\"get\", \"ticker/price\", data=params)\n\n    futures_coin_symbol_ticker.__doc__ = Client.futures_coin_symbol_ticker.__doc__\n\n    async def futures_coin_orderbook_ticker(self, **params):\n        return await self._request_futures_coin_api(\n            \"get\", \"ticker/bookTicker\", data=params\n        )\n\n    futures_coin_orderbook_ticker.__doc__ = Client.futures_coin_orderbook_ticker.__doc__\n\n    async def futures_coin_index_price_constituents(self, **params):\n        return await self._request_futures_coin_api(\"get\", \"constituents\", data=params)\n\n    futures_coin_index_price_constituents.__doc__ = (\n        Client.futures_coin_index_price_constituents.__doc__\n    )\n\n    async def futures_coin_liquidation_orders(self, **params):\n        return await self._request_futures_coin_api(\n            \"get\", \"forceOrders\", signed=True, data=params\n        )\n\n    futures_coin_liquidation_orders.__doc__ = Client.futures_coin_liquidation_orders.__doc__\n\n    async def futures_coin_open_interest(self, **params):\n        return await self._request_futures_coin_api(\"get\", \"openInterest\", data=params)\n\n    futures_coin_open_interest.__doc__ = Client.futures_coin_open_interest.__doc__\n\n    async def futures_coin_open_interest_hist(self, **params):\n        return await self._request_futures_coin_data_api(\n            \"get\", \"openInterestHist\", data=params\n        )\n\n    futures_coin_open_interest_hist.__doc__ = Client.futures_coin_open_interest_hist.__doc__\n\n    async def futures_coin_leverage_bracket(self, **params):\n        return await self._request_futures_coin_api(\n            \"get\", \"leverageBracket\", version=2, signed=True, data=params\n        )\n\n    futures_coin_leverage_bracket.__doc__ = Client.futures_coin_leverage_bracket.__doc__\n\n    async def new_transfer_history(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"asset/transfer\", True, data=params\n        )\n\n    new_transfer_history.__doc__ = Client.new_transfer_history.__doc__\n\n    async def funding_wallet(self, **params):\n        return await self._request_margin_api(\n            \"post\", \"asset/get-funding-asset\", True, data=params\n        )\n\n    funding_wallet.__doc__ = Client.funding_wallet.__doc__\n\n    async def get_user_asset(self, **params):\n        return await self._request_margin_api(\n            \"post\", \"asset/getUserAsset\", True, data=params, version=3\n        )\n\n    get_user_asset.__doc__ = Client.get_user_asset.__doc__\n\n    async def universal_transfer(self, **params):\n        return await self._request_margin_api(\n            \"post\", \"asset/transfer\", signed=True, data=params\n        )\n\n    universal_transfer.__doc__ = Client.universal_transfer.__doc__\n\n    async def futures_coin_create_order(self, **params):\n        if \"newClientOrderId\" not in params:\n            params[\"newClientOrderId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n        return await self._request_futures_coin_api(\"post\", \"order\", True, data=params)\n\n    futures_coin_create_order.__doc__ = Client.futures_coin_create_order.__doc__\n\n    async def futures_coin_place_batch_order(self, **params):\n        for order in params[\"batchOrders\"]:\n            if \"newClientOrderId\" not in order:\n                order[\"newClientOrderId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n        query_string = urlencode(params)\n        query_string = query_string.replace(\"%27\", \"%22\")\n        params[\"batchOrders\"] = query_string[12:]\n\n        return await self._request_futures_coin_api(\n            \"post\", \"batchOrders\", True, data=params\n        )\n\n    futures_coin_place_batch_order.__doc__ = Client.futures_coin_place_batch_order.__doc__\n\n    async def futures_coin_get_order(self, **params):\n        return await self._request_futures_coin_api(\"get\", \"order\", True, data=params)\n\n    futures_coin_get_order.__doc__ = Client.futures_coin_get_order.__doc__\n\n    async def futures_coin_get_open_orders(self, **params):\n        return await self._request_futures_coin_api(\n            \"get\", \"openOrders\", True, data=params\n        )\n\n    futures_coin_get_open_orders.__doc__ = Client.futures_coin_get_open_orders.__doc__\n\n    async def futures_coin_get_all_orders(self, **params):\n        return await self._request_futures_coin_api(\n            \"get\", \"allOrders\", signed=True, data=params\n        )\n\n    futures_coin_get_all_orders.__doc__ = Client.futures_coin_get_all_orders.__doc__\n\n    async def futures_coin_cancel_order(self, **params):\n        return await self._request_futures_coin_api(\n            \"delete\", \"order\", signed=True, data=params\n        )\n\n    futures_coin_cancel_order.__doc__ = Client.futures_coin_cancel_order.__doc__\n\n    async def futures_coin_cancel_all_open_orders(self, **params):\n        return await self._request_futures_coin_api(\n            \"delete\", \"allOpenOrders\", signed=True, data=params, force_params=True\n        )\n\n    futures_coin_cancel_all_open_orders.__doc__ = Client.futures_coin_cancel_all_open_orders.__doc__\n\n    async def futures_coin_cancel_orders(self, **params):\n        if params.get(\"orderidlist\"):\n            params[\"orderidlist\"] = quote(\n                convert_list_to_json_array(params[\"orderidlist\"])\n            )\n        if params.get(\"origclientorderidlist\"):\n            params[\"origclientorderidlist\"] = quote(\n                convert_list_to_json_array(params[\"origclientorderidlist\"])\n            )\n        return await self._request_futures_coin_api(\n            \"delete\", \"batchOrders\", True, data=params\n        )\n\n    futures_coin_cancel_orders.__doc__ = Client.futures_coin_cancel_orders.__doc__\n\n    async def futures_coin_account_balance(self, **params):\n        return await self._request_futures_coin_api(\n            \"get\", \"balance\", signed=True, data=params\n        )\n\n    futures_coin_account_balance.__doc__ = Client.futures_coin_account_balance.__doc__\n\n    async def futures_coin_account(self, **params):\n        return await self._request_futures_coin_api(\n            \"get\", \"account\", signed=True, data=params\n        )\n\n    futures_coin_account.__doc__ = Client.futures_coin_account.__doc__\n\n    async def futures_coin_change_leverage(self, **params):\n        return await self._request_futures_coin_api(\n            \"post\", \"leverage\", signed=True, data=params\n        )\n\n    futures_coin_change_leverage.__doc__ = Client.futures_coin_change_leverage.__doc__\n\n    async def futures_coin_change_margin_type(self, **params):\n        return await self._request_futures_coin_api(\n            \"post\", \"marginType\", signed=True, data=params\n        )\n\n    futures_coin_change_margin_type.__doc__ = Client.futures_coin_change_margin_type.__doc__\n\n    async def futures_coin_change_position_margin(self, **params):\n        return await self._request_futures_coin_api(\n            \"post\", \"positionMargin\", True, data=params\n        )\n\n    futures_coin_change_position_margin.__doc__ = Client.futures_coin_change_position_margin.__doc__\n\n    async def futures_coin_position_margin_history(self, **params):\n        return await self._request_futures_coin_api(\n            \"get\", \"positionMargin/history\", True, data=params\n        )\n\n    futures_coin_position_margin_history.__doc__ = Client.futures_coin_position_margin_history.__doc__\n\n    async def futures_coin_position_information(self, **params):\n        return await self._request_futures_coin_api(\n            \"get\", \"positionRisk\", True, data=params\n        )\n\n    futures_coin_position_information.__doc__ = Client.futures_coin_position_information.__doc__\n\n    async def futures_coin_account_trades(self, **params):\n        return await self._request_futures_coin_api(\n            \"get\", \"userTrades\", True, data=params\n        )\n\n    futures_coin_account_trades.__doc__ = Client.futures_coin_account_trades.__doc__\n\n    async def futures_coin_income_history(self, **params):\n        return await self._request_futures_coin_api(\"get\", \"income\", True, data=params)\n\n    futures_coin_income_history.__doc__ = Client.futures_coin_income_history.__doc__\n\n    async def futures_coin_change_position_mode(self, **params):\n        return await self._request_futures_coin_api(\n            \"post\", \"positionSide/dual\", True, data=params\n        )\n\n    futures_coin_change_position_mode.__doc__ = Client.futures_coin_change_position_mode.__doc__\n\n    async def futures_coin_get_position_mode(self, **params):\n        return await self._request_futures_coin_api(\n            \"get\", \"positionSide/dual\", True, data=params\n        )\n\n    futures_coin_get_position_mode.__doc__ = Client.futures_coin_get_position_mode.__doc__\n\n    async def futures_coin_stream_get_listen_key(self):\n        res = await self._request_futures_coin_api(\n            \"post\", \"listenKey\", signed=False, data={}\n        )\n        return res[\"listenKey\"]\n\n    futures_coin_stream_get_listen_key.__doc__ = Client.futures_coin_stream_get_listen_key.__doc__\n\n    async def futures_coin_stream_keepalive(self, listenKey):\n        params = {\"listenKey\": listenKey}\n        return await self._request_futures_coin_api(\n            \"put\", \"listenKey\", signed=False, data=params\n        )\n\n    futures_coin_stream_keepalive.__doc__ = Client.futures_coin_stream_keepalive.__doc__\n\n    async def futures_coin_account_order_history_download(self, **params):\n        return await self._request_futures_coin_api(\n            \"get\", \"order/asyn\", True, data=params\n        )\n\n    futures_coin_account_order_history_download.__doc__ = (\n        Client.futures_coin_account_order_history_download.__doc__\n    )\n\n    async def futures_coin_account_order_history_download_link(self, **params):\n        return await self._request_futures_coin_api(\n            \"get\", \"order/asyn/id\", True, data=params\n        )\n\n    futures_coin_account_order_history_download_link.__doc__ = (\n        Client.futures_coin_accout_order_history_download_link.__doc__\n    )\n\n    async def futures_coin_account_trade_history_download(self, **params):\n        return await self._request_futures_coin_api(\n            \"get\", \"trade/asyn\", True, data=params\n        )\n\n    futures_coin_account_trade_history_download.__doc__ = (\n        Client.futures_coin_account_trade_history_download.__doc__\n    )\n\n    async def futures_coin_account_trade_history_download_link(self, **params):\n        return await self._request_futures_coin_api(\n            \"get\", \"trade/asyn/id\", True, data=params\n        )\n\n    futures_coin_account_trade_history_download_link.__doc__ = (\n        Client.futures_coin_account_trade_history_download_link.__doc__\n    )\n\n    async def futures_coin_stream_close(self, listenKey):\n        params = {\"listenKey\": listenKey}\n        return await self._request_futures_coin_api(\n            \"delete\", \"listenKey\", signed=False, data=params\n        )\n\n    futures_coin_stream_close.__doc__ = Client.futures_coin_stream_close.__doc__\n\n    async def get_all_coins_info(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"capital/config/getall\", True, data=params\n        )\n\n    get_all_coins_info.__doc__ = Client.get_all_coins_info.__doc__\n\n    async def get_account_snapshot(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"accountSnapshot\", True, data=params\n        )\n\n    get_account_snapshot.__doc__ = Client.get_account_snapshot.__doc__\n\n    async def disable_fast_withdraw_switch(self, **params):\n        return await self._request_margin_api(\n            \"post\", \"disableFastWithdrawSwitch\", True, data=params\n        )\n\n    disable_fast_withdraw_switch.__doc__ = Client.disable_fast_withdraw_switch.__doc__\n\n    async def enable_fast_withdraw_switch(self, **params):\n        return await self._request_margin_api(\n            \"post\", \"enableFastWithdrawSwitch\", True, data=params\n        )\n\n    \"\"\"\n    ====================================================================================================================\n    Options API\n    ====================================================================================================================\n    \"\"\"\n\n    # Quoting interface endpoints\n\n    enable_fast_withdraw_switch.__doc__ = Client.enable_fast_withdraw_switch.__doc__\n\n    async def options_ping(self):\n        return await self._request_options_api(\"get\", \"ping\")\n\n    options_ping.__doc__ = Client.options_ping.__doc__\n\n    async def options_time(self):\n        return await self._request_options_api(\"get\", \"time\")\n\n    options_time.__doc__ = Client.options_time.__doc__\n\n    async def options_info(self):\n        return await self._request_options_api(\"get\", \"optionInfo\")\n\n    options_info.__doc__ = Client.options_info.__doc__\n\n    async def options_exchange_info(self):\n        return await self._request_options_api(\"get\", \"exchangeInfo\")\n\n    options_exchange_info.__doc__ = Client.options_exchange_info.__doc__\n\n    async def options_index_price(self, **params):\n        return await self._request_options_api(\"get\", \"index\", data=params)\n\n    options_index_price.__doc__ = Client.options_index_price.__doc__\n\n    async def options_price(self, **params):\n        return await self._request_options_api(\"get\", \"ticker\", data=params)\n\n    options_price.__doc__ = Client.options_price.__doc__\n\n    async def options_mark_price(self, **params):\n        return await self._request_options_api(\"get\", \"mark\", data=params)\n\n    options_mark_price.__doc__ = Client.options_mark_price.__doc__\n\n    async def options_order_book(self, **params):\n        return await self._request_options_api(\"get\", \"depth\", data=params)\n\n    options_order_book.__doc__ = Client.options_order_book.__doc__\n\n    async def options_klines(self, **params):\n        return await self._request_options_api(\"get\", \"klines\", data=params)\n\n    options_klines.__doc__ = Client.options_klines.__doc__\n\n    async def options_recent_trades(self, **params):\n        return await self._request_options_api(\"get\", \"trades\", data=params)\n\n    options_recent_trades.__doc__ = Client.options_recent_trades.__doc__\n\n    async def options_historical_trades(self, **params):\n        return await self._request_options_api(\"get\", \"historicalTrades\", data=params)\n\n    # Account and trading interface endpoints\n\n    options_historical_trades.__doc__ = Client.options_historical_trades.__doc__\n\n    async def options_account_info(self, **params):\n        return await self._request_options_api(\n            \"get\", \"account\", signed=True, data=params\n        )\n\n    options_account_info.__doc__ = Client.options_account_info.__doc__\n\n    async def options_funds_transfer(self, **params):\n        return await self._request_options_api(\n            \"post\", \"transfer\", signed=True, data=params\n        )\n\n    options_funds_transfer.__doc__ = Client.options_funds_transfer.__doc__\n\n    async def options_positions(self, **params):\n        return await self._request_options_api(\n            \"get\", \"position\", signed=True, data=params\n        )\n\n    options_positions.__doc__ = Client.options_positions.__doc__\n\n    async def options_bill(self, **params):\n        return await self._request_options_api(\"post\", \"bill\", signed=True, data=params)\n\n    options_bill.__doc__ = Client.options_bill.__doc__\n\n    async def options_place_order(self, **params):\n        if \"clientOrderId\" not in params:\n            params[\"clientOrderId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n        return await self._request_options_api(\n            \"post\", \"order\", signed=True, data=params\n        )\n\n    options_place_order.__doc__ = Client.options_place_order.__doc__\n\n    async def options_place_batch_order(self, **params):\n        for order in params[\"batchOrders\"]:\n            if \"newClientOrderId\" not in order:\n                order[\"newClientOrderId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n        return await self._request_options_api(\n            \"post\", \"batchOrders\", signed=True, data=params\n        )\n\n    options_place_batch_order.__doc__ = Client.options_place_batch_order.__doc__\n\n    async def options_cancel_order(self, **params):\n        return await self._request_options_api(\n            \"delete\", \"order\", signed=True, data=params\n        )\n\n    options_cancel_order.__doc__ = Client.options_cancel_order.__doc__\n\n    async def options_cancel_batch_order(self, **params):\n        return await self._request_options_api(\n            \"delete\", \"batchOrders\", signed=True, data=params\n        )\n\n    options_cancel_batch_order.__doc__ = Client.options_cancel_batch_order.__doc__\n\n    async def options_cancel_all_orders(self, **params):\n        return await self._request_options_api(\n            \"delete\", \"allOpenOrders\", signed=True, data=params\n        )\n\n    options_cancel_all_orders.__doc__ = Client.options_cancel_all_orders.__doc__\n\n    async def options_query_order(self, **params):\n        return await self._request_options_api(\"get\", \"order\", signed=True, data=params)\n\n    options_query_order.__doc__ = Client.options_query_order.__doc__\n\n    async def options_query_pending_orders(self, **params):\n        return await self._request_options_api(\n            \"get\", \"openOrders\", signed=True, data=params\n        )\n\n    options_query_pending_orders.__doc__ = Client.options_query_pending_orders.__doc__\n\n    async def options_query_order_history(self, **params):\n        return await self._request_options_api(\n            \"get\", \"historyOrders\", signed=True, data=params\n        )\n\n    options_query_order_history.__doc__ = Client.options_query_order_history.__doc__\n\n    async def options_user_trades(self, **params):\n        return await self._request_options_api(\n            \"get\", \"userTrades\", signed=True, data=params\n        )\n\n    # Fiat Endpoints\n\n    options_user_trades.__doc__ = Client.options_user_trades.__doc__\n\n    async def get_fiat_deposit_withdraw_history(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"fiat/orders\", signed=True, data=params\n        )\n\n    get_fiat_deposit_withdraw_history.__doc__ = Client.get_fiat_deposit_withdraw_history.__doc__\n\n    async def get_fiat_payments_history(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"fiat/payments\", signed=True, data=params\n        )\n\n    # C2C Endpoints\n\n    get_fiat_payments_history.__doc__ = Client.get_fiat_payments_history.__doc__\n\n    async def get_c2c_trade_history(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"c2c/orderMatch/listUserOrderHistory\", signed=True, data=params\n        )\n\n    # Pay Endpoints\n\n    get_c2c_trade_history.__doc__ = Client.get_c2c_trade_history.__doc__\n\n    async def get_pay_trade_history(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"pay/transactions\", signed=True, data=params\n        )\n\n    get_pay_trade_history.__doc__ = Client.get_pay_trade_history.__doc__\n\n    # Convert Endpoints\n\n    async def get_convert_trade_history(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"convert/tradeFlow\", signed=True, data=params\n        )\n\n    get_convert_trade_history.__doc__ = Client.get_convert_trade_history.__doc__\n\n    async def convert_request_quote(self, **params):\n        return await self._request_margin_api(\n            \"post\", \"convert/getQuote\", signed=True, data=params\n        )\n\n    convert_request_quote.__doc__ = Client.convert_request_quote.__doc__\n\n    async def convert_accept_quote(self, **params):\n        return await self._request_margin_api(\n            \"post\", \"convert/acceptQuote\", signed=True, data=params\n        )\n\n    convert_accept_quote.__doc__ = Client.convert_accept_quote.__doc__\n\n    \"\"\"\n    ====================================================================================================================\n    PortfolioMargin API\n    ====================================================================================================================\n    \"\"\"\n\n    async def papi_stream_get_listen_key(self):\n        res = await self._request_papi_api(\"post\", \"listenKey\", signed=False, data={})\n        return res[\"listenKey\"]\n\n    papi_stream_get_listen_key.__doc__ = Client.papi_stream_get_listen_key.__doc__\n\n    async def papi_stream_keepalive(self, listenKey):\n        params = {\"listenKey\": listenKey}\n        return await self._request_papi_api(\n            \"put\", \"listenKey\", signed=False, data=params\n        )\n\n    papi_stream_keepalive.__doc__ = Client.papi_stream_keepalive.__doc__\n\n    async def papi_stream_close(self, listenKey):\n        params = {\"listenKey\": listenKey}\n        return await self._request_papi_api(\n            \"delete\", \"listenKey\", signed=False, data=params\n        )\n\n    papi_stream_close.__doc__ = Client.papi_stream_close.__doc__\n\n    async def papi_get_balance(self, **params):\n        return await self._request_papi_api(\"get\", \"balance\", signed=True, data=params)\n    papi_get_balance.__doc__ = Client.papi_get_balance.__doc__\n\n    async def papi_get_rate_limit(self, **params):\n        return await self._request_papi_api(\"get\", \"rateLimit/order\", signed=True, data=params)\n    papi_get_rate_limit.__doc__ = Client.papi_get_rate_limit.__doc__\n\n    async def papi_get_account(self, **params):\n        return await self._request_papi_api(\"get\", \"account\", signed=True, data=params)\n\n    papi_get_account.__doc__ = Client.papi_get_account.__doc__\n\n    async def papi_get_margin_max_borrowable(self, **params):\n        return await self._request_papi_api(\n            \"get\", \"margin/maxBorrowable\", signed=True, data=params\n        )\n\n    papi_get_margin_max_borrowable.__doc__ = Client.papi_get_margin_max_borrowable.__doc__\n\n    async def papi_get_margin_max_withdraw(self, **params):\n        return await self._request_papi_api(\n            \"get\", \"margin/maxWithdraw\", signed=True, data=params\n        )\n\n    papi_get_margin_max_withdraw.__doc__ = Client.papi_get_margin_max_withdraw.__doc__\n\n    async def papi_get_um_position_risk(self, **params):\n        return await self._request_papi_api(\n            \"get\", \"um/positionRisk\", signed=True, data=params\n        )\n\n    papi_get_um_position_risk.__doc__ = Client.papi_get_um_position_risk.__doc__\n\n    async def papi_get_cm_position_risk(self, **params):\n        return await self._request_papi_api(\n            \"get\", \"cm/positionRisk\", signed=True, data=params\n        )\n\n    papi_get_cm_position_risk.__doc__ = Client.papi_get_cm_position_risk.__doc__\n\n    async def papi_set_um_leverage(self, **params):\n        return await self._request_papi_api(\n            \"post\", \"um/leverage\", signed=True, data=params\n        )\n\n    papi_set_um_leverage.__doc__ = Client.papi_set_um_leverage.__doc__\n\n    async def papi_set_cm_leverage(self, **params):\n        return await self._request_papi_api(\n            \"post\", \"cm/leverage\", signed=True, data=params\n        )\n\n    papi_set_cm_leverage.__doc__ = Client.papi_set_cm_leverage.__doc__\n\n    async def papi_change_um_position_side_dual(self, **params):\n        return await self._request_papi_api(\n            \"post\", \"um/positionSide/dual\", signed=True, data=params\n        )\n\n    papi_change_um_position_side_dual.__doc__ = Client.papi_change_um_position_side_dual.__doc__\n\n    async def papi_get_um_position_side_dual(self, **params):\n        return await self._request_papi_api(\n            \"get\", \"um/positionSide/dual\", signed=True, data=params\n        )\n\n    papi_get_um_position_side_dual.__doc__ = Client.papi_get_um_position_side_dual.__doc__\n\n    async def papi_get_cm_position_side_dual(self, **params):\n        return await self._request_papi_api(\n            \"get\", \"cm/positionSide/dual\", signed=True, data=params\n        )\n\n    papi_get_cm_position_side_dual.__doc__ = Client.papi_get_cm_position_side_dual.__doc__\n\n    async def papi_get_um_leverage_bracket(self, **params):\n        return await self._request_papi_api(\n            \"get\", \"um/leverageBracket\", signed=True, data=params\n        )\n\n    papi_get_um_leverage_bracket.__doc__ = Client.papi_get_um_leverage_bracket.__doc__\n\n    async def papi_get_cm_leverage_bracket(self, **params):\n        return await self._request_papi_api(\n            \"get\", \"cm/leverageBracket\", signed=True, data=params\n        )\n\n    papi_get_cm_leverage_bracket.__doc__ = Client.papi_get_cm_leverage_bracket.__doc__\n\n    async def papi_get_um_api_trading_status(self, **params):\n        return await self._request_papi_api(\n            \"get\", \"um/apiTradingStatus\", signed=True, data=params\n        )\n\n    papi_get_um_api_trading_status.__doc__ = Client.papi_get_um_api_trading_status.__doc__\n\n    async def papi_get_um_comission_rate(self, **params):\n        return await self._request_papi_api(\n            \"get\", \"um/commissionRate\", signed=True, data=params\n        )\n\n    papi_get_um_comission_rate.__doc__ = Client.papi_get_um_comission_rate.__doc__\n\n    async def papi_get_cm_comission_rate(self, **params):\n        return await self._request_papi_api(\n            \"get\", \"cm/commissionRate\", signed=True, data=params\n        )\n\n    papi_get_cm_comission_rate.__doc__ = Client.papi_get_cm_comission_rate.__doc__\n\n    async def papi_get_margin_margin_loan(self, **params):\n        return await self._request_papi_api(\n            \"get\", \"margin/marginLoan\", signed=True, data=params\n        )\n\n    papi_get_margin_margin_loan.__doc__ = Client.papi_get_margin_margin_loan.__doc__\n\n    async def papi_get_margin_repay_loan(self, **params):\n        return await self._request_papi_api(\n            \"get\", \"margin/repayLoan\", signed=True, data=params\n        )\n\n    papi_get_margin_repay_loan.__doc__ = Client.papi_get_margin_repay_loan.__doc__\n\n    async def papi_get_repay_futures_switch(self, **params):\n        return await self._request_papi_api(\n            \"get\", \"repay-futures-switch\", signed=True, data=params\n        )\n\n    papi_get_repay_futures_switch.__doc__ = Client.papi_get_repay_futures_switch.__doc__\n\n    async def papi_repay_futures_switch(self, **params):\n        return await self._request_papi_api(\n            \"post\", \"repay-futures-switch\", signed=True, data=params\n        )\n\n    papi_repay_futures_switch.__doc__ = Client.papi_repay_futures_switch.__doc__\n\n    async def papi_get_margin_interest_history(self, **params):\n        return await self._request_papi_api(\n            \"get\", \"margin/marginInterestHistory\", signed=True, data=params\n        )\n\n    papi_get_margin_interest_history.__doc__ = Client.papi_get_margin_interest_history.__doc__\n\n    async def papi_repay_futures_negative_balance(self, **params):\n        return await self._request_papi_api(\n            \"post\", \"repay-futures-negative-balance\", signed=True, data=params\n        )\n\n    papi_repay_futures_negative_balance.__doc__ = Client.papi_repay_futures_negative_balance.__doc__\n\n    async def papi_get_portfolio_interest_history(self, **params):\n        return await self._request_papi_api(\n            \"get\", \"portfolio/interest-history\", signed=True, data=params\n        )\n\n    papi_get_portfolio_interest_history.__doc__ = Client.papi_get_portfolio_interest_history.__doc__\n\n\n    async def papi_get_portfolio_negative_balance_exchange_record(self, **params):\n        return await self._request_papi_api(\n            \"get\", \"portfolio/negative-balance-exchange-record\", signed=True, data=params\n        )\n    papi_get_portfolio_negative_balance_exchange_record.__doc__ = Client.papi_get_portfolio_negative_balance_exchange_record.__doc__\n\n    async def papi_fund_auto_collection(self, **params):\n        return await self._request_papi_api(\n            \"post\", \"auto-collection\", signed=True, data=params\n        )\n\n    papi_fund_auto_collection.__doc__ = Client.papi_fund_auto_collection.__doc__\n\n    async def papi_fund_asset_collection(self, **params):\n        return await self._request_papi_api(\n            \"post\", \"asset-collection\", signed=True, data=params\n        )\n\n    papi_fund_asset_collection.__doc__ = Client.papi_fund_asset_collection.__doc__\n\n    async def papi_bnb_transfer(self, **params):\n        return await self._request_papi_api(\n            \"post\", \"bnb-transfer\", signed=True, data=params\n        )\n\n    papi_bnb_transfer.__doc__ = Client.papi_bnb_transfer.__doc__\n\n    async def papi_get_um_income_history(self, **params):\n        return await self._request_papi_api(\n            \"get\", \"um/income\", signed=True, data=params\n        )\n\n    papi_get_um_income_history.__doc__ = Client.papi_get_um_income_history.__doc__\n\n    async def papi_get_cm_income_history(self, **params):\n        return await self._request_papi_api(\n            \"get\", \"cm/income\", signed=True, data=params\n        )\n\n    papi_get_cm_income_history.__doc__ = Client.papi_get_cm_income_history.__doc__\n\n    async def papi_get_um_account(self, **params):\n        return await self._request_papi_api(\n            \"get\", \"um/account\", signed=True, data=params\n        )\n\n    papi_get_um_account.__doc__ = Client.papi_get_um_account.__doc__\n\n    async def papi_get_um_account_v2(self, **params):\n        return await self._request_papi_api(\n            \"get\", \"um/account\", version=2, signed=True, data=params\n        )\n\n    papi_get_um_account_v2.__doc__ = Client.papi_get_um_account_v2.__doc__\n\n    async def papi_get_cm_account(self, **params):\n        return await self._request_papi_api(\n            \"get\", \"cm/account\", signed=True, data=params\n        )\n\n    papi_get_cm_account.__doc__ = Client.papi_get_cm_account.__doc__\n\n    async def papi_get_um_account_config(self, **params):\n        return await self._request_papi_api(\n            \"get\", \"um/accountConfig\", signed=True, data=params\n        )\n\n    papi_get_um_account_config.__doc__ = Client.papi_get_um_account_config.__doc__\n\n    async def papi_get_um_symbol_config(self, **params):\n        return await self._request_papi_api(\n            \"get\", \"um/symbolConfig\", signed=True, data=params\n        )\n\n    papi_get_um_symbol_config.__doc__ = Client.papi_get_um_symbol_config.__doc__\n\n    async def papi_get_um_trade_asyn(self, **params):\n        return await self._request_papi_api(\n            \"get\", \"um/trade/asyn\", signed=True, data=params\n        )\n\n    papi_get_um_trade_asyn.__doc__ = Client.papi_get_um_trade_asyn.__doc__\n\n    async def papi_get_um_trade_asyn_id(self, **params):\n        return await self._request_papi_api(\n            \"get\", \"um/trade/asyn/id\", signed=True, data=params\n        )\n\n    papi_get_um_trade_asyn_id.__doc__ = Client.papi_get_um_trade_asyn_id.__doc__\n\n    async def papi_get_um_order_asyn(self, **params):\n        return await self._request_papi_api(\n            \"get\", \"um/order/asyn\", signed=True, data=params\n        )\n\n    papi_get_um_order_asyn.__doc__ = Client.papi_get_um_order_asyn.__doc__\n\n    async def papi_get_um_order_asyn_id(self, **params):\n        return await self._request_papi_api(\n            \"get\", \"um/order/asyn/id\", signed=True, data=params\n        )\n\n    papi_get_um_order_asyn_id.__doc__ = Client.papi_get_um_order_asyn_id.__doc__\n\n    async def papi_get_um_income_asyn(self, **params):\n        return await self._request_papi_api(\n            \"get\", \"um/income/asyn\", signed=True, data=params\n        )\n\n    papi_get_um_income_asyn.__doc__ = Client.papi_get_um_income_asyn.__doc__\n\n    async def papi_get_um_income_asyn_id(self, **params):\n        return await self._request_papi_api(\n            \"get\", \"um/income/asyn/id\", signed=True, data=params\n        )\n\n    papi_get_um_income_asyn_id.__doc__ = Client.papi_get_um_income_asyn_id.__doc__\n\n    async def papi_ping(self, **params):\n        return await self._request_papi_api(\"get\", \"ping\", signed=False, data=params)\n\n    # papi trading endpoints\n\n    papi_ping.__doc__ = Client.papi_ping.__doc__\n\n    async def papi_create_um_order(self, **params):\n        \"\"\"Place new UM order.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade\n\n        :returns: API response\n\n        \"\"\"\n        if \"newClientOrderId\" not in params:\n            params[\"newClientOrderId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n        return await self._request_papi_api(\n            \"post\", \"um/order\", signed=True, data=params\n        )\n\n    async def papi_create_um_conditional_order(self, **params):\n        \"\"\"Place new UM Conditional order.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/New-UM-Conditional-Order\n\n        :returns: API response\n\n        \"\"\"\n        if \"newClientOrderId\" not in params:\n            params[\"newClientOrderId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n        return await self._request_papi_api(\n            \"post\", \"um/conditional/order\", signed=True, data=params\n        )\n\n    async def papi_create_cm_order(self, **params):\n        \"\"\"Place new CM order.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/New-CM-Order\n\n        :returns: API response\n\n        \"\"\"\n        if \"newClientOrderId\" not in params:\n            params[\"newClientOrderId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n        return await self._request_papi_api(\n            \"post\", \"cm/order\", signed=True, data=params\n        )\n\n    async def papi_create_cm_conditional_order(self, **params):\n        \"\"\"Place new CM Conditional order.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/New-CM-Conditional-Order\n\n        :returns: API response\n\n        \"\"\"\n        if \"newClientOrderId\" not in params:\n            params[\"newClientOrderId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n        return await self._request_papi_api(\n            \"post\", \"cm/conditional/order\", signed=True, data=params\n        )\n\n    async def papi_create_margin_order(self, **params):\n        \"\"\"New Margin Order.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/New-Margin-Order\n\n        :returns: API response\n\n        \"\"\"\n        if \"newClientOrderId\" not in params:\n            params[\"newClientOrderId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n        return await self._request_papi_api(\n            \"post\", \"margin/order\", signed=True, data=params\n        )\n\n    async def papi_margin_loan(self, **params):\n        \"\"\"Apply for a margin loan.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Margin-Account-Borrow\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"post\", \"marginLoan\", signed=True, data=params\n        )\n\n    async def papi_repay_loan(self, **params):\n        \"\"\"Repay for a margin loan.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Margin-Account-Repay\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"post\", \"repayLoan\", signed=True, data=params\n        )\n\n    async def papi_margin_order_oco(self, **params):\n        \"\"\"Send in a new OCO for a margin account.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Margin-Account-New-OCO\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"post\", \"margin/order/oco\", signed=True, data=params\n        )\n\n    async def papi_cancel_um_order(self, **params):\n        \"\"\"Cancel an active UM LIMIT order.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Cancel-UM-Order\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"delete\", \"um/order\", signed=True, data=params\n        )\n\n    async def papi_cancel_um_all_open_orders(self, **params):\n        \"\"\"Cancel an active UM LIMIT order.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Cancel-All-UM-Open-Orders\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"delete\", \"um/allOpenOrders\", signed=True, data=params\n        )\n\n    async def papi_cancel_um_conditional_order(self, **params):\n        \"\"\"Cancel UM Conditional Order.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Cancel-UM-Conditional-Order\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"delete\", \"um/conditional/order\", signed=True, data=params\n        )\n\n    async def papi_cancel_um_conditional_all_open_orders(self, **params):\n        \"\"\"Cancel All UM Open Conditional Orders.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Cancel-All-UM-Open-Conditional-Orders\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"delete\", \"um/conditional/allOpenOrders\", signed=True, data=params\n        )\n\n    async def papi_cancel_cm_order(self, **params):\n        \"\"\"Cancel an active CM LIMIT order.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Cancel-CM-Order\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"delete\", \"cm/order\", signed=True, data=params\n        )\n\n    async def papi_cancel_cm_all_open_orders(self, **params):\n        \"\"\"Cancel an active CM LIMIT order.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Cancel-All-CM-Open-Orders\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"delete\", \"cm/allOpenOrders\", signed=True, data=params\n        )\n\n    async def papi_cancel_cm_conditional_order(self, **params):\n        \"\"\"Cancel CM Conditional Order.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Cancel-CM-Conditional-Order\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"delete\", \"cm/conditional/order\", signed=True, data=params\n        )\n\n    async def papi_cancel_cm_conditional_all_open_orders(self, **params):\n        \"\"\"Cancel All CM Open Conditional Orders.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Cancel-All-CM-Open-Conditional-Orders\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"delete\", \"cm/conditional/allOpenOrders\", signed=True, data=params\n        )\n\n    async def papi_cancel_margin_order(self, **params):\n        \"\"\"Cancel Margin Account Order.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Cancel-Margin-Account-Order\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"delete\", \"margin/order\", signed=True, data=params\n        )\n\n    async def papi_cancel_margin_order_list(self, **params):\n        \"\"\"Cancel Margin Account OCO Orders.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Cancel-Margin-Account-OCO-Orders\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"delete\", \"margin/orderList\", signed=True, data=params\n        )\n\n    async def papi_cancel_margin_all_open_orders(self, **params):\n        \"\"\"Cancel Margin Account All Open Orders on a Symbol.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Cancel-Margin-Account-All-Open-Orders-on-a-Symbol\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"delete\", \"margin/allOpenOrders\", signed=True, data=params\n        )\n\n    async def papi_modify_um_order(self, **params):\n        \"\"\"Order modify function, currently only LIMIT order modification is supported, modified orders will be reordered in the match queue.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Modify-UM-Order\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\"put\", \"um/order\", signed=True, data=params)\n\n    async def papi_modify_cm_order(self, **params):\n        \"\"\"Order modify function, currently only LIMIT order modification is supported, modified orders will be reordered in the match queue.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Modify-CM-Order\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\"put\", \"cm/order\", signed=True, data=params)\n\n    async def papi_get_um_order(self, **params):\n        \"\"\"Check an UM order's status.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-UM-Order\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\"get\", \"um/order\", signed=True, data=params)\n\n    async def papi_get_um_all_orders(self, **params):\n        \"\"\"Get all account UM orders; active, canceled, or filled.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-UM-Order\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"get\", \"um/allOrders\", signed=True, data=params\n        )\n\n    async def papi_get_um_open_order(self, **params):\n        \"\"\"Query current UM open order.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-Current-UM-Open-Order\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"get\", \"um/openOrder\", signed=True, data=params\n        )\n\n    async def papi_get_um_open_orders(self, **params):\n        \"\"\"Get all open orders on a symbol.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-All-Current-UM-Open-Orders\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"get\", \"um/openOrders\", signed=True, data=params\n        )\n\n    async def papi_get_um_conditional_all_orders(self, **params):\n        \"\"\"Query All UM Conditional Orders.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-All-UM-Conditional-Orders\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"get\", \"um/conditional/allOrders\", signed=True, data=params\n        )\n\n    async def papi_get_um_conditional_open_orders(self, **params):\n        \"\"\"Get all open conditional orders on a symbol.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-All-Current-UM-Open-Conditional-Orders\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"get\", \"um/conditional/openOrders\", signed=True, data=params\n        )\n\n    async def papi_get_um_conditional_open_order(self, **params):\n        \"\"\"Query Current UM Open Conditional Order.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-Current-UM-Open-Conditional-Order\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"get\", \"um/conditional/openOrder\", signed=True, data=params\n        )\n\n    async def papi_get_um_conditional_order_history(self, **params):\n        \"\"\"Get all open conditional orders on a symbol.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-UM-Conditional-Order-History\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"get\", \"um/conditional/orderHistory\", signed=True, data=params\n        )\n\n    async def papi_get_cm_order(self, **params):\n        \"\"\"Check an CM order's status.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-CM-Order\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\"get\", \"cm/order\", signed=True, data=params)\n\n    async def papi_get_cm_all_orders(self, **params):\n        \"\"\"Get all account CM orders; active, canceled, or filled.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-CM-Order\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"get\", \"cm/allOrders\", signed=True, data=params\n        )\n\n    async def papi_get_cm_open_order(self, **params):\n        \"\"\"Query current CM open order.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-Current-CM-Open-Order\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"get\", \"cm/openOrder\", signed=True, data=params\n        )\n\n    async def papi_get_cm_open_orders(self, **params):\n        \"\"\"Get all open orders on a symbol.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-All-Current-CM-Open-Orders\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"get\", \"cm/openOrders\", signed=True, data=params\n        )\n\n    async def papi_get_cm_conditional_all_orders(self, **params):\n        \"\"\"Query All CM Conditional Orders.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-All-CM-Conditional-Orders\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"get\", \"cm/conditional/allOrders\", signed=True, data=params\n        )\n\n    async def papi_get_cm_conditional_open_orders(self, **params):\n        \"\"\"Get all open conditional orders on a symbol.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-All-Current-CM-Open-Conditional-Orders\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"get\", \"cm/conditional/openOrders\", signed=True, data=params\n        )\n\n    async def papi_get_cm_conditional_open_order(self, **params):\n        \"\"\"Query Current UM Open Conditional Order.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-Current-CM-Open-Conditional-Order\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"get\", \"cm/conditional/openOrder\", signed=True, data=params\n        )\n\n    async def papi_get_cm_conditional_order_history(self, **params):\n        \"\"\"Get all open conditional orders on a symbol.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-CM-Conditional-Order-History\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"get\", \"cm/conditional/orderHistory\", signed=True, data=params\n        )\n\n    async def papi_get_um_force_orders(self, **params):\n        \"\"\"Query User's UM Force Orders.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-Users-UM-Force-Orders\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"get\", \"um/forceOrders\", signed=True, data=params\n        )\n\n    async def papi_get_cm_force_orders(self, **params):\n        \"\"\"Query User's CM Force Orders.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-Users-CM-Force-Orders\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"get\", \"cm/forceOrders\", signed=True, data=params\n        )\n\n    async def papi_get_um_order_amendment(self, **params):\n        \"\"\"Get order modification history.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-UM-Modify-Order-History\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"get\", \"um/orderAmendment\", signed=True, data=params\n        )\n\n    async def papi_get_cm_order_amendment(self, **params):\n        \"\"\"Get order modification history.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-CM-Modify-Order-History\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"get\", \"cm/orderAmendment\", signed=True, data=params\n        )\n\n    async def papi_get_margin_force_orders(self, **params):\n        \"\"\"Query user's margin force orders.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-Users-Margin-Force-Orders\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"get\", \"margin/forceOrders\", signed=True, data=params\n        )\n\n    async def papi_get_um_user_trades(self, **params):\n        \"\"\"Get trades for a specific account and UM symbol.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/UM-Account-Trade-List\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"get\", \"um/userTrades\", signed=True, data=params\n        )\n\n    async def papi_get_cm_user_trades(self, **params):\n        \"\"\"Get trades for a specific account and CM symbol.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/CM-Account-Trade-List\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"get\", \"cm/userTrades\", signed=True, data=params\n        )\n\n    async def papi_get_um_adl_quantile(self, **params):\n        \"\"\"Query UM Position ADL Quantile Estimation.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/UM-Position-ADL-Quantile-Estimation\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"get\", \"um/adlQuantile\", signed=True, data=params\n        )\n\n    async def papi_get_cm_adl_quantile(self, **params):\n        \"\"\"Query CM Position ADL Quantile Estimation.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/CM-Position-ADL-Quantile-Estimation\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"get\", \"cm/adlQuantile\", signed=True, data=params\n        )\n\n    async def papi_set_um_fee_burn(self, **params):\n        \"\"\"Change user's BNB Fee Discount for UM Futures (Fee Discount On or Fee Discount Off ) on EVERY symbol.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Toggle-BNB-Burn-On-UM-Futures-Trade\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"post\", \"um/feeBurn\", signed=True, data=params\n        )\n\n    async def papi_get_um_fee_burn(self, **params):\n        \"\"\"Get user's BNB Fee Discount for UM Futures (Fee Discount On or Fee Discount Off).\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Get-UM-Futures-BNB-Burn-Status\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"get\", \"um/feeBurn\", signed=True, data=params\n        )\n\n    async def papi_get_margin_order(self, **params):\n        \"\"\"Query Margin Account Order.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-Margin-Account-Order\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"get\", \"margin/order\", signed=True, data=params\n        )\n\n    async def papi_get_margin_open_orders(self, **params):\n        \"\"\"Query Current Margin Open Order.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-Margin-Account-Order\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"get\", \"margin/openOrders\", signed=True, data=params\n        )\n\n    async def papi_get_margin_all_orders(self, **params):\n        \"\"\"Query All Margin Account Orders.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-All-Margin-Account-Orders\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"get\", \"margin/allOrders\", signed=True, data=params\n        )\n\n    async def papi_get_margin_order_list(self, **params):\n        \"\"\"Retrieves a specific OCO based on provided optional parameters.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-Margin-Account-OCO\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"get\", \"margin/orderList\", signed=True, data=params\n        )\n\n    async def papi_get_margin_all_order_list(self, **params):\n        \"\"\"Query all OCO for a specific margin account based on provided optional parameters.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-Margin-Account-all-OCO\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"get\", \"margin/allOrderList\", signed=True, data=params\n        )\n\n    async def papi_get_margin_open_order_list(self, **params):\n        \"\"\"Query Margin Account's Open OCO.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-Margin-Account-Open-OCO\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"get\", \"margin/openOrderList\", signed=True, data=params\n        )\n\n    async def papi_get_margin_my_trades(self, **params):\n        \"\"\"Margin Account Trade List.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Margin-Account-Trade-List\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"get\", \"margin/myTrades\", signed=True, data=params\n        )\n\n    async def papi_get_margin_repay_debt(self, **params):\n        \"\"\"Repay debt for a margin loan.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Margin-Account-Trade-List\n\n        :returns: API response\n\n        \"\"\"\n        return await self._request_papi_api(\n            \"post\", \"margin/repay-debt\", signed=True, data=params\n        )\n\n    async def create_oco_order(self, **params):\n        if \"listClientOrderId\" not in params:\n            params[\"listClientOrderId\"] = self.SPOT_ORDER_PREFIX + self.uuid22()\n        return await self._post(\"orderList/oco\", True, data=params)\n\n    ############################################################\n    # WebSocket API methods\n    ############################################################\n\n    create_oco_order.__doc__ = Client.create_oco_order.__doc__\n\n    async def ws_create_test_order(self, **params):\n        \"\"\"Test new order creation and signature/recvWindow long. Creates and validates a new order but does not send it into the matching engine.\n        https://binance-docs.github.io/apidocs/websocket_api/en/#test-new-order-trade\n        :param symbol: required\n        :type symbol: str\n        :param side: required\n        :type side: str\n        :param type: required\n        :type type: str\n        :param timeInForce: required if limit order\n        :type timeInForce: str\n        :param quantity: required\n        :type quantity: decimal\n        :param price: required\n        :type price: str\n        :param newClientOrderId: A unique id for the order. Automatically generated if not sent.\n        :type newClientOrderId: str\n        :param icebergQty: Used with iceberg orders\n        :type icebergQty: decimal\n        :param newOrderRespType: Set the response JSON. ACK, RESULT, or FULL; default: RESULT.\n        :type newOrderRespType: str\n        :param recvWindow: The number of milliseconds the request is valid for\n        :type recvWindow: int\n        :returns: WS response\n        .. code-block:: python\n            {}\n        \"\"\"\n        if \"newClientOrderId\" not in params:\n            params[\"newClientOrderId\"] = self.SPOT_ORDER_PREFIX + self.uuid22()\n\n        return await self._ws_api_request(\"order.test\", True, params)\n\n    async def ws_create_order(self, **params):\n        \"\"\"Create an order via WebSocket.\n        https://binance-docs.github.io/apidocs/websocket_api/en/#place-new-order-trade\n        :param id: The request ID to be used. By default uuid22() is used.\n        :param symbol: The symbol to create an order for\n        :param side: BUY or SELL\n        :param type: Order type (e.g., LIMIT, MARKET)\n        :param quantity: The amount to buy or sell\n        :param kwargs: Additional order parameters\n        \"\"\"\n        if \"newClientOrderId\" not in params:\n            params[\"newClientOrderId\"] = self.SPOT_ORDER_PREFIX + self.uuid22()\n\n        return await self._ws_api_request(\"order.place\", True, params)\n\n    async def ws_order_limit(self, timeInForce=BaseClient.TIME_IN_FORCE_GTC, **params):\n        \"\"\"Send in a new limit order\n        Any order with an icebergQty MUST have timeInForce set to GTC.\n        :param symbol: required\n        :type symbol: str\n        :param side: required\n        :type side: str\n        :param quantity: required\n        :type quantity: decimal\n        :param price: required\n        :type price: str\n        :param timeInForce: default Good till cancelled\n        :type timeInForce: str\n        :param newClientOrderId: A unique id for the order. Automatically generated if not sent.\n        :type newClientOrderId: str\n        :param icebergQty: Used with LIMIT, STOP_LOSS_LIMIT, and TAKE_PROFIT_LIMIT to create an iceberg order.\n        :type icebergQty: decimal\n        :param newOrderRespType: Set the response JSON. ACK, RESULT, or FULL; default: RESULT.\n        :type newOrderRespType: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n        :returns: WS response\n        See order endpoint for full response options\n        \"\"\"\n        params.update({\n            \"type\": self.ORDER_TYPE_LIMIT,\n            \"timeInForce\": timeInForce,\n        })\n        return await self.ws_create_order(**params)\n\n    async def ws_order_limit_buy(\n        self, timeInForce=BaseClient.TIME_IN_FORCE_GTC, **params\n    ):\n        \"\"\"Send in a new limit buy order\n        Any order with an icebergQty MUST have timeInForce set to GTC.\n        :param symbol: required\n        :type symbol: str\n        :param quantity: required\n        :type quantity: decimal\n        :param price: required\n        :type price: str\n        :param timeInForce: default Good till cancelled\n        :type timeInForce: str\n        :param newClientOrderId: A unique id for the order. Automatically generated if not sent.\n        :type newClientOrderId: str\n        :param stopPrice: Used with stop orders\n        :type stopPrice: decimal\n        :param icebergQty: Used with iceberg orders\n        :type icebergQty: decimal\n        :param newOrderRespType: Set the response JSON. ACK, RESULT, or FULL; default: RESULT.\n        :type newOrderRespType: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n        :returns: WS response\n        See order endpoint for full response options\n        \"\"\"\n        params.update({\n            \"side\": self.SIDE_BUY,\n        })\n        return await self.ws_order_limit(timeInForce=timeInForce, **params)\n\n    async def ws_order_limit_sell(\n        self, timeInForce=BaseClient.TIME_IN_FORCE_GTC, **params\n    ):\n        \"\"\"Send in a new limit sell order\n        :param symbol: required\n        :type symbol: str\n        :param quantity: required\n        :type quantity: decimal\n        :param price: required\n        :type price: str\n        :param timeInForce: default Good till cancelled\n        :type timeInForce: str\n        :param newClientOrderId: A unique id for the order. Automatically generated if not sent.\n        :type newClientOrderId: str\n        :param stopPrice: Used with stop orders\n        :type stopPrice: decimal\n        :param icebergQty: Used with iceberg orders\n        :type icebergQty: decimal\n        :param newOrderRespType: Set the response JSON. ACK, RESULT, or FULL; default: RESULT.\n        :type newOrderRespType: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n        :returns: WS response\n        See order endpoint for full response options\n        \"\"\"\n        params.update({\"side\": self.SIDE_SELL})\n        return await self.ws_order_limit(timeInForce=timeInForce, **params)\n\n    async def ws_order_market(self, **params):\n        \"\"\"Send in a new market order\n        :param symbol: required\n        :type symbol: str\n        :param side: required\n        :type side: str\n        :param quantity: required\n        :type quantity: decimal\n        :param quoteOrderQty: amount the user wants to spend (when buying) or receive (when selling)\n            of the quote asset\n        :type quoteOrderQty: decimal\n        :param newClientOrderId: A unique id for the order. Automatically generated if not sent.\n        :type newClientOrderId: str\n        :param newOrderRespType: Set the response JSON. ACK, RESULT, or FULL; default: RESULT.\n        :type newOrderRespType: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n        :returns: WS response\n        See order endpoint for full response options\n        \"\"\"\n        params.update({\"type\": self.ORDER_TYPE_MARKET})\n        return await self.ws_create_order(**params)\n\n    async def ws_order_market_buy(self, **params):\n        \"\"\"Send in a new market buy order\n        :param symbol: required\n        :type symbol: str\n        :param quantity: required\n        :type quantity: decimal\n        :param quoteOrderQty: the amount the user wants to spend of the quote asset\n        :type quoteOrderQty: decimal\n        :param newClientOrderId: A unique id for the order. Automatically generated if not sent.\n        :type newClientOrderId: str\n        :param newOrderRespType: Set the response JSON. ACK, RESULT, or FULL; default: RESULT.\n        :type newOrderRespType: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n        :returns: WS response\n        See order endpoint for full response options\n        \"\"\"\n        params.update({\"side\": self.SIDE_BUY})\n        return await self.ws_order_market(**params)\n\n    async def ws_order_market_sell(self, **params):\n        \"\"\"Send in a new market sell order\n        :param symbol: required\n        :type symbol: str\n        :param quantity: required\n        :type quantity: decimal\n        :param quoteOrderQty: the amount the user wants to receive of the quote asset\n        :type quoteOrderQty: decimal\n        :param newClientOrderId: A unique id for the order. Automatically generated if not sent.\n        :type newClientOrderId: str\n        :param newOrderRespType: Set the response JSON. ACK, RESULT, or FULL; default: RESULT.\n        :type newOrderRespType: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n        :returns: WS response\n        See order endpoint for full response options\n        \"\"\"\n        params.update({\"side\": self.SIDE_SELL})\n        return await self.ws_order_market(**params)\n\n    async def ws_get_order(self, **params):\n        \"\"\"Check an order's status. Either orderId or origClientOrderId must be sent.\n        https://binance-docs.github.io/apidocs/websocket_api/en/#query-order-user_data\n        :param symbol: required\n        :type symbol: str\n        :param orderId: The unique order id\n        :type orderId: int\n        :param origClientOrderId: optional\n        :type origClientOrderId: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n        \"\"\"\n\n        return await self._ws_api_request(\"order.status\", True, params)\n\n    async def ws_cancel_order(self, **params):\n        return await self._ws_api_request(\"order.cancel\", True, params)\n\n    ws_cancel_order.__doc__ = Client.ws_cancel_order.__doc__\n\n    async def cancel_all_open_orders(self, **params):\n        return await self._delete(\"openOrders\", True, data=params)\n\n    cancel_all_open_orders.__doc__ = Client.cancel_all_open_orders.__doc__\n\n    async def cancel_replace_order(self, **params):\n        if \"newClientOrderId\" not in params:\n            params[\"newClientOrderId\"] = self.SPOT_ORDER_PREFIX + self.uuid22()\n        return await self._post(\"order/cancelReplace\", signed=True, data=params)\n\n    cancel_replace_order.__doc__ = Client.cancel_replace_order.__doc__\n\n    async def ws_cancel_and_replace_order(self, **params):\n        return await self._ws_api_request(\"order.cancelReplace\", True, params)\n\n    ws_cancel_and_replace_order.__doc__ = Client.ws_cancel_and_replace_order.__doc__\n\n    async def ws_get_open_orders(self, **params):\n        return await self._ws_api_request(\"openOrders.status\", True, params)\n\n    ws_get_open_orders.__doc__ = Client.ws_get_open_orders.__doc__\n\n    async def ws_cancel_all_open_orders(self, **params):\n        return await self._ws_api_request(\"openOrders.cancelAll\", True, params)\n\n    ws_cancel_all_open_orders.__doc__ = Client.ws_cancel_all_open_orders.__doc__\n\n    async def ws_create_oco_order(self, **params):\n        return await self._ws_api_request(\"orderList.place.oco\", True, params)\n\n    ws_create_oco_order.__doc__ = Client.ws_create_oco_order.__doc__\n\n    async def ws_create_oto_order(self, **params):\n        return await self._ws_api_request(\"orderList.place.oto\", True, params)\n\n    ws_create_oto_order.__doc__ = Client.ws_create_oto_order.__doc__\n\n    async def ws_create_otoco_order(self, **params):\n        return await self._ws_api_request(\"orderList.place.otoco\", True, params)\n\n    ws_create_otoco_order.__doc__ = Client.ws_create_otoco_order.__doc__\n\n    async def ws_get_oco_order(self, **params):\n        return await self._ws_api_request(\"orderList.status\", True, params)\n\n    ws_get_oco_order.__doc__ = Client.ws_get_oco_order.__doc__\n\n    async def ws_cancel_oco_order(self, **params):\n        return await self._ws_api_request(\"orderList.cancel\", True, params)\n\n    ws_cancel_oco_order.__doc__ = Client.ws_cancel_oco_order.__doc__\n\n    async def ws_get_oco_open_orders(self, **params):\n        return await self._ws_api_request(\"openOrderLists.status\", True, params)\n\n    ws_get_oco_open_orders.__doc__ = Client.ws_get_oco_open_orders.__doc__\n\n    async def ws_create_sor_order(self, **params):\n        return await self._ws_api_request(\"sor.order.place\", True, params)\n\n    ws_create_sor_order.__doc__ = Client.ws_create_sor_order.__doc__\n\n    async def ws_create_test_sor_order(self, **params):\n        return await self._ws_api_request(\"sor.order.test\", True, params)\n\n    ws_create_test_sor_order.__doc__ = Client.ws_create_test_sor_order.__doc__\n\n    async def ws_get_account(self, **params):\n        return await self._ws_api_request(\"account.status\", True, params)\n\n    ws_get_account.__doc__ = Client.ws_get_account.__doc__\n\n    async def ws_get_account_rate_limits_orders(self, **params):\n        return await self._ws_api_request(\"account.rateLimits.orders\", True, params)\n\n    ws_get_account_rate_limits_orders.__doc__ = Client.ws_get_account_rate_limits_orders.__doc__\n\n    async def ws_get_all_orders(self, **params):\n        return await self._ws_api_request(\"allOrders\", True, params)\n\n    ws_get_all_orders.__doc__ = Client.ws_get_all_orders.__doc__\n\n    async def ws_get_my_trades(self, **params):\n        return await self._ws_api_request(\"myTrades\", True, params)\n\n    ws_get_my_trades.__doc__ = Client.ws_get_my_trades.__doc__\n\n    async def ws_get_prevented_matches(self, **params):\n        return await self._ws_api_request(\"myPreventedMatches\", True, params)\n\n    ws_get_prevented_matches.__doc__ = Client.ws_get_prevented_matches.__doc__\n\n    async def ws_get_allocations(self, **params):\n        return await self._ws_api_request(\"myAllocations\", True, params)\n\n    ws_get_allocations.__doc__ = Client.ws_get_allocations.__doc__\n\n    async def ws_get_commission_rates(self, **params):\n        return await self._ws_api_request(\"account.commission\", True, params)\n\n    ws_get_commission_rates.__doc__ = Client.ws_get_commission_rates.__doc__\n\n    async def ws_get_order_book(self, **params):\n        return await self._ws_api_request(\"depth\", False, params)\n\n    ws_get_order_book.__doc__ = Client.ws_get_order_book.__doc__\n\n    async def ws_get_recent_trades(self, **params):\n        return await self._ws_api_request(\"trades.recent\", False, params)\n\n    ws_get_recent_trades.__doc__ = Client.ws_get_recent_trades.__doc__\n\n    async def ws_get_historical_trades(self, **params):\n        return await self._ws_api_request(\"trades.historical\", False, params)\n\n    ws_get_historical_trades.__doc__ = Client.ws_get_historical_trades.__doc__\n\n    async def ws_get_aggregate_trades(self, **params):\n        return await self._ws_api_request(\"trades.aggregate\", False, params)\n\n    ws_get_aggregate_trades.__doc__ = Client.ws_get_aggregate_trades.__doc__\n\n    async def ws_get_klines(self, **params):\n        return await self._ws_api_request(\"klines\", False, params)\n\n    ws_get_klines.__doc__ = Client.ws_get_klines.__doc__\n\n    async def ws_get_uiKlines(self, **params):\n        return await self._ws_api_request(\"uiKlines\", False, params)\n\n    ws_get_uiKlines.__doc__ = Client.ws_get_uiKlines.__doc__\n\n    async def ws_get_avg_price(self, **params):\n        return await self._ws_api_request(\"avgPrice\", False, params)\n\n    ws_get_avg_price.__doc__ = Client.ws_get_avg_price.__doc__\n\n    async def ws_get_ticker(self, **params):\n        return await self._ws_api_request(\"ticker.24hr\", False, params)\n\n    ws_get_ticker.__doc__ = Client.ws_get_ticker.__doc__\n\n    async def ws_get_trading_day_ticker(self, **params):\n        return await self._ws_api_request(\"ticker.tradingDay\", False, params)\n\n    ws_get_trading_day_ticker.__doc__ = Client.ws_get_trading_day_ticker.__doc__\n\n    async def ws_get_symbol_ticker_window(self, **params):\n        return await self._ws_api_request(\"ticker\", False, params)\n\n    ws_get_symbol_ticker_window.__doc__ = Client.ws_get_symbol_ticker_window.__doc__\n\n    async def ws_get_symbol_ticker(self, **params):\n        return await self._ws_api_request(\"ticker.price\", False, params)\n\n    ws_get_symbol_ticker.__doc__ = Client.ws_get_symbol_ticker.__doc__\n\n    async def ws_get_orderbook_ticker(self, **params):\n        return await self._ws_api_request(\"ticker.book\", False, params)\n\n    ws_get_orderbook_ticker.__doc__ = Client.ws_get_orderbook_ticker.__doc__\n\n    async def ws_ping(self, **params):\n        return await self._ws_api_request(\"ping\", False, params)\n\n    ws_ping.__doc__ = Client.ws_ping.__doc__\n\n    async def ws_get_time(self, **params):\n        return await self._ws_api_request(\"time\", False, params)\n\n    ws_get_time.__doc__ = Client.ws_get_time.__doc__\n\n    async def ws_get_exchange_info(self, **params):\n        return await self._ws_api_request(\"exchangeInfo\", False, params)\n\n    ws_get_exchange_info.__doc__ = Client.ws_get_exchange_info.__doc__\n\n    ####################################################\n    # FUTURES WS API Endpoints\n    ####################################################\n    async def ws_futures_get_order_book(self, **params):\n        \"\"\"\n        Get the order book for a symbol\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/websocket-api\n        \"\"\"\n        return await self._ws_futures_api_request(\"depth\", False, params)\n\n    async def ws_futures_get_all_tickers(self, **params):\n        \"\"\"\n        Latest price for a symbol or symbols\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/websocket-api/Symbol-Price-Ticker\n        \"\"\"\n        return await self._ws_futures_api_request(\"ticker.price\", False, params)\n\n    async def ws_futures_get_order_book_ticker(self, **params):\n        \"\"\"\n        Best price/qty on the order book for a symbol or symbols.\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/websocket-api/Symbol-Order-Book-Ticker\n        \"\"\"\n        return await self._ws_futures_api_request(\"ticker.book\", False, params)\n\n    async def ws_futures_create_order(self, **params):\n        \"\"\"\n        Send in a new order\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api\n        \"\"\"\n        # Check if this is a conditional order type that needs to use algo endpoint\n        order_type = params.get(\"type\", \"\").upper()\n        conditional_types = [\n            \"STOP\",\n            \"STOP_MARKET\",\n            \"TAKE_PROFIT\",\n            \"TAKE_PROFIT_MARKET\",\n            \"TRAILING_STOP_MARKET\",\n        ]\n\n        if order_type in conditional_types:\n            # Route to algo order endpoint\n            if \"clientAlgoId\" not in params:\n                params[\"clientAlgoId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n            # Remove newClientOrderId if it was added by default\n            params.pop(\"newClientOrderId\", None)\n            if \"algoType\" not in params:\n                params[\"algoType\"] = \"CONDITIONAL\"\n            # Convert stopPrice to triggerPrice for algo orders\n            if \"stopPrice\" in params and \"triggerPrice\" not in params:\n                params[\"triggerPrice\"] = params.pop(\"stopPrice\")\n            return await self._ws_futures_api_request(\"algoOrder.place\", True, params)\n        else:\n            # Use regular order endpoint\n            if \"newClientOrderId\" not in params:\n                params[\"newClientOrderId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n            return await self._ws_futures_api_request(\"order.place\", True, params)\n\n    async def ws_futures_edit_order(self, **params):\n        \"\"\"\n        Edit an order\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api/Modify-Order\n        \"\"\"\n        return await self._ws_futures_api_request(\"order.modify\", True, params)\n\n    async def ws_futures_cancel_order(self, **params):\n        \"\"\"\n        cancel an order\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api/Cancel-Order\n        \"\"\"\n        is_conditional = False\n        if \"algoId\" in params or \"clientAlgoId\" in params:\n            is_conditional = True\n\n        if is_conditional:\n            return await self._ws_futures_api_request(\"algoOrder.cancel\", True, params)\n        else:\n            return await self._ws_futures_api_request(\"order.cancel\", True, params)\n\n    async def ws_futures_get_order(self, **params):\n        \"\"\"\n        Get an order\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api/Query-Order\n\n        Note: Algo/conditional orders cannot be queried via websocket API\n        \"\"\"\n        return await self._ws_futures_api_request(\"order.status\", True, params)\n\n    async def ws_futures_v2_account_position(self, **params):\n        \"\"\"\n        Get current position information(only symbol that has position or open orders will be return awaited).\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api/Position-Info-V2\n        \"\"\"\n        return await self._ws_futures_api_request(\"v2/account.position\", True, params)\n\n    async def ws_futures_account_position(self, **params):\n        \"\"\"\n        Get current position information.\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api/Position-Information\n        \"\"\"\n        return await self._ws_futures_api_request(\"account.position\", True, params)\n\n    async def ws_futures_v2_account_balance(self, **params):\n        \"\"\"\n        Get current account information.\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api#api-description\n        \"\"\"\n        return await self._ws_futures_api_request(\"v2/account.balance\", True, params)\n\n    async def ws_futures_account_balance(self, **params):\n        \"\"\"\n        Get current account information.\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api/Futures-Account-Balance\n        \"\"\"\n        return await self._ws_futures_api_request(\"account.balance\", True, params)\n\n    async def ws_futures_v2_account_status(self, **params):\n        \"\"\"\n        Get current account information. User in single-asset/ multi-assets mode will see different value, see comments in response section for detail.\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api/Account-Information-V2\n        \"\"\"\n        return await self._ws_futures_api_request(\"v2/account.status\", True, params)\n\n    async def ws_futures_account_status(self, **params):\n        \"\"\"\n        Get current account information. User in single-asset/ multi-assets mode will see different value, see comments in response section for detail.\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api/Account-Information\n        \"\"\"\n        return await self._ws_futures_api_request(\"account.status\", True, params)\n\n    async def ws_futures_create_algo_order(self, **params):\n        if \"clientAlgoId\" not in params:\n            params[\"clientAlgoId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n        return await self._ws_futures_api_request(\"algoOrder.place\", True, params)\n    ws_futures_create_algo_order.__doc__ = Client.ws_futures_create_algo_order.__doc__\n\n    async def ws_futures_cancel_algo_order(self, **params):\n        return await self._ws_futures_api_request(\"algoOrder.cancel\", True, params)\n\n    ws_futures_cancel_algo_order.__doc__ = Client.ws_futures_cancel_algo_order.__doc__\n\n    ####################################################\n    # Gift Card API Endpoints\n    ####################################################\n\n    async def gift_card_fetch_token_limit(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"giftcard/buyCode/token-limit\", signed=True, data=params\n        )\n\n    gift_card_fetch_token_limit.__doc__ = Client.gift_card_fetch_token_limit.__doc__\n\n    async def gift_card_fetch_rsa_public_key(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"giftcard/cryptography/rsa-public-key\", signed=True, data=params\n        )\n\n    gift_card_fetch_rsa_public_key.__doc__ = (\n        Client.gift_card_fetch_rsa_public_key.__doc__\n    )\n\n    async def gift_card_verify(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"giftcard/verify\", signed=True, data=params\n        )\n\n    gift_card_verify.__doc__ = Client.gift_card_verify.__doc__\n\n    async def gift_card_redeem(self, **params):\n        return await self._request_margin_api(\n            \"post\", \"giftcard/redeemCode\", signed=True, data=params\n        )\n\n    gift_card_redeem.__doc__ = Client.gift_card_redeem.__doc__\n\n    async def gift_card_create(self, **params):\n        return await self._request_margin_api(\n            \"post\", \"giftcard/createCode\", signed=True, data=params\n        )\n\n    gift_card_create.__doc__ = Client.gift_card_create.__doc__\n\n    async def gift_card_create_dual_token(self, **params):\n        return await self._request_margin_api(\n            \"post\", \"giftcard/buyCode\", signed=True, data=params\n        )\n\n    gift_card_create_dual_token.__doc__ = Client.gift_card_create_dual_token.__doc__\n\n    ####################################################\n    # Options - Market Maker Block Trade\n    ####################################################\n\n    async def options_create_block_trade_order(self, **params):\n        return await self._request_options_api(\n            \"post\", \"block/order/create\", signed=True, data=params\n        )\n\n    options_create_block_trade_order.__doc__ = (\n        Client.options_create_block_trade_order.__doc__\n    )\n\n    async def options_cancel_block_trade_order(self, **params):\n        return await self._request_options_api(\n            \"delete\", \"block/order/create\", signed=True, data=params\n        )\n\n    options_cancel_block_trade_order.__doc__ = (\n        Client.options_cancel_block_trade_order.__doc__\n    )\n\n    async def options_extend_block_trade_order(self, **params):\n        return await self._request_options_api(\n            \"put\", \"block/order/create\", signed=True, data=params\n        )\n\n    options_extend_block_trade_order.__doc__ = (\n        Client.options_extend_block_trade_order.__doc__\n    )\n\n    async def options_get_block_trade_orders(self, **params):\n        return await self._request_options_api(\n            \"get\", \"block/order/orders\", signed=True, data=params\n        )\n\n    options_get_block_trade_orders.__doc__ = (\n        Client.options_get_block_trade_orders.__doc__\n    )\n\n    async def options_accept_block_trade_order(self, **params):\n        return await self._request_options_api(\n            \"post\", \"block/order/execute\", signed=True, data=params\n        )\n\n    options_accept_block_trade_order.__doc__ = (\n        Client.options_accept_block_trade_order.__doc__\n    )\n\n    async def options_get_block_trade_order(self, **params):\n        return await self._request_options_api(\n            \"get\", \"block/order/execute\", signed=True, data=params\n        )\n\n    options_get_block_trade_order.__doc__ = Client.options_get_block_trade_order.__doc__\n\n    async def options_account_get_block_trades(self, **params):\n        return await self._request_options_api(\n            \"get\", \"block/user-trades\", signed=True, data=params\n        )\n\n    options_account_get_block_trades.__doc__ = (\n        Client.options_account_get_block_trades.__doc__\n    )\n\n    async def margin_next_hourly_interest_rate(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"margin/next-hourly-interest-rate\", signed=True, data=params\n        )\n\n    margin_next_hourly_interest_rate.__doc__ = (\n        Client.margin_next_hourly_interest_rate.__doc__\n    )\n\n    async def margin_interest_history(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"margin/interestHistory\", signed=True, data=params\n        )\n\n    margin_interest_history.__doc__ = Client.margin_interest_history.__doc__\n\n    async def margin_borrow_repay(self, **params):\n        return await self._request_margin_api(\n            \"post\", \"margin/borrow-repay\", signed=True, data=params\n        )\n\n    margin_borrow_repay.__doc__ = Client.margin_borrow_repay.__doc__\n\n    async def margin_get_borrow_repay_records(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"margin/borrow-repay\", signed=True, data=params\n        )\n\n    margin_get_borrow_repay_records.__doc__ = (\n        Client.margin_get_borrow_repay_records.__doc__\n    )\n\n    async def margin_interest_rate_history(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"margin/interestRateHistory\", signed=True, data=params\n        )\n\n    margin_interest_rate_history.__doc__ = Client.margin_interest_rate_history.__doc__\n\n    async def margin_max_borrowable(self, **params):\n        return await self._request_margin_api(\n            \"get\", \"margin/maxBorrowable\", signed=True, data=params\n        )\n\n    margin_max_borrowable.__doc__ = Client.margin_max_borrowable.__doc__\n\n    ####################################################\n    # Futures Data\n    ####################################################\n\n    async def futures_historical_data_link(self, **params):\n        return await self._request_margin_api(\"get\", \"futures/data/histDataLink\", signed=True, data=params)\n\n    futures_historical_data_link.__doc__ = Client.futures_historical_data_link.__doc__\n\n    async def margin_v1_get_loan_vip_ongoing_orders(self, **params):\n        return await self._request_margin_api(\"get\", \"loan/vip/ongoing/orders\", signed=True, data=params, version=1)\n        \n    margin_v1_get_loan_vip_ongoing_orders.__doc__ = Client.margin_v1_get_loan_vip_ongoing_orders.__doc__\n            \n    async def margin_v1_get_mining_payment_other(self, **params):\n        return await self._request_margin_api(\"get\", \"mining/payment/other\", signed=True, data=params, version=1)\n        \n    margin_v1_get_mining_payment_other.__doc__ = Client.margin_v1_get_mining_payment_other.__doc__\n            \n    async def futures_coin_v1_get_income_asyn_id(self, **params):\n        return await self._request_futures_coin_api(\"get\", \"income/asyn/id\", signed=True, data=params, version=1)\n        \n    futures_coin_v1_get_income_asyn_id.__doc__ = Client.futures_coin_v1_get_income_asyn_id.__doc__\n            \n    async def margin_v1_get_simple_earn_flexible_history_subscription_record(self, **params):\n        return await self._request_margin_api(\"get\", \"simple-earn/flexible/history/subscriptionRecord\", signed=True, data=params, version=1)\n        \n    margin_v1_get_simple_earn_flexible_history_subscription_record.__doc__ = Client.margin_v1_get_simple_earn_flexible_history_subscription_record.__doc__\n            \n    async def margin_v1_post_lending_auto_invest_one_off(self, **params):\n        return await self._request_margin_api(\"post\", \"lending/auto-invest/one-off\", signed=True, data=params, version=1)\n        \n    margin_v1_post_lending_auto_invest_one_off.__doc__ = Client.margin_v1_post_lending_auto_invest_one_off.__doc__\n            \n    async def margin_v1_post_broker_sub_account_api_commission_coin_futures(self, **params):\n        return await self._request_margin_api(\"post\", \"broker/subAccountApi/commission/coinFutures\", signed=True, data=params, version=1)\n        \n    margin_v1_post_broker_sub_account_api_commission_coin_futures.__doc__ = Client.margin_v1_post_broker_sub_account_api_commission_coin_futures.__doc__\n            \n    async def v3_post_order_list_otoco(self, **params):\n        return await self._request_api(\"post\", \"orderList/otoco\", signed=True, data=params, version=\"v3\")\n        \n    v3_post_order_list_otoco.__doc__ = Client.v3_post_order_list_otoco.__doc__\n            \n    async def futures_v1_get_order_asyn(self, **params):\n        return await self._request_futures_api(\"get\", \"order/asyn\", signed=True, data=params, version=1)\n        \n    futures_v1_get_order_asyn.__doc__ = Client.futures_v1_get_order_asyn.__doc__\n            \n    async def margin_v1_get_asset_custody_transfer_history(self, **params):\n        return await self._request_margin_api(\"get\", \"asset/custody/transfer-history\", signed=True, data=params, version=1)\n        \n    margin_v1_get_asset_custody_transfer_history.__doc__ = Client.margin_v1_get_asset_custody_transfer_history.__doc__\n            \n    async def margin_v1_post_broker_sub_account_blvt(self, **params):\n        return await self._request_margin_api(\"post\", \"broker/subAccount/blvt\", signed=True, data=params, version=1)\n        \n    margin_v1_post_broker_sub_account_blvt.__doc__ = Client.margin_v1_post_broker_sub_account_blvt.__doc__\n            \n    async def margin_v1_post_sol_staking_sol_redeem(self, **params):\n        return await self._request_margin_api(\"post\", \"sol-staking/sol/redeem\", signed=True, data=params, version=1)\n        \n    margin_v1_post_sol_staking_sol_redeem.__doc__ = Client.margin_v1_post_sol_staking_sol_redeem.__doc__\n            \n    async def options_v1_get_countdown_cancel_all(self, **params):\n        return await self._request_options_api(\"get\", \"countdownCancelAll\", signed=True, data=params)\n        \n    options_v1_get_countdown_cancel_all.__doc__ = Client.options_v1_get_countdown_cancel_all.__doc__\n            \n    async def margin_v1_get_margin_trade_coeff(self, **params):\n        return await self._request_margin_api(\"get\", \"margin/tradeCoeff\", signed=True, data=params, version=1)\n        \n    margin_v1_get_margin_trade_coeff.__doc__ = Client.margin_v1_get_margin_trade_coeff.__doc__\n            \n    async def futures_coin_v1_get_order_amendment(self, **params):\n        return await self._request_futures_coin_api(\"get\", \"orderAmendment\", signed=True, data=params, version=1)\n        \n    futures_coin_v1_get_order_amendment.__doc__ = Client.futures_coin_v1_get_order_amendment.__doc__\n            \n    async def margin_v1_get_margin_available_inventory(self, **params):\n        return await self._request_margin_api(\"get\", \"margin/available-inventory\", signed=True, data=params, version=1)\n        \n    margin_v1_get_margin_available_inventory.__doc__ = Client.margin_v1_get_margin_available_inventory.__doc__\n            \n    async def margin_v1_post_account_api_restrictions_ip_restriction_ip_list(self, **params):\n        return await self._request_margin_api(\"post\", \"account/apiRestrictions/ipRestriction/ipList\", signed=True, data=params, version=1)\n        \n    margin_v1_post_account_api_restrictions_ip_restriction_ip_list.__doc__ = Client.margin_v1_post_account_api_restrictions_ip_restriction_ip_list.__doc__\n            \n    async def margin_v2_get_eth_staking_account(self, **params):\n        return await self._request_margin_api(\"get\", \"eth-staking/account\", signed=True, data=params, version=2)\n        \n    margin_v2_get_eth_staking_account.__doc__ = Client.margin_v2_get_eth_staking_account.__doc__\n            \n    async def margin_v1_get_loan_income(self, **params):\n        return await self._request_margin_api(\"get\", \"loan/income\", signed=True, data=params, version=1)\n        \n    margin_v1_get_loan_income.__doc__ = Client.margin_v1_get_loan_income.__doc__\n            \n    async def futures_coin_v1_get_pm_account_info(self, **params):\n        return await self._request_futures_coin_api(\"get\", \"pmAccountInfo\", signed=True, data=params, version=1)\n        \n    futures_coin_v1_get_pm_account_info.__doc__ = Client.futures_coin_v1_get_pm_account_info.__doc__\n            \n    async def margin_v1_get_managed_subaccount_query_trans_log_for_investor(self, **params):\n        return await self._request_margin_api(\"get\", \"managed-subaccount/queryTransLogForInvestor\", signed=True, data=params, version=1)\n        \n    margin_v1_get_managed_subaccount_query_trans_log_for_investor.__doc__ = Client.margin_v1_get_managed_subaccount_query_trans_log_for_investor.__doc__\n            \n    async def margin_v1_post_dci_product_auto_compound_edit_status(self, **params):\n        return await self._request_margin_api(\"post\", \"dci/product/auto_compound/edit-status\", signed=True, data=params, version=1)\n        \n    margin_v1_post_dci_product_auto_compound_edit_status.__doc__ = Client.margin_v1_post_dci_product_auto_compound_edit_status.__doc__\n            \n    async def futures_v1_get_trade_asyn(self, **params):\n        return await self._request_futures_api(\"get\", \"trade/asyn\", signed=True, data=params, version=1)\n        \n    futures_v1_get_trade_asyn.__doc__ = Client.futures_v1_get_trade_asyn.__doc__\n            \n    async def margin_v1_get_loan_vip_request_interest_rate(self, **params):\n        return await self._request_margin_api(\"get\", \"loan/vip/request/interestRate\", signed=True, data=params, version=1)\n        \n    margin_v1_get_loan_vip_request_interest_rate.__doc__ = Client.margin_v1_get_loan_vip_request_interest_rate.__doc__\n            \n    async def futures_v1_get_funding_info(self, **params):\n        return await self._request_futures_api(\"get\", \"fundingInfo\", signed=False, data=params, version=1)\n        \n    futures_v1_get_funding_info.__doc__ = Client.futures_v1_get_funding_info.__doc__\n            \n    async def v3_get_all_orders(self, **params):\n        return await self._request_api(\"get\", \"allOrders\", signed=True, data=params, version=\"v3\")\n        \n    async def margin_v2_get_loan_flexible_repay_rate(self, **params):\n        return await self._request_margin_api(\"get\", \"loan/flexible/repay/rate\", signed=True, data=params, version=2)\n        \n    margin_v2_get_loan_flexible_repay_rate.__doc__ = Client.margin_v2_get_loan_flexible_repay_rate.__doc__\n            \n    async def margin_v1_get_lending_auto_invest_plan_id(self, **params):\n        return await self._request_margin_api(\"get\", \"lending/auto-invest/plan/id\", signed=True, data=params, version=1)\n        \n    margin_v1_get_lending_auto_invest_plan_id.__doc__ = Client.margin_v1_get_lending_auto_invest_plan_id.__doc__\n            \n    async def margin_v1_post_loan_adjust_ltv(self, **params):\n        return await self._request_margin_api(\"post\", \"loan/adjust/ltv\", signed=True, data=params, version=1)\n        \n    margin_v1_post_loan_adjust_ltv.__doc__ = Client.margin_v1_post_loan_adjust_ltv.__doc__\n            \n    async def margin_v1_get_mining_statistics_user_status(self, **params):\n        return await self._request_margin_api(\"get\", \"mining/statistics/user/status\", signed=True, data=params, version=1)\n        \n    margin_v1_get_mining_statistics_user_status.__doc__ = Client.margin_v1_get_mining_statistics_user_status.__doc__\n            \n    async def margin_v1_get_broker_transfer_futures(self, **params):\n        return await self._request_margin_api(\"get\", \"broker/transfer/futures\", signed=True, data=params, version=1)\n        \n    margin_v1_get_broker_transfer_futures.__doc__ = Client.margin_v1_get_broker_transfer_futures.__doc__\n            \n    async def margin_v1_post_algo_spot_new_order_twap(self, **params):\n        return await self._request_margin_api(\"post\", \"algo/spot/newOrderTwap\", signed=True, data=params, version=1)\n        \n    margin_v1_post_algo_spot_new_order_twap.__doc__ = Client.margin_v1_post_algo_spot_new_order_twap.__doc__\n            \n    async def margin_v1_get_lending_auto_invest_target_asset_list(self, **params):\n        return await self._request_margin_api(\"get\", \"lending/auto-invest/target-asset/list\", signed=True, data=params, version=1)\n        \n    margin_v1_get_lending_auto_invest_target_asset_list.__doc__ = Client.margin_v1_get_lending_auto_invest_target_asset_list.__doc__\n            \n    async def margin_v1_get_capital_deposit_address_list(self, **params):\n        return await self._request_margin_api(\"get\", \"capital/deposit/address/list\", signed=True, data=params, version=1)\n        \n    margin_v1_get_capital_deposit_address_list.__doc__ = Client.margin_v1_get_capital_deposit_address_list.__doc__\n            \n    async def margin_v1_post_broker_sub_account_bnb_burn_margin_interest(self, **params):\n        return await self._request_margin_api(\"post\", \"broker/subAccount/bnbBurn/marginInterest\", signed=True, data=params, version=1)\n        \n    margin_v1_post_broker_sub_account_bnb_burn_margin_interest.__doc__ = Client.margin_v1_post_broker_sub_account_bnb_burn_margin_interest.__doc__\n            \n    async def margin_v2_post_loan_flexible_repay(self, **params):\n        return await self._request_margin_api(\"post\", \"loan/flexible/repay\", signed=True, data=params, version=2)\n        \n    margin_v2_post_loan_flexible_repay.__doc__ = Client.margin_v2_post_loan_flexible_repay.__doc__\n            \n    async def margin_v2_get_loan_flexible_loanable_data(self, **params):\n        return await self._request_margin_api(\"get\", \"loan/flexible/loanable/data\", signed=True, data=params, version=2)\n        \n    margin_v2_get_loan_flexible_loanable_data.__doc__ = Client.margin_v2_get_loan_flexible_loanable_data.__doc__\n            \n    async def margin_v1_post_broker_sub_account_api_permission(self, **params):\n        return await self._request_margin_api(\"post\", \"broker/subAccountApi/permission\", signed=True, data=params, version=1)\n        \n    margin_v1_post_broker_sub_account_api_permission.__doc__ = Client.margin_v1_post_broker_sub_account_api_permission.__doc__\n            \n    async def margin_v1_post_broker_sub_account_api(self, **params):\n        return await self._request_margin_api(\"post\", \"broker/subAccountApi\", signed=True, data=params, version=1)\n        \n    margin_v1_post_broker_sub_account_api.__doc__ = Client.margin_v1_post_broker_sub_account_api.__doc__\n            \n    async def margin_v1_get_dci_product_positions(self, **params):\n        return await self._request_margin_api(\"get\", \"dci/product/positions\", signed=True, data=params, version=1)\n        \n    margin_v1_get_dci_product_positions.__doc__ = Client.margin_v1_get_dci_product_positions.__doc__\n            \n    async def margin_v1_post_convert_limit_cancel_order(self, **params):\n        return await self._request_margin_api(\"post\", \"convert/limit/cancelOrder\", signed=True, data=params, version=1)\n        \n    margin_v1_post_convert_limit_cancel_order.__doc__ = Client.margin_v1_post_convert_limit_cancel_order.__doc__\n            \n    async def v3_post_order_list_oto(self, **params):\n        return await self._request_api(\"post\", \"orderList/oto\", signed=True, data=params, version=\"v3\")\n        \n    v3_post_order_list_oto.__doc__ = Client.v3_post_order_list_oto.__doc__\n            \n    async def margin_v1_get_mining_hash_transfer_config_details_list(self, **params):\n        return await self._request_margin_api(\"get\", \"mining/hash-transfer/config/details/list\", signed=True, data=params, version=1)\n        \n    margin_v1_get_mining_hash_transfer_config_details_list.__doc__ = Client.margin_v1_get_mining_hash_transfer_config_details_list.__doc__\n            \n    async def margin_v1_get_mining_hash_transfer_profit_details(self, **params):\n        return await self._request_margin_api(\"get\", \"mining/hash-transfer/profit/details\", signed=True, data=params, version=1)\n        \n    margin_v1_get_mining_hash_transfer_profit_details.__doc__ = Client.margin_v1_get_mining_hash_transfer_profit_details.__doc__\n            \n    async def margin_v1_get_broker_sub_account(self, **params):\n        return await self._request_margin_api(\"get\", \"broker/subAccount\", signed=True, data=params, version=1)\n        \n    margin_v1_get_broker_sub_account.__doc__ = Client.margin_v1_get_broker_sub_account.__doc__\n            \n    async def margin_v1_get_portfolio_balance(self, **params):\n        return await self._request_margin_api(\"get\", \"portfolio/balance\", signed=True, data=params, version=1)\n        \n    margin_v1_get_portfolio_balance.__doc__ = Client.margin_v1_get_portfolio_balance.__doc__\n            \n    async def margin_v1_post_sub_account_eoptions_enable(self, **params):\n        return await self._request_margin_api(\"post\", \"sub-account/eoptions/enable\", signed=True, data=params, version=1)\n        \n    margin_v1_post_sub_account_eoptions_enable.__doc__ = Client.margin_v1_post_sub_account_eoptions_enable.__doc__\n            \n    async def papi_v1_post_ping(self, **params):\n        return await self._request_papi_api(\"post\", \"ping\", signed=True, data=params, version=1)\n        \n    papi_v1_post_ping.__doc__ = Client.papi_v1_post_ping.__doc__\n            \n    async def margin_v1_get_loan_loanable_data(self, **params):\n        return await self._request_margin_api(\"get\", \"loan/loanable/data\", signed=True, data=params, version=1)\n        \n    margin_v1_get_loan_loanable_data.__doc__ = Client.margin_v1_get_loan_loanable_data.__doc__\n            \n    async def margin_v1_post_eth_staking_wbeth_unwrap(self, **params):\n        return await self._request_margin_api(\"post\", \"eth-staking/wbeth/unwrap\", signed=True, data=params, version=1)\n        \n    margin_v1_post_eth_staking_wbeth_unwrap.__doc__ = Client.margin_v1_post_eth_staking_wbeth_unwrap.__doc__\n            \n    async def margin_v1_get_eth_staking_eth_history_staking_history(self, **params):\n        return await self._request_margin_api(\"get\", \"eth-staking/eth/history/stakingHistory\", signed=True, data=params, version=1)\n        \n    margin_v1_get_eth_staking_eth_history_staking_history.__doc__ = Client.margin_v1_get_eth_staking_eth_history_staking_history.__doc__\n            \n    async def margin_v1_get_staking_staking_record(self, **params):\n        return await self._request_margin_api(\"get\", \"staking/stakingRecord\", signed=True, data=params, version=1)\n        \n    margin_v1_get_staking_staking_record.__doc__ = Client.margin_v1_get_staking_staking_record.__doc__\n            \n    async def margin_v1_get_broker_rebate_recent_record(self, **params):\n        return await self._request_margin_api(\"get\", \"broker/rebate/recentRecord\", signed=True, data=params, version=1)\n        \n    margin_v1_get_broker_rebate_recent_record.__doc__ = Client.margin_v1_get_broker_rebate_recent_record.__doc__\n            \n    async def v3_delete_user_data_stream(self, **params):\n        return await self._request_api(\"delete\", \"userDataStream\", signed=True, data=params, version=\"v3\")\n        \n    async def v3_get_open_order_list(self, **params):\n        return await self._request_api(\"get\", \"openOrderList\", signed=True, data=params, version=\"v3\")\n        \n    async def margin_v1_get_loan_vip_collateral_account(self, **params):\n        return await self._request_margin_api(\"get\", \"loan/vip/collateral/account\", signed=True, data=params, version=1)\n        \n    margin_v1_get_loan_vip_collateral_account.__doc__ = Client.margin_v1_get_loan_vip_collateral_account.__doc__\n            \n    async def margin_v1_get_algo_spot_open_orders(self, **params):\n        return await self._request_margin_api(\"get\", \"algo/spot/openOrders\", signed=True, data=params, version=1)\n        \n    margin_v1_get_algo_spot_open_orders.__doc__ = Client.margin_v1_get_algo_spot_open_orders.__doc__\n            \n    async def margin_v1_post_loan_repay(self, **params):\n        return await self._request_margin_api(\"post\", \"loan/repay\", signed=True, data=params, version=1)\n        \n    margin_v1_post_loan_repay.__doc__ = Client.margin_v1_post_loan_repay.__doc__\n            \n    async def futures_coin_v1_get_funding_info(self, **params):\n        return await self._request_futures_coin_api(\"get\", \"fundingInfo\", signed=False, data=params, version=1)\n        \n    futures_coin_v1_get_funding_info.__doc__ = Client.futures_coin_v1_get_funding_info.__doc__\n            \n    async def margin_v1_get_margin_leverage_bracket(self, **params):\n        return await self._request_margin_api(\"get\", \"margin/leverageBracket\", signed=True, data=params, version=1)\n        \n    margin_v1_get_margin_leverage_bracket.__doc__ = Client.margin_v1_get_margin_leverage_bracket.__doc__\n            \n    async def margin_v2_get_portfolio_collateral_rate(self, **params):\n        return await self._request_margin_api(\"get\", \"portfolio/collateralRate\", signed=True, data=params, version=2)\n        \n    margin_v2_get_portfolio_collateral_rate.__doc__ = Client.margin_v2_get_portfolio_collateral_rate.__doc__\n            \n    async def margin_v2_post_loan_flexible_adjust_ltv(self, **params):\n        return await self._request_margin_api(\"post\", \"loan/flexible/adjust/ltv\", signed=True, data=params, version=2)\n        \n    margin_v2_post_loan_flexible_adjust_ltv.__doc__ = Client.margin_v2_post_loan_flexible_adjust_ltv.__doc__\n            \n    async def margin_v1_get_convert_order_status(self, **params):\n        return await self._request_margin_api(\"get\", \"convert/orderStatus\", signed=True, data=params, version=1)\n        \n    margin_v1_get_convert_order_status.__doc__ = Client.margin_v1_get_convert_order_status.__doc__\n            \n    async def margin_v1_get_broker_sub_account_api_ip_restriction(self, **params):\n        return await self._request_margin_api(\"get\", \"broker/subAccountApi/ipRestriction\", signed=True, data=params, version=1)\n        \n    margin_v1_get_broker_sub_account_api_ip_restriction.__doc__ = Client.margin_v1_get_broker_sub_account_api_ip_restriction.__doc__\n            \n    async def margin_v1_post_dci_product_subscribe(self, **params):\n        return await self._request_margin_api(\"post\", \"dci/product/subscribe\", signed=True, data=params, version=1)\n        \n    margin_v1_post_dci_product_subscribe.__doc__ = Client.margin_v1_post_dci_product_subscribe.__doc__\n            \n    async def futures_v1_get_income_asyn_id(self, **params):\n        return await self._request_futures_api(\"get\", \"income/asyn/id\", signed=True, data=params, version=1)\n        \n    futures_v1_get_income_asyn_id.__doc__ = Client.futures_v1_get_income_asyn_id.__doc__\n            \n    async def options_v1_post_countdown_cancel_all(self, **params):\n        return await self._request_options_api(\"post\", \"countdownCancelAll\", signed=True, data=params)\n        \n    options_v1_post_countdown_cancel_all.__doc__ = Client.options_v1_post_countdown_cancel_all.__doc__\n            \n    async def margin_v1_post_mining_hash_transfer_config_cancel(self, **params):\n        return await self._request_margin_api(\"post\", \"mining/hash-transfer/config/cancel\", signed=True, data=params, version=1)\n        \n    margin_v1_post_mining_hash_transfer_config_cancel.__doc__ = Client.margin_v1_post_mining_hash_transfer_config_cancel.__doc__\n            \n    async def margin_v1_get_broker_sub_account_deposit_hist(self, **params):\n        return await self._request_margin_api(\"get\", \"broker/subAccount/depositHist\", signed=True, data=params, version=1)\n        \n    margin_v1_get_broker_sub_account_deposit_hist.__doc__ = Client.margin_v1_get_broker_sub_account_deposit_hist.__doc__\n            \n    async def margin_v1_get_mining_payment_list(self, **params):\n        return await self._request_margin_api(\"get\", \"mining/payment/list\", signed=True, data=params, version=1)\n        \n    margin_v1_get_mining_payment_list.__doc__ = Client.margin_v1_get_mining_payment_list.__doc__\n            \n    async def futures_v1_get_pm_account_info(self, **params):\n        return await self._request_futures_api(\"get\", \"pmAccountInfo\", signed=True, data=params, version=1)\n        \n    futures_v1_get_pm_account_info.__doc__ = Client.futures_v1_get_pm_account_info.__doc__\n            \n    async def futures_coin_v1_get_adl_quantile(self, **params):\n        return await self._request_futures_coin_api(\"get\", \"adlQuantile\", signed=True, data=params, version=1)\n        \n    futures_coin_v1_get_adl_quantile.__doc__ = Client.futures_coin_v1_get_adl_quantile.__doc__\n            \n    async def options_v1_get_income_asyn_id(self, **params):\n        return await self._request_options_api(\"get\", \"income/asyn/id\", signed=True, data=params)\n        \n    options_v1_get_income_asyn_id.__doc__ = Client.options_v1_get_income_asyn_id.__doc__\n            \n    async def v3_post_cancel_replace(self, **params):\n        return await self._request_api(\"post\", \"cancelReplace\", signed=True, data=params, version=\"v3\")\n        \n    v3_post_cancel_replace.__doc__ = Client.v3_post_cancel_replace.__doc__\n            \n    async def v3_post_order_test(self, **params):\n        return await self._request_api(\"post\", \"order/test\", signed=True, data=params, version=\"v3\")\n        \n    async def margin_v1_post_account_enable_fast_withdraw_switch(self, **params):\n        return await self._request_margin_api(\"post\", \"account/enableFastWithdrawSwitch\", signed=True, data=params, version=1)\n        \n    margin_v1_post_account_enable_fast_withdraw_switch.__doc__ = Client.margin_v1_post_account_enable_fast_withdraw_switch.__doc__\n            \n    async def margin_v1_post_broker_transfer_futures(self, **params):\n        return await self._request_margin_api(\"post\", \"broker/transfer/futures\", signed=True, data=params, version=1)\n        \n    margin_v1_post_broker_transfer_futures.__doc__ = Client.margin_v1_post_broker_transfer_futures.__doc__\n            \n    async def margin_v1_get_margin_isolated_transfer(self, **params):\n        return await self._request_margin_api(\"get\", \"margin/isolated/transfer\", signed=True, data=params, version=1)\n        \n    async def v3_post_order_cancel_replace(self, **params):\n        return await self._request_api(\"post\", \"order/cancelReplace\", signed=True, data=params, version=\"v3\")\n        \n    async def margin_v1_post_sol_staking_sol_stake(self, **params):\n        return await self._request_margin_api(\"post\", \"sol-staking/sol/stake\", signed=True, data=params, version=1)\n        \n    margin_v1_post_sol_staking_sol_stake.__doc__ = Client.margin_v1_post_sol_staking_sol_stake.__doc__\n            \n    async def margin_v1_post_loan_borrow(self, **params):\n        return await self._request_margin_api(\"post\", \"loan/borrow\", signed=True, data=params, version=1)\n        \n    margin_v1_post_loan_borrow.__doc__ = Client.margin_v1_post_loan_borrow.__doc__\n            \n    async def margin_v1_get_managed_subaccount_info(self, **params):\n        return await self._request_margin_api(\"get\", \"managed-subaccount/info\", signed=True, data=params, version=1)\n        \n    margin_v1_get_managed_subaccount_info.__doc__ = Client.margin_v1_get_managed_subaccount_info.__doc__\n            \n    async def margin_v1_post_lending_auto_invest_plan_edit_status(self, **params):\n        return await self._request_margin_api(\"post\", \"lending/auto-invest/plan/edit-status\", signed=True, data=params, version=1)\n        \n    margin_v1_post_lending_auto_invest_plan_edit_status.__doc__ = Client.margin_v1_post_lending_auto_invest_plan_edit_status.__doc__\n            \n    async def margin_v1_get_sol_staking_sol_history_unclaimed_rewards(self, **params):\n        return await self._request_margin_api(\"get\", \"sol-staking/sol/history/unclaimedRewards\", signed=True, data=params, version=1)\n        \n    margin_v1_get_sol_staking_sol_history_unclaimed_rewards.__doc__ = Client.margin_v1_get_sol_staking_sol_history_unclaimed_rewards.__doc__\n            \n    async def margin_v1_post_asset_convert_transfer_query_by_page(self, **params):\n        return await self._request_margin_api(\"post\", \"asset/convert-transfer/queryByPage\", signed=True, data=params, version=1)\n        \n    margin_v1_post_asset_convert_transfer_query_by_page.__doc__ = Client.margin_v1_post_asset_convert_transfer_query_by_page.__doc__\n            \n    async def margin_v1_get_sol_staking_sol_history_boost_rewards_history(self, **params):\n        return await self._request_margin_api(\"get\", \"sol-staking/sol/history/boostRewardsHistory\", signed=True, data=params, version=1)\n        \n    margin_v1_get_sol_staking_sol_history_boost_rewards_history.__doc__ = Client.margin_v1_get_sol_staking_sol_history_boost_rewards_history.__doc__\n            \n    async def margin_v1_get_lending_auto_invest_one_off_status(self, **params):\n        return await self._request_margin_api(\"get\", \"lending/auto-invest/one-off/status\", signed=True, data=params, version=1)\n        \n    margin_v1_get_lending_auto_invest_one_off_status.__doc__ = Client.margin_v1_get_lending_auto_invest_one_off_status.__doc__\n            \n    async def margin_v1_post_broker_sub_account(self, **params):\n        return await self._request_margin_api(\"post\", \"broker/subAccount\", signed=True, data=params, version=1)\n        \n    margin_v1_post_broker_sub_account.__doc__ = Client.margin_v1_post_broker_sub_account.__doc__\n            \n    async def margin_v1_get_asset_ledger_transfer_cloud_mining_query_by_page(self, **params):\n        return await self._request_margin_api(\"get\", \"asset/ledger-transfer/cloud-mining/queryByPage\", signed=True, data=params, version=1)\n        \n    margin_v1_get_asset_ledger_transfer_cloud_mining_query_by_page.__doc__ = Client.margin_v1_get_asset_ledger_transfer_cloud_mining_query_by_page.__doc__\n            \n    async def margin_v1_get_mining_pub_coin_list(self, **params):\n        return await self._request_margin_api(\"get\", \"mining/pub/coinList\", signed=True, data=params, version=1)\n        \n    margin_v1_get_mining_pub_coin_list.__doc__ = Client.margin_v1_get_mining_pub_coin_list.__doc__\n            \n    async def margin_v2_get_loan_flexible_repay_history(self, **params):\n        return await self._request_margin_api(\"get\", \"loan/flexible/repay/history\", signed=True, data=params, version=2)\n        \n    margin_v2_get_loan_flexible_repay_history.__doc__ = Client.margin_v2_get_loan_flexible_repay_history.__doc__\n            \n    async def v3_post_sor_order(self, **params):\n        return await self._request_api(\"post\", \"sor/order\", signed=True, data=params, version=\"v3\")\n        \n    v3_post_sor_order.__doc__ = Client.v3_post_sor_order.__doc__\n            \n    async def margin_v1_post_capital_deposit_credit_apply(self, **params):\n        return await self._request_margin_api(\"post\", \"capital/deposit/credit-apply\", signed=True, data=params, version=1)\n        \n    margin_v1_post_capital_deposit_credit_apply.__doc__ = Client.margin_v1_post_capital_deposit_credit_apply.__doc__\n            \n    async def futures_v1_put_batch_order(self, **params):\n        return await self._request_futures_api(\"put\", \"batchOrder\", signed=True, data=params, version=1)\n        \n    futures_v1_put_batch_order.__doc__ = Client.futures_v1_put_batch_order.__doc__\n            \n    async def v3_get_my_prevented_matches(self, **params):\n        return await self._request_api(\"get\", \"myPreventedMatches\", signed=True, data=params, version=\"v3\")\n        \n    async def margin_v1_get_mining_statistics_user_list(self, **params):\n        return await self._request_margin_api(\"get\", \"mining/statistics/user/list\", signed=True, data=params, version=1)\n        \n    margin_v1_get_mining_statistics_user_list.__doc__ = Client.margin_v1_get_mining_statistics_user_list.__doc__\n            \n    async def futures_v1_post_batch_order(self, **params):\n        return await self._request_futures_api(\"post\", \"batchOrder\", signed=True, data=params, version=1)\n        \n    futures_v1_post_batch_order.__doc__ = Client.futures_v1_post_batch_order.__doc__\n            \n    async def v3_get_ticker_trading_day(self, **params):\n        return await self._request_api(\"get\", \"ticker/tradingDay\", signed=False, data=params, version=\"v3\")\n        \n    v3_get_ticker_trading_day.__doc__ = Client.v3_get_ticker_trading_day.__doc__\n            \n    async def margin_v1_get_mining_worker_detail(self, **params):\n        return await self._request_margin_api(\"get\", \"mining/worker/detail\", signed=True, data=params, version=1)\n        \n    margin_v1_get_mining_worker_detail.__doc__ = Client.margin_v1_get_mining_worker_detail.__doc__\n            \n    async def margin_v1_get_managed_subaccount_fetch_future_asset(self, **params):\n        return await self._request_margin_api(\"get\", \"managed-subaccount/fetch-future-asset\", signed=True, data=params, version=1)\n        \n    margin_v1_get_managed_subaccount_fetch_future_asset.__doc__ = Client.margin_v1_get_managed_subaccount_fetch_future_asset.__doc__\n            \n    async def margin_v1_get_margin_rate_limit_order(self, **params):\n        return await self._request_margin_api(\"get\", \"margin/rateLimit/order\", signed=True, data=params, version=1)\n        \n    margin_v1_get_margin_rate_limit_order.__doc__ = Client.margin_v1_get_margin_rate_limit_order.__doc__\n            \n    async def margin_v1_get_localentity_vasp(self, **params):\n        return await self._request_margin_api(\"get\", \"localentity/vasp\", signed=True, data=params, version=1)\n        \n    margin_v1_get_localentity_vasp.__doc__ = Client.margin_v1_get_localentity_vasp.__doc__\n            \n    async def margin_v1_get_sol_staking_sol_history_rate_history(self, **params):\n        return await self._request_margin_api(\"get\", \"sol-staking/sol/history/rateHistory\", signed=True, data=params, version=1)\n        \n    margin_v1_get_sol_staking_sol_history_rate_history.__doc__ = Client.margin_v1_get_sol_staking_sol_history_rate_history.__doc__\n            \n    async def margin_v1_post_broker_sub_account_api_ip_restriction(self, **params):\n        return await self._request_margin_api(\"post\", \"broker/subAccountApi/ipRestriction\", signed=True, data=params, version=1)\n        \n    margin_v1_post_broker_sub_account_api_ip_restriction.__doc__ = Client.margin_v1_post_broker_sub_account_api_ip_restriction.__doc__\n            \n    async def margin_v1_get_broker_transfer(self, **params):\n        return await self._request_margin_api(\"get\", \"broker/transfer\", signed=True, data=params, version=1)\n        \n    margin_v1_get_broker_transfer.__doc__ = Client.margin_v1_get_broker_transfer.__doc__\n            \n    async def margin_v1_get_sol_staking_account(self, **params):\n        return await self._request_margin_api(\"get\", \"sol-staking/account\", signed=True, data=params, version=1)\n        \n    margin_v1_get_sol_staking_account.__doc__ = Client.margin_v1_get_sol_staking_account.__doc__\n            \n    async def margin_v1_get_account_info(self, **params):\n        return await self._request_margin_api(\"get\", \"account/info\", signed=True, data=params, version=1)\n        \n    margin_v1_get_account_info.__doc__ = Client.margin_v1_get_account_info.__doc__\n            \n    async def margin_v1_post_portfolio_repay_futures_switch(self, **params):\n        return await self._request_margin_api(\"post\", \"portfolio/repay-futures-switch\", signed=True, data=params, version=1)\n        \n    margin_v1_post_portfolio_repay_futures_switch.__doc__ = Client.margin_v1_post_portfolio_repay_futures_switch.__doc__\n            \n    async def margin_v1_post_loan_vip_borrow(self, **params):\n        return await self._request_margin_api(\"post\", \"loan/vip/borrow\", signed=True, data=params, version=1)\n        \n    margin_v1_post_loan_vip_borrow.__doc__ = Client.margin_v1_post_loan_vip_borrow.__doc__\n            \n    async def margin_v2_get_loan_flexible_ltv_adjustment_history(self, **params):\n        return await self._request_margin_api(\"get\", \"loan/flexible/ltv/adjustment/history\", signed=True, data=params, version=2)\n        \n    margin_v2_get_loan_flexible_ltv_adjustment_history.__doc__ = Client.margin_v2_get_loan_flexible_ltv_adjustment_history.__doc__\n            \n    async def options_v1_delete_all_open_orders_by_underlying(self, **params):\n        return await self._request_options_api(\"delete\", \"allOpenOrdersByUnderlying\", signed=True, data=params)\n        \n    options_v1_delete_all_open_orders_by_underlying.__doc__ = Client.options_v1_delete_all_open_orders_by_underlying.__doc__\n            \n    async def margin_v1_get_broker_sub_account_futures_summary(self, **params):\n        return await self._request_margin_api(\"get\", \"broker/subAccount/futuresSummary\", signed=True, data=params, version=1)\n        \n    margin_v1_get_broker_sub_account_futures_summary.__doc__ = Client.margin_v1_get_broker_sub_account_futures_summary.__doc__\n            \n    async def margin_v1_get_broker_sub_account_spot_summary(self, **params):\n        return await self._request_margin_api(\"get\", \"broker/subAccount/spotSummary\", signed=True, data=params, version=1)\n        \n    margin_v1_get_broker_sub_account_spot_summary.__doc__ = Client.margin_v1_get_broker_sub_account_spot_summary.__doc__\n            \n    async def margin_v1_post_sub_account_blvt_enable(self, **params):\n        return await self._request_margin_api(\"post\", \"sub-account/blvt/enable\", signed=True, data=params, version=1)\n        \n    margin_v1_post_sub_account_blvt_enable.__doc__ = Client.margin_v1_post_sub_account_blvt_enable.__doc__\n            \n    async def margin_v1_get_algo_spot_historical_orders(self, **params):\n        return await self._request_margin_api(\"get\", \"algo/spot/historicalOrders\", signed=True, data=params, version=1)\n        \n    margin_v1_get_algo_spot_historical_orders.__doc__ = Client.margin_v1_get_algo_spot_historical_orders.__doc__\n            \n    async def margin_v1_get_loan_vip_repay_history(self, **params):\n        return await self._request_margin_api(\"get\", \"loan/vip/repay/history\", signed=True, data=params, version=1)\n        \n    margin_v1_get_loan_vip_repay_history.__doc__ = Client.margin_v1_get_loan_vip_repay_history.__doc__\n            \n    async def margin_v1_get_loan_borrow_history(self, **params):\n        return await self._request_margin_api(\"get\", \"loan/borrow/history\", signed=True, data=params, version=1)\n        \n    margin_v1_get_loan_borrow_history.__doc__ = Client.margin_v1_get_loan_borrow_history.__doc__\n            \n    async def margin_v1_post_lending_auto_invest_redeem(self, **params):\n        return await self._request_margin_api(\"post\", \"lending/auto-invest/redeem\", signed=True, data=params, version=1)\n        \n    margin_v1_post_lending_auto_invest_redeem.__doc__ = Client.margin_v1_post_lending_auto_invest_redeem.__doc__\n            \n    async def v3_get_account(self, **params):\n        return await self._request_api(\"get\", \"account\", signed=True, data=params, version=\"v3\")\n        \n    async def v3_delete_order(self, **params):\n        return await self._request_api(\"delete\", \"order\", signed=True, data=params, version=\"v3\")\n        \n    async def futures_coin_v1_get_income_asyn(self, **params):\n        return await self._request_futures_coin_api(\"get\", \"income/asyn\", signed=True, data=params, version=1)\n        \n    futures_coin_v1_get_income_asyn.__doc__ = Client.futures_coin_v1_get_income_asyn.__doc__\n            \n    async def margin_v1_post_managed_subaccount_deposit(self, **params):\n        return await self._request_margin_api(\"post\", \"managed-subaccount/deposit\", signed=True, data=params, version=1)\n        \n    margin_v1_post_managed_subaccount_deposit.__doc__ = Client.margin_v1_post_managed_subaccount_deposit.__doc__\n            \n    async def margin_v1_post_lending_daily_purchase(self, **params):\n        return await self._request_margin_api(\"post\", \"lending/daily/purchase\", signed=True, data=params, version=1)\n        \n    margin_v1_post_lending_daily_purchase.__doc__ = Client.margin_v1_post_lending_daily_purchase.__doc__\n            \n    async def futures_v1_get_trade_asyn_id(self, **params):\n        return await self._request_futures_api(\"get\", \"trade/asyn/id\", signed=True, data=params, version=1)\n        \n    futures_v1_get_trade_asyn_id.__doc__ = Client.futures_v1_get_trade_asyn_id.__doc__\n            \n    async def margin_v1_delete_sub_account_sub_account_api_ip_restriction_ip_list(self, **params):\n        return await self._request_margin_api(\"delete\", \"sub-account/subAccountApi/ipRestriction/ipList\", signed=True, data=params, version=1)\n        \n    margin_v1_delete_sub_account_sub_account_api_ip_restriction_ip_list.__doc__ = Client.margin_v1_delete_sub_account_sub_account_api_ip_restriction_ip_list.__doc__\n            \n    async def margin_v1_get_copy_trading_futures_user_status(self, **params):\n        return await self._request_margin_api(\"get\", \"copyTrading/futures/userStatus\", signed=True, data=params, version=1)\n        \n    margin_v1_get_copy_trading_futures_user_status.__doc__ = Client.margin_v1_get_copy_trading_futures_user_status.__doc__\n            \n    async def options_v1_get_margin_account(self, **params):\n        return await self._request_options_api(\"get\", \"marginAccount\", signed=True, data=params)\n        \n    options_v1_get_margin_account.__doc__ = Client.options_v1_get_margin_account.__doc__\n            \n    async def margin_v1_post_localentity_withdraw_apply(self, **params):\n        return await self._request_margin_api(\"post\", \"localentity/withdraw/apply\", signed=True, data=params, version=1)\n        \n    margin_v1_post_localentity_withdraw_apply.__doc__ = Client.margin_v1_post_localentity_withdraw_apply.__doc__\n            \n    async def v3_put_user_data_stream(self, **params):\n        return await self._request_api(\"put\", \"userDataStream\", signed=True, data=params, version=\"v3\")\n        \n    async def margin_v1_get_asset_wallet_balance(self, **params):\n        return await self._request_margin_api(\"get\", \"asset/wallet/balance\", signed=True, data=params, version=1)\n        \n    margin_v1_get_asset_wallet_balance.__doc__ = Client.margin_v1_get_asset_wallet_balance.__doc__\n            \n    async def margin_v1_post_broker_transfer(self, **params):\n        return await self._request_margin_api(\"post\", \"broker/transfer\", signed=True, data=params, version=1)\n        \n    margin_v1_post_broker_transfer.__doc__ = Client.margin_v1_post_broker_transfer.__doc__\n            \n    async def margin_v1_post_lending_customized_fixed_purchase(self, **params):\n        return await self._request_margin_api(\"post\", \"lending/customizedFixed/purchase\", signed=True, data=params, version=1)\n        \n    margin_v1_post_lending_customized_fixed_purchase.__doc__ = Client.margin_v1_post_lending_customized_fixed_purchase.__doc__\n            \n    async def margin_v1_post_algo_futures_new_order_twap(self, **params):\n        return await self._request_margin_api(\"post\", \"algo/futures/newOrderTwap\", signed=True, data=params, version=1)\n        \n    margin_v1_post_algo_futures_new_order_twap.__doc__ = Client.margin_v1_post_algo_futures_new_order_twap.__doc__\n            \n    async def margin_v2_post_eth_staking_eth_stake(self, **params):\n        return await self._request_margin_api(\"post\", \"eth-staking/eth/stake\", signed=True, data=params, version=2)\n        \n    margin_v2_post_eth_staking_eth_stake.__doc__ = Client.margin_v2_post_eth_staking_eth_stake.__doc__\n            \n    async def margin_v1_post_loan_flexible_repay_history(self, **params):\n        return await self._request_margin_api(\"post\", \"loan/flexible/repay/history\", signed=True, data=params, version=1)\n        \n    margin_v1_post_loan_flexible_repay_history.__doc__ = Client.margin_v1_post_loan_flexible_repay_history.__doc__\n            \n    async def v3_post_user_data_stream(self, **params):\n        return await self._request_api(\"post\", \"userDataStream\", signed=True, data=params, version=\"v3\")\n        \n    async def margin_v1_get_lending_auto_invest_index_info(self, **params):\n        return await self._request_margin_api(\"get\", \"lending/auto-invest/index/info\", signed=True, data=params, version=1)\n        \n    margin_v1_get_lending_auto_invest_index_info.__doc__ = Client.margin_v1_get_lending_auto_invest_index_info.__doc__\n            \n    async def margin_v1_get_sol_staking_sol_history_redemption_history(self, **params):\n        return await self._request_margin_api(\"get\", \"sol-staking/sol/history/redemptionHistory\", signed=True, data=params, version=1)\n        \n    margin_v1_get_sol_staking_sol_history_redemption_history.__doc__ = Client.margin_v1_get_sol_staking_sol_history_redemption_history.__doc__\n            \n    async def margin_v1_get_broker_rebate_futures_recent_record(self, **params):\n        return await self._request_margin_api(\"get\", \"broker/rebate/futures/recentRecord\", signed=True, data=params, version=1)\n        \n    margin_v1_get_broker_rebate_futures_recent_record.__doc__ = Client.margin_v1_get_broker_rebate_futures_recent_record.__doc__\n            \n    async def margin_v3_get_broker_sub_account_futures_summary(self, **params):\n        return await self._request_margin_api(\"get\", \"broker/subAccount/futuresSummary\", signed=True, data=params, version=3)\n        \n    margin_v3_get_broker_sub_account_futures_summary.__doc__ = Client.margin_v3_get_broker_sub_account_futures_summary.__doc__\n            \n    async def margin_v1_post_margin_manual_liquidation(self, **params):\n        return await self._request_margin_api(\"post\", \"margin/manual-liquidation\", signed=True, data=params, version=1)\n        \n    async def margin_v1_get_lending_auto_invest_target_asset_roi_list(self, **params):\n        return await self._request_margin_api(\"get\", \"lending/auto-invest/target-asset/roi/list\", signed=True, data=params, version=1)\n        \n    margin_v1_get_lending_auto_invest_target_asset_roi_list.__doc__ = Client.margin_v1_get_lending_auto_invest_target_asset_roi_list.__doc__\n            \n    async def margin_v1_get_broker_universal_transfer(self, **params):\n        return await self._request_margin_api(\"get\", \"broker/universalTransfer\", signed=True, data=params, version=1)\n        \n    margin_v1_get_broker_universal_transfer.__doc__ = Client.margin_v1_get_broker_universal_transfer.__doc__\n            \n    async def futures_v1_put_batch_orders(self, **params):\n        return await self._request_futures_api(\"put\", \"batchOrders\", signed=True, data=params, version=1)\n        \n    futures_v1_put_batch_orders.__doc__ = Client.futures_v1_put_batch_orders.__doc__\n            \n    async def options_v1_post_countdown_cancel_all_heart_beat(self, **params):\n        return await self._request_options_api(\"post\", \"countdownCancelAllHeartBeat\", signed=True, data=params)\n        \n    options_v1_post_countdown_cancel_all_heart_beat.__doc__ = Client.options_v1_post_countdown_cancel_all_heart_beat.__doc__\n            \n    async def margin_v1_get_loan_collateral_data(self, **params):\n        return await self._request_margin_api(\"get\", \"loan/collateral/data\", signed=True, data=params, version=1)\n        \n    margin_v1_get_loan_collateral_data.__doc__ = Client.margin_v1_get_loan_collateral_data.__doc__\n            \n    async def margin_v1_get_loan_repay_history(self, **params):\n        return await self._request_margin_api(\"get\", \"loan/repay/history\", signed=True, data=params, version=1)\n        \n    margin_v1_get_loan_repay_history.__doc__ = Client.margin_v1_get_loan_repay_history.__doc__\n            \n    async def margin_v1_post_convert_limit_place_order(self, **params):\n        return await self._request_margin_api(\"post\", \"convert/limit/placeOrder\", signed=True, data=params, version=1)\n        \n    margin_v1_post_convert_limit_place_order.__doc__ = Client.margin_v1_post_convert_limit_place_order.__doc__\n            \n    async def futures_v1_get_convert_exchange_info(self, **params):\n        return await self._request_futures_api(\"get\", \"convert/exchangeInfo\", signed=False, data=params, version=1)\n        \n    futures_v1_get_convert_exchange_info.__doc__ = Client.futures_v1_get_convert_exchange_info.__doc__\n            \n    async def v3_get_all_order_list(self, **params):\n        return await self._request_api(\"get\", \"allOrderList\", signed=True, data=params, version=\"v3\")\n        \n    v3_get_all_order_list.__doc__ = Client.v3_get_all_order_list.__doc__\n            \n    async def margin_v1_delete_broker_sub_account_api_ip_restriction_ip_list(self, **params):\n        return await self._request_margin_api(\"delete\", \"broker/subAccountApi/ipRestriction/ipList\", signed=True, data=params, version=1)\n        \n    margin_v1_delete_broker_sub_account_api_ip_restriction_ip_list.__doc__ = Client.margin_v1_delete_broker_sub_account_api_ip_restriction_ip_list.__doc__\n            \n    async def margin_v1_post_sub_account_virtual_sub_account(self, **params):\n        return await self._request_margin_api(\"post\", \"sub-account/virtualSubAccount\", signed=True, data=params, version=1)\n        \n    margin_v1_post_sub_account_virtual_sub_account.__doc__ = Client.margin_v1_post_sub_account_virtual_sub_account.__doc__\n            \n    async def margin_v1_put_localentity_deposit_provide_info(self, **params):\n        return await self._request_margin_api(\"put\", \"localentity/deposit/provide-info\", signed=True, data=params, version=1)\n        \n    margin_v1_put_localentity_deposit_provide_info.__doc__ = Client.margin_v1_put_localentity_deposit_provide_info.__doc__\n            \n    async def margin_v1_post_portfolio_mint(self, **params):\n        return await self._request_margin_api(\"post\", \"portfolio/mint\", signed=True, data=params, version=1)\n        \n    margin_v1_post_portfolio_mint.__doc__ = Client.margin_v1_post_portfolio_mint.__doc__\n            \n    async def futures_v1_get_order_amendment(self, **params):\n        return await self._request_futures_api(\"get\", \"orderAmendment\", signed=True, data=params, version=1)\n        \n    futures_v1_get_order_amendment.__doc__ = Client.futures_v1_get_order_amendment.__doc__\n            \n    async def margin_v1_post_sol_staking_sol_claim(self, **params):\n        return await self._request_margin_api(\"post\", \"sol-staking/sol/claim\", signed=True, data=params, version=1)\n        \n    margin_v1_post_sol_staking_sol_claim.__doc__ = Client.margin_v1_post_sol_staking_sol_claim.__doc__\n            \n    async def margin_v1_post_lending_daily_redeem(self, **params):\n        return await self._request_margin_api(\"post\", \"lending/daily/redeem\", signed=True, data=params, version=1)\n        \n    margin_v1_post_lending_daily_redeem.__doc__ = Client.margin_v1_post_lending_daily_redeem.__doc__\n            \n    async def margin_v1_post_mining_hash_transfer_config(self, **params):\n        return await self._request_margin_api(\"post\", \"mining/hash-transfer/config\", signed=True, data=params, version=1)\n        \n    margin_v1_post_mining_hash_transfer_config.__doc__ = Client.margin_v1_post_mining_hash_transfer_config.__doc__\n            \n    async def margin_v1_get_lending_auto_invest_rebalance_history(self, **params):\n        return await self._request_margin_api(\"get\", \"lending/auto-invest/rebalance/history\", signed=True, data=params, version=1)\n        \n    margin_v1_get_lending_auto_invest_rebalance_history.__doc__ = Client.margin_v1_get_lending_auto_invest_rebalance_history.__doc__\n            \n    async def margin_v1_get_loan_repay_collateral_rate(self, **params):\n        return await self._request_margin_api(\"get\", \"loan/repay/collateral/rate\", signed=True, data=params, version=1)\n        \n    margin_v1_get_loan_repay_collateral_rate.__doc__ = Client.margin_v1_get_loan_repay_collateral_rate.__doc__\n            \n    async def futures_v1_get_income_asyn(self, **params):\n        return await self._request_futures_api(\"get\", \"income/asyn\", signed=True, data=params, version=1)\n        \n    futures_v1_get_income_asyn.__doc__ = Client.futures_v1_get_income_asyn.__doc__\n            \n    async def margin_v1_get_mining_payment_uid(self, **params):\n        return await self._request_margin_api(\"get\", \"mining/payment/uid\", signed=True, data=params, version=1)\n        \n    margin_v1_get_mining_payment_uid.__doc__ = Client.margin_v1_get_mining_payment_uid.__doc__\n            \n    async def margin_v2_get_loan_flexible_borrow_history(self, **params):\n        return await self._request_margin_api(\"get\", \"loan/flexible/borrow/history\", signed=True, data=params, version=2)\n        \n    margin_v2_get_loan_flexible_borrow_history.__doc__ = Client.margin_v2_get_loan_flexible_borrow_history.__doc__\n            \n    async def v3_get_order(self, **params):\n        return await self._request_api(\"get\", \"order\", signed=True, data=params, version=\"v3\")\n        \n    async def margin_v1_get_capital_contract_convertible_coins(self, **params):\n        return await self._request_margin_api(\"get\", \"capital/contract/convertible-coins\", signed=True, data=params, version=1)\n        \n    margin_v1_get_capital_contract_convertible_coins.__doc__ = Client.margin_v1_get_capital_contract_convertible_coins.__doc__\n            \n    async def margin_v1_post_broker_sub_account_api_permission_vanilla_options(self, **params):\n        return await self._request_margin_api(\"post\", \"broker/subAccountApi/permission/vanillaOptions\", signed=True, data=params, version=1)\n        \n    margin_v1_post_broker_sub_account_api_permission_vanilla_options.__doc__ = Client.margin_v1_post_broker_sub_account_api_permission_vanilla_options.__doc__\n            \n    async def margin_v1_get_lending_auto_invest_redeem_history(self, **params):\n        return await self._request_margin_api(\"get\", \"lending/auto-invest/redeem/history\", signed=True, data=params, version=1)\n        \n    margin_v1_get_lending_auto_invest_redeem_history.__doc__ = Client.margin_v1_get_lending_auto_invest_redeem_history.__doc__\n            \n    async def margin_v2_get_localentity_withdraw_history(self, **params):\n        return await self._request_margin_api(\"get\", \"localentity/withdraw/history\", signed=True, data=params, version=2)\n        \n    margin_v2_get_localentity_withdraw_history.__doc__ = Client.margin_v2_get_localentity_withdraw_history.__doc__\n            \n    async def margin_v1_get_eth_staking_eth_history_redemption_history(self, **params):\n        return await self._request_margin_api(\"get\", \"eth-staking/eth/history/redemptionHistory\", signed=True, data=params, version=1)\n        \n    margin_v1_get_eth_staking_eth_history_redemption_history.__doc__ = Client.margin_v1_get_eth_staking_eth_history_redemption_history.__doc__\n            \n    async def futures_v1_get_fee_burn(self, **params):\n        return await self._request_futures_api(\"get\", \"feeBurn\", signed=True, data=params, version=1)\n        \n    futures_v1_get_fee_burn.__doc__ = Client.futures_v1_get_fee_burn.__doc__\n            \n    async def margin_v1_get_lending_auto_invest_index_user_summary(self, **params):\n        return await self._request_margin_api(\"get\", \"lending/auto-invest/index/user-summary\", signed=True, data=params, version=1)\n        \n    margin_v1_get_lending_auto_invest_index_user_summary.__doc__ = Client.margin_v1_get_lending_auto_invest_index_user_summary.__doc__\n            \n    async def margin_v2_post_loan_flexible_borrow(self, **params):\n        return await self._request_margin_api(\"post\", \"loan/flexible/borrow\", signed=True, data=params, version=2)\n        \n    margin_v2_post_loan_flexible_borrow.__doc__ = Client.margin_v2_post_loan_flexible_borrow.__doc__\n            \n    async def margin_v1_post_loan_vip_repay(self, **params):\n        return await self._request_margin_api(\"post\", \"loan/vip/repay\", signed=True, data=params, version=1)\n        \n    margin_v1_post_loan_vip_repay.__doc__ = Client.margin_v1_post_loan_vip_repay.__doc__\n            \n    async def futures_coin_v1_get_commission_rate(self, **params):\n        return await self._request_futures_coin_api(\"get\", \"commissionRate\", signed=True, data=params, version=1)\n        \n    futures_coin_v1_get_commission_rate.__doc__ = Client.futures_coin_v1_get_commission_rate.__doc__\n            \n    async def margin_v1_get_convert_asset_info(self, **params):\n        return await self._request_margin_api(\"get\", \"convert/assetInfo\", signed=True, data=params, version=1)\n        \n    margin_v1_get_convert_asset_info.__doc__ = Client.margin_v1_get_convert_asset_info.__doc__\n            \n    async def v3_post_sor_order_test(self, **params):\n        return await self._request_api(\"post\", \"sor/order/test\", signed=True, data=params, version=\"v3\")\n        \n    v3_post_sor_order_test.__doc__ = Client.v3_post_sor_order_test.__doc__\n            \n    async def margin_v1_post_broker_universal_transfer(self, **params):\n        return await self._request_margin_api(\"post\", \"broker/universalTransfer\", signed=True, data=params, version=1)\n        \n    margin_v1_post_broker_universal_transfer.__doc__ = Client.margin_v1_post_broker_universal_transfer.__doc__\n            \n    async def margin_v1_post_account_disable_fast_withdraw_switch(self, **params):\n        return await self._request_margin_api(\"post\", \"account/disableFastWithdrawSwitch\", signed=True, data=params, version=1)\n        \n    margin_v1_post_account_disable_fast_withdraw_switch.__doc__ = Client.margin_v1_post_account_disable_fast_withdraw_switch.__doc__\n            \n    async def futures_v1_get_asset_index(self, **params):\n        return await self._request_futures_api(\"get\", \"assetIndex\", signed=False, data=params, version=1)\n        \n    futures_v1_get_asset_index.__doc__ = Client.futures_v1_get_asset_index.__doc__\n            \n    async def v3_get_rate_limit_order(self, **params):\n        return await self._request_api(\"get\", \"rateLimit/order\", signed=True, data=params, version=\"v3\")\n        \n    async def margin_v1_get_account_api_restrictions_ip_restriction(self, **params):\n        return await self._request_margin_api(\"get\", \"account/apiRestrictions/ipRestriction\", signed=True, data=params, version=1)\n        \n    margin_v1_get_account_api_restrictions_ip_restriction.__doc__ = Client.margin_v1_get_account_api_restrictions_ip_restriction.__doc__\n            \n    async def margin_v1_post_broker_sub_account_bnb_burn_spot(self, **params):\n        return await self._request_margin_api(\"post\", \"broker/subAccount/bnbBurn/spot\", signed=True, data=params, version=1)\n        \n    margin_v1_post_broker_sub_account_bnb_burn_spot.__doc__ = Client.margin_v1_post_broker_sub_account_bnb_burn_spot.__doc__\n            \n    async def futures_coin_v1_put_batch_orders(self, **params):\n        return await self._request_futures_coin_api(\"put\", \"batchOrders\", signed=True, data=params, version=1)\n        \n    futures_coin_v1_put_batch_orders.__doc__ = Client.futures_coin_v1_put_batch_orders.__doc__\n            \n    async def v3_delete_open_orders(self, **params):\n        return await self._request_api(\"delete\", \"openOrders\", signed=True, data=params, version=\"v3\")\n        \n    async def margin_v1_post_broker_sub_account_api_permission_universal_transfer(self, **params):\n        return await self._request_margin_api(\"post\", \"broker/subAccountApi/permission/universalTransfer\", signed=True, data=params, version=1)\n        \n    margin_v1_post_broker_sub_account_api_permission_universal_transfer.__doc__ = Client.margin_v1_post_broker_sub_account_api_permission_universal_transfer.__doc__\n            \n    async def v3_get_my_allocations(self, **params):\n        return await self._request_api(\"get\", \"myAllocations\", signed=True, data=params, version=\"v3\")\n        \n    async def margin_v1_get_loan_ltv_adjustment_history(self, **params):\n        return await self._request_margin_api(\"get\", \"loan/ltv/adjustment/history\", signed=True, data=params, version=1)\n        \n    margin_v1_get_loan_ltv_adjustment_history.__doc__ = Client.margin_v1_get_loan_ltv_adjustment_history.__doc__\n            \n    async def margin_v1_get_localentity_withdraw_history(self, **params):\n        return await self._request_margin_api(\"get\", \"localentity/withdraw/history\", signed=True, data=params, version=1)\n        \n    margin_v1_get_localentity_withdraw_history.__doc__ = Client.margin_v1_get_localentity_withdraw_history.__doc__\n            \n    async def margin_v2_post_sub_account_sub_account_api_ip_restriction(self, **params):\n        return await self._request_margin_api(\"post\", \"sub-account/subAccountApi/ipRestriction\", signed=True, data=params, version=2)\n        \n    margin_v2_post_sub_account_sub_account_api_ip_restriction.__doc__ = Client.margin_v2_post_sub_account_sub_account_api_ip_restriction.__doc__\n            \n    async def futures_v1_get_rate_limit_order(self, **params):\n        return await self._request_futures_api(\"get\", \"rateLimit/order\", signed=True, data=params, version=1)\n        \n    futures_v1_get_rate_limit_order.__doc__ = Client.futures_v1_get_rate_limit_order.__doc__\n            \n    async def margin_v1_get_broker_sub_account_api_commission_futures(self, **params):\n        return await self._request_margin_api(\"get\", \"broker/subAccountApi/commission/futures\", signed=True, data=params, version=1)\n        \n    margin_v1_get_broker_sub_account_api_commission_futures.__doc__ = Client.margin_v1_get_broker_sub_account_api_commission_futures.__doc__\n            \n    async def margin_v1_get_sol_staking_sol_history_staking_history(self, **params):\n        return await self._request_margin_api(\"get\", \"sol-staking/sol/history/stakingHistory\", signed=True, data=params, version=1)\n        \n    margin_v1_get_sol_staking_sol_history_staking_history.__doc__ = Client.margin_v1_get_sol_staking_sol_history_staking_history.__doc__\n            \n    async def futures_v1_get_open_order(self, **params):\n        return await self._request_futures_api(\"get\", \"openOrder\", signed=True, data=params, version=1)\n        \n    futures_v1_get_open_order.__doc__ = Client.futures_v1_get_open_order.__doc__\n            \n    async def margin_v1_delete_algo_spot_order(self, **params):\n        return await self._request_margin_api(\"delete\", \"algo/spot/order\", signed=True, data=params, version=1)\n        \n    margin_v1_delete_algo_spot_order.__doc__ = Client.margin_v1_delete_algo_spot_order.__doc__\n            \n    async def v3_post_order(self, **params):\n        return await self._request_api(\"post\", \"order\", signed=True, data=params, version=\"v3\")\n        \n    async def margin_v1_delete_account_api_restrictions_ip_restriction_ip_list(self, **params):\n        return await self._request_margin_api(\"delete\", \"account/apiRestrictions/ipRestriction/ipList\", signed=True, data=params, version=1)\n        \n    margin_v1_delete_account_api_restrictions_ip_restriction_ip_list.__doc__ = Client.margin_v1_delete_account_api_restrictions_ip_restriction_ip_list.__doc__\n            \n    async def margin_v1_post_capital_contract_convertible_coins(self, **params):\n        return await self._request_margin_api(\"post\", \"capital/contract/convertible-coins\", signed=True, data=params, version=1)\n        \n    margin_v1_post_capital_contract_convertible_coins.__doc__ = Client.margin_v1_post_capital_contract_convertible_coins.__doc__\n            \n    async def margin_v1_get_managed_subaccount_margin_asset(self, **params):\n        return await self._request_margin_api(\"get\", \"managed-subaccount/marginAsset\", signed=True, data=params, version=1)\n        \n    margin_v1_get_managed_subaccount_margin_asset.__doc__ = Client.margin_v1_get_managed_subaccount_margin_asset.__doc__\n            \n    async def v3_delete_order_list(self, **params):\n        return await self._request_api(\"delete\", \"orderList\", signed=True, data=params, version=\"v3\")\n        \n    v3_delete_order_list.__doc__ = Client.v3_delete_order_list.__doc__\n            \n    async def margin_v1_post_sub_account_sub_account_api_ip_restriction_ip_list(self, **params):\n        return await self._request_margin_api(\"post\", \"sub-account/subAccountApi/ipRestriction/ipList\", signed=True, data=params, version=1)\n        \n    margin_v1_post_sub_account_sub_account_api_ip_restriction_ip_list.__doc__ = Client.margin_v1_post_sub_account_sub_account_api_ip_restriction_ip_list.__doc__\n            \n    async def margin_v1_post_broker_sub_account_api_commission(self, **params):\n        return await self._request_margin_api(\"post\", \"broker/subAccountApi/commission\", signed=True, data=params, version=1)\n        \n    margin_v1_post_broker_sub_account_api_commission.__doc__ = Client.margin_v1_post_broker_sub_account_api_commission.__doc__\n            \n    async def futures_v1_post_fee_burn(self, **params):\n        return await self._request_futures_api(\"post\", \"feeBurn\", signed=True, data=params, version=1)\n        \n    futures_v1_post_fee_burn.__doc__ = Client.futures_v1_post_fee_burn.__doc__\n            \n    async def margin_v1_get_broker_sub_account_margin_summary(self, **params):\n        return await self._request_margin_api(\"get\", \"broker/subAccount/marginSummary\", signed=True, data=params, version=1)\n        \n    margin_v1_get_broker_sub_account_margin_summary.__doc__ = Client.margin_v1_get_broker_sub_account_margin_summary.__doc__\n            \n    async def margin_v1_get_lending_auto_invest_plan_list(self, **params):\n        return await self._request_margin_api(\"get\", \"lending/auto-invest/plan/list\", signed=True, data=params, version=1)\n        \n    margin_v1_get_lending_auto_invest_plan_list.__doc__ = Client.margin_v1_get_lending_auto_invest_plan_list.__doc__\n            \n    async def margin_v1_get_loan_vip_loanable_data(self, **params):\n        return await self._request_margin_api(\"get\", \"loan/vip/loanable/data\", signed=True, data=params, version=1)\n        \n    margin_v1_get_loan_vip_loanable_data.__doc__ = Client.margin_v1_get_loan_vip_loanable_data.__doc__\n            \n    async def margin_v2_get_loan_flexible_collateral_data(self, **params):\n        return await self._request_margin_api(\"get\", \"loan/flexible/collateral/data\", signed=True, data=params, version=2)\n        \n    margin_v2_get_loan_flexible_collateral_data.__doc__ = Client.margin_v2_get_loan_flexible_collateral_data.__doc__\n            \n    async def margin_v1_delete_broker_sub_account_api(self, **params):\n        return await self._request_margin_api(\"delete\", \"broker/subAccountApi\", signed=True, data=params, version=1)\n        \n    margin_v1_delete_broker_sub_account_api.__doc__ = Client.margin_v1_delete_broker_sub_account_api.__doc__\n            \n    async def margin_v1_get_sol_staking_sol_history_bnsol_rewards_history(self, **params):\n        return await self._request_margin_api(\"get\", \"sol-staking/sol/history/bnsolRewardsHistory\", signed=True, data=params, version=1)\n        \n    margin_v1_get_sol_staking_sol_history_bnsol_rewards_history.__doc__ = Client.margin_v1_get_sol_staking_sol_history_bnsol_rewards_history.__doc__\n            \n    async def margin_v1_get_convert_limit_query_open_orders(self, **params):\n        return await self._request_margin_api(\"get\", \"convert/limit/queryOpenOrders\", signed=True, data=params, version=1)\n        \n    margin_v1_get_convert_limit_query_open_orders.__doc__ = Client.margin_v1_get_convert_limit_query_open_orders.__doc__\n            \n    async def v3_get_account_commission(self, **params):\n        return await self._request_api(\"get\", \"account/commission\", signed=True, data=params, version=\"v3\")\n        \n    v3_get_account_commission.__doc__ = Client.v3_get_account_commission.__doc__\n            \n    async def v3_post_order_list_oco(self, **params):\n        return await self._request_api(\"post\", \"orderList/oco\", signed=True, data=params, version=\"v3\")\n        \n    async def margin_v1_get_managed_subaccount_query_trans_log(self, **params):\n        return await self._request_margin_api(\"get\", \"managed-subaccount/query-trans-log\", signed=True, data=params, version=1)\n        \n    margin_v1_get_managed_subaccount_query_trans_log.__doc__ = Client.margin_v1_get_managed_subaccount_query_trans_log.__doc__\n            \n    async def margin_v2_post_broker_sub_account_api_ip_restriction(self, **params):\n        return await self._request_margin_api(\"post\", \"broker/subAccountApi/ipRestriction\", signed=True, data=params, version=2)\n        \n    margin_v2_post_broker_sub_account_api_ip_restriction.__doc__ = Client.margin_v2_post_broker_sub_account_api_ip_restriction.__doc__\n            \n    async def margin_v1_get_lending_auto_invest_all_asset(self, **params):\n        return await self._request_margin_api(\"get\", \"lending/auto-invest/all/asset\", signed=True, data=params, version=1)\n        \n    margin_v1_get_lending_auto_invest_all_asset.__doc__ = Client.margin_v1_get_lending_auto_invest_all_asset.__doc__\n            \n    async def futures_v1_post_convert_accept_quote(self, **params):\n        return await self._request_futures_api(\"post\", \"convert/acceptQuote\", signed=True, data=params, version=1)\n        \n    futures_v1_post_convert_accept_quote.__doc__ = Client.futures_v1_post_convert_accept_quote.__doc__\n            \n    async def margin_v1_get_spot_delist_schedule(self, **params):\n        return await self._request_margin_api(\"get\", \"spot/delist-schedule\", signed=True, data=params, version=1)\n        \n    margin_v1_get_spot_delist_schedule.__doc__ = Client.margin_v1_get_spot_delist_schedule.__doc__\n            \n    async def margin_v1_post_account_api_restrictions_ip_restriction(self, **params):\n        return await self._request_margin_api(\"post\", \"account/apiRestrictions/ipRestriction\", signed=True, data=params, version=1)\n        \n    margin_v1_post_account_api_restrictions_ip_restriction.__doc__ = Client.margin_v1_post_account_api_restrictions_ip_restriction.__doc__\n            \n    async def margin_v1_get_dci_product_accounts(self, **params):\n        return await self._request_margin_api(\"get\", \"dci/product/accounts\", signed=True, data=params, version=1)\n        \n    margin_v1_get_dci_product_accounts.__doc__ = Client.margin_v1_get_dci_product_accounts.__doc__\n            \n    async def margin_v1_get_sub_account_sub_account_api_ip_restriction(self, **params):\n        return await self._request_margin_api(\"get\", \"sub-account/subAccountApi/ipRestriction\", signed=True, data=params, version=1)\n        \n    margin_v1_get_sub_account_sub_account_api_ip_restriction.__doc__ = Client.margin_v1_get_sub_account_sub_account_api_ip_restriction.__doc__\n            \n    async def margin_v1_get_sub_account_transaction_statistics(self, **params):\n        return await self._request_margin_api(\"get\", \"sub-account/transaction-statistics\", signed=True, data=params, version=1)\n        \n    margin_v1_get_sub_account_transaction_statistics.__doc__ = Client.margin_v1_get_sub_account_transaction_statistics.__doc__\n            \n    async def margin_v1_get_managed_subaccount_deposit_address(self, **params):\n        return await self._request_margin_api(\"get\", \"managed-subaccount/deposit/address\", signed=True, data=params, version=1)\n        \n    margin_v1_get_managed_subaccount_deposit_address.__doc__ = Client.margin_v1_get_managed_subaccount_deposit_address.__doc__\n            \n    async def margin_v2_get_portfolio_account(self, **params):\n        return await self._request_margin_api(\"get\", \"portfolio/account\", signed=True, data=params, version=2)\n        \n    margin_v2_get_portfolio_account.__doc__ = Client.margin_v2_get_portfolio_account.__doc__\n            \n    async def margin_v1_get_simple_earn_locked_history_redemption_record(self, **params):\n        return await self._request_margin_api(\"get\", \"simple-earn/locked/history/redemptionRecord\", signed=True, data=params, version=1)\n        \n    margin_v1_get_simple_earn_locked_history_redemption_record.__doc__ = Client.margin_v1_get_simple_earn_locked_history_redemption_record.__doc__\n            \n    async def futures_v1_get_order_asyn_id(self, **params):\n        return await self._request_futures_api(\"get\", \"order/asyn/id\", signed=True, data=params, version=1)\n        \n    futures_v1_get_order_asyn_id.__doc__ = Client.futures_v1_get_order_asyn_id.__doc__\n            \n    async def margin_v1_post_managed_subaccount_withdraw(self, **params):\n        return await self._request_margin_api(\"post\", \"managed-subaccount/withdraw\", signed=True, data=params, version=1)\n        \n    margin_v1_post_managed_subaccount_withdraw.__doc__ = Client.margin_v1_post_managed_subaccount_withdraw.__doc__\n            \n    async def margin_v1_get_localentity_deposit_history(self, **params):\n        return await self._request_margin_api(\"get\", \"localentity/deposit/history\", signed=True, data=params, version=1)\n        \n    margin_v1_get_localentity_deposit_history.__doc__ = Client.margin_v1_get_localentity_deposit_history.__doc__\n            \n    async def margin_v1_post_eth_staking_wbeth_wrap(self, **params):\n        return await self._request_margin_api(\"post\", \"eth-staking/wbeth/wrap\", signed=True, data=params, version=1)\n        \n    margin_v1_post_eth_staking_wbeth_wrap.__doc__ = Client.margin_v1_post_eth_staking_wbeth_wrap.__doc__\n            \n    async def margin_v1_post_simple_earn_locked_set_redeem_option(self, **params):\n        return await self._request_margin_api(\"post\", \"simple-earn/locked/setRedeemOption\", signed=True, data=params, version=1)\n        \n    margin_v1_post_simple_earn_locked_set_redeem_option.__doc__ = Client.margin_v1_post_simple_earn_locked_set_redeem_option.__doc__\n            \n    async def margin_v1_post_broker_sub_account_api_ip_restriction_ip_list(self, **params):\n        return await self._request_margin_api(\"post\", \"broker/subAccountApi/ipRestriction/ipList\", signed=True, data=params, version=1)\n        \n    margin_v1_post_broker_sub_account_api_ip_restriction_ip_list.__doc__ = Client.margin_v1_post_broker_sub_account_api_ip_restriction_ip_list.__doc__\n            \n    async def margin_v1_post_broker_sub_account_api_commission_futures(self, **params):\n        return await self._request_margin_api(\"post\", \"broker/subAccountApi/commission/futures\", signed=True, data=params, version=1)\n        \n    margin_v1_post_broker_sub_account_api_commission_futures.__doc__ = Client.margin_v1_post_broker_sub_account_api_commission_futures.__doc__\n            \n    async def v3_get_open_orders(self, **params):\n        return await self._request_api(\"get\", \"openOrders\", signed=True, data=params, version=\"v3\")\n        \n    async def margin_v1_get_lending_auto_invest_history_list(self, **params):\n        return await self._request_margin_api(\"get\", \"lending/auto-invest/history/list\", signed=True, data=params, version=1)\n        \n    margin_v1_get_lending_auto_invest_history_list.__doc__ = Client.margin_v1_get_lending_auto_invest_history_list.__doc__\n            \n    async def margin_v1_post_loan_customize_margin_call(self, **params):\n        return await self._request_margin_api(\"post\", \"loan/customize/margin_call\", signed=True, data=params, version=1)\n        \n    margin_v1_post_loan_customize_margin_call.__doc__ = Client.margin_v1_post_loan_customize_margin_call.__doc__\n            \n    async def margin_v1_get_broker_sub_account_bnb_burn_status(self, **params):\n        return await self._request_margin_api(\"get\", \"broker/subAccount/bnbBurn/status\", signed=True, data=params, version=1)\n        \n    margin_v1_get_broker_sub_account_bnb_burn_status.__doc__ = Client.margin_v1_get_broker_sub_account_bnb_burn_status.__doc__\n            \n    async def margin_v1_get_managed_subaccount_account_snapshot(self, **params):\n        return await self._request_margin_api(\"get\", \"managed-subaccount/accountSnapshot\", signed=True, data=params, version=1)\n        \n    margin_v1_get_managed_subaccount_account_snapshot.__doc__ = Client.margin_v1_get_managed_subaccount_account_snapshot.__doc__\n            \n    async def margin_v1_post_asset_convert_transfer(self, **params):\n        return await self._request_margin_api(\"post\", \"asset/convert-transfer\", signed=True, data=params, version=1)\n        \n    margin_v1_post_asset_convert_transfer.__doc__ = Client.margin_v1_post_asset_convert_transfer.__doc__\n            \n    async def options_v1_get_income_asyn(self, **params):\n        return await self._request_options_api(\"get\", \"income/asyn\", signed=True, data=params)\n        \n    options_v1_get_income_asyn.__doc__ = Client.options_v1_get_income_asyn.__doc__\n            \n    async def margin_v1_get_broker_sub_account_api_commission_coin_futures(self, **params):\n        return await self._request_margin_api(\"get\", \"broker/subAccountApi/commission/coinFutures\", signed=True, data=params, version=1)\n        \n    margin_v1_get_broker_sub_account_api_commission_coin_futures.__doc__ = Client.margin_v1_get_broker_sub_account_api_commission_coin_futures.__doc__\n            \n    async def margin_v2_get_broker_sub_account_futures_summary(self, **params):\n        return await self._request_margin_api(\"get\", \"broker/subAccount/futuresSummary\", signed=True, data=params, version=2)\n        \n    margin_v2_get_broker_sub_account_futures_summary.__doc__ = Client.margin_v2_get_broker_sub_account_futures_summary.__doc__\n            \n    async def margin_v1_get_loan_ongoing_orders(self, **params):\n        return await self._request_margin_api(\"get\", \"loan/ongoing/orders\", signed=True, data=params, version=1)\n        \n    margin_v1_get_loan_ongoing_orders.__doc__ = Client.margin_v1_get_loan_ongoing_orders.__doc__\n            \n    async def margin_v2_get_loan_flexible_ongoing_orders(self, **params):\n        return await self._request_margin_api(\"get\", \"loan/flexible/ongoing/orders\", signed=True, data=params, version=2)\n        \n    margin_v2_get_loan_flexible_ongoing_orders.__doc__ = Client.margin_v2_get_loan_flexible_ongoing_orders.__doc__\n            \n    async def margin_v1_post_algo_futures_new_order_vp(self, **params):\n        return await self._request_margin_api(\"post\", \"algo/futures/newOrderVp\", signed=True, data=params, version=1)\n        \n    margin_v1_post_algo_futures_new_order_vp.__doc__ = Client.margin_v1_post_algo_futures_new_order_vp.__doc__\n            \n    async def futures_v1_post_convert_get_quote(self, **params):\n        return await self._request_futures_api(\"post\", \"convert/getQuote\", signed=True, data=params, version=1)\n        \n    futures_v1_post_convert_get_quote.__doc__ = Client.futures_v1_post_convert_get_quote.__doc__\n            \n    async def margin_v1_get_algo_spot_sub_orders(self, **params):\n        return await self._request_margin_api(\"get\", \"algo/spot/subOrders\", signed=True, data=params, version=1)\n        \n    margin_v1_get_algo_spot_sub_orders.__doc__ = Client.margin_v1_get_algo_spot_sub_orders.__doc__\n            \n    async def margin_v1_post_portfolio_redeem(self, **params):\n        return await self._request_margin_api(\"post\", \"portfolio/redeem\", signed=True, data=params, version=1)\n        \n    margin_v1_post_portfolio_redeem.__doc__ = Client.margin_v1_post_portfolio_redeem.__doc__\n            \n    async def margin_v1_post_lending_auto_invest_plan_add(self, **params):\n        return await self._request_margin_api(\"post\", \"lending/auto-invest/plan/add\", signed=True, data=params, version=1)\n        \n    margin_v1_post_lending_auto_invest_plan_add.__doc__ = Client.margin_v1_post_lending_auto_invest_plan_add.__doc__\n            \n    async def v3_get_order_list(self, **params):\n        return await self._request_api(\"get\", \"orderList\", signed=True, data=params, version=\"v3\")\n        \n    v3_get_order_list.__doc__ = Client.v3_get_order_list.__doc__\n            \n    async def v3_get_my_trades(self, **params):\n        return await self._request_api(\"get\", \"myTrades\", signed=True, data=params, version=\"v3\")\n        \n    async def margin_v1_get_lending_auto_invest_source_asset_list(self, **params):\n        return await self._request_margin_api(\"get\", \"lending/auto-invest/source-asset/list\", signed=True, data=params, version=1)\n        \n    margin_v1_get_lending_auto_invest_source_asset_list.__doc__ = Client.margin_v1_get_lending_auto_invest_source_asset_list.__doc__\n            \n    async def margin_v1_get_margin_all_order_list(self, **params):\n        return await self._request_margin_api(\"get\", \"margin/allOrderList\", signed=True, data=params, version=1)\n        \n    margin_v1_get_margin_all_order_list.__doc__ = Client.margin_v1_get_margin_all_order_list.__doc__\n            \n    async def margin_v1_post_eth_staking_eth_redeem(self, **params):\n        return await self._request_margin_api(\"post\", \"eth-staking/eth/redeem\", signed=True, data=params, version=1)\n        \n    margin_v1_post_eth_staking_eth_redeem.__doc__ = Client.margin_v1_post_eth_staking_eth_redeem.__doc__\n            \n    async def margin_v1_get_broker_rebate_historical_record(self, **params):\n        return await self._request_margin_api(\"get\", \"broker/rebate/historicalRecord\", signed=True, data=params, version=1)\n        \n    margin_v1_get_broker_rebate_historical_record.__doc__ = Client.margin_v1_get_broker_rebate_historical_record.__doc__\n            \n    async def margin_v1_get_simple_earn_locked_history_subscription_record(self, **params):\n        return await self._request_margin_api(\"get\", \"simple-earn/locked/history/subscriptionRecord\", signed=True, data=params, version=1)\n        \n    margin_v1_get_simple_earn_locked_history_subscription_record.__doc__ = Client.margin_v1_get_simple_earn_locked_history_subscription_record.__doc__\n            \n    async def futures_coin_v1_put_order(self, **params):\n        return await self._request_futures_coin_api(\"put\", \"order\", signed=True, data=params, version=1)\n        \n    futures_coin_v1_put_order.__doc__ = Client.futures_coin_v1_put_order.__doc__\n            \n    async def margin_v1_get_managed_subaccount_asset(self, **params):\n        return await self._request_margin_api(\"get\", \"managed-subaccount/asset\", signed=True, data=params, version=1)\n        \n    margin_v1_get_managed_subaccount_asset.__doc__ = Client.margin_v1_get_managed_subaccount_asset.__doc__\n            \n    async def margin_v1_get_sol_staking_sol_quota(self, **params):\n        return await self._request_margin_api(\"get\", \"sol-staking/sol/quota\", signed=True, data=params, version=1)\n        \n    margin_v1_get_sol_staking_sol_quota.__doc__ = Client.margin_v1_get_sol_staking_sol_quota.__doc__\n            \n    async def margin_v1_post_loan_vip_renew(self, **params):\n        return await self._request_margin_api(\"post\", \"loan/vip/renew\", signed=True, data=params, version=1)\n        \n    margin_v1_post_loan_vip_renew.__doc__ = Client.margin_v1_post_loan_vip_renew.__doc__\n            \n    async def margin_v1_get_managed_subaccount_query_trans_log_for_trade_parent(self, **params):\n        return await self._request_margin_api(\"get\", \"managed-subaccount/queryTransLogForTradeParent\", signed=True, data=params, version=1)\n        \n    margin_v1_get_managed_subaccount_query_trans_log_for_trade_parent.__doc__ = Client.margin_v1_get_managed_subaccount_query_trans_log_for_trade_parent.__doc__\n            \n    async def margin_v1_post_sub_account_sub_account_api_ip_restriction(self, **params):\n        return await self._request_margin_api(\"post\", \"sub-account/subAccountApi/ipRestriction\", signed=True, data=params, version=1)\n        \n    margin_v1_post_sub_account_sub_account_api_ip_restriction.__doc__ = Client.margin_v1_post_sub_account_sub_account_api_ip_restriction.__doc__\n            \n    async def margin_v1_get_simple_earn_flexible_history_redemption_record(self, **params):\n        return await self._request_margin_api(\"get\", \"simple-earn/flexible/history/redemptionRecord\", signed=True, data=params, version=1)\n        \n    margin_v1_get_simple_earn_flexible_history_redemption_record.__doc__ = Client.margin_v1_get_simple_earn_flexible_history_redemption_record.__doc__\n            \n    async def margin_v1_get_broker_sub_account_api(self, **params):\n        return await self._request_margin_api(\"get\", \"broker/subAccountApi\", signed=True, data=params, version=1)\n        \n    margin_v1_get_broker_sub_account_api.__doc__ = Client.margin_v1_get_broker_sub_account_api.__doc__\n            \n    async def options_v1_get_exercise_history(self, **params):\n        return await self._request_options_api(\"get\", \"exerciseHistory\", signed=False, data=params)\n        \n    options_v1_get_exercise_history.__doc__ = Client.options_v1_get_exercise_history.__doc__\n            \n    async def margin_v1_get_convert_exchange_info(self, **params):\n        return await self._request_margin_api(\"get\", \"convert/exchangeInfo\", signed=False, data=params, version=1)\n        \n    margin_v1_get_convert_exchange_info.__doc__ = Client.margin_v1_get_convert_exchange_info.__doc__\n            \n    async def futures_v1_delete_batch_order(self, **params):\n        return await self._request_futures_api(\"delete\", \"batchOrder\", signed=True, data=params, version=1)\n        \n    futures_v1_delete_batch_order.__doc__ = Client.futures_v1_delete_batch_order.__doc__\n            \n    async def margin_v1_get_eth_staking_eth_history_wbeth_rewards_history(self, **params):\n        return await self._request_margin_api(\"get\", \"eth-staking/eth/history/wbethRewardsHistory\", signed=True, data=params, version=1)\n        \n    margin_v1_get_eth_staking_eth_history_wbeth_rewards_history.__doc__ = Client.margin_v1_get_eth_staking_eth_history_wbeth_rewards_history.__doc__\n            \n    async def margin_v1_get_mining_pub_algo_list(self, **params):\n        return await self._request_margin_api(\"get\", \"mining/pub/algoList\", signed=True, data=params, version=1)\n        \n    margin_v1_get_mining_pub_algo_list.__doc__ = Client.margin_v1_get_mining_pub_algo_list.__doc__\n            \n    async def options_v1_get_block_trades(self, **params):\n        return await self._request_options_api(\"get\", \"blockTrades\", signed=False, data=params)\n        \n    options_v1_get_block_trades.__doc__ = Client.options_v1_get_block_trades.__doc__\n            \n    async def margin_v1_get_copy_trading_futures_lead_symbol(self, **params):\n        return await self._request_margin_api(\"get\", \"copyTrading/futures/leadSymbol\", signed=True, data=params, version=1)\n        \n    margin_v1_get_copy_trading_futures_lead_symbol.__doc__ = Client.margin_v1_get_copy_trading_futures_lead_symbol.__doc__\n            \n    async def margin_v1_get_mining_worker_list(self, **params):\n        return await self._request_margin_api(\"get\", \"mining/worker/list\", signed=True, data=params, version=1)\n        \n    margin_v1_get_mining_worker_list.__doc__ = Client.margin_v1_get_mining_worker_list.__doc__\n            \n    async def margin_v1_get_dci_product_list(self, **params):\n        return await self._request_margin_api(\"get\", \"dci/product/list\", signed=True, data=params, version=1)\n        \n    margin_v1_get_dci_product_list.__doc__ = Client.margin_v1_get_dci_product_list.__doc__\n            \n    async def futures_v1_get_convert_order_status(self, **params):\n        return await self._request_futures_api(\"get\", \"convert/orderStatus\", signed=True, data=params, version=1)\n        \n    futures_v1_get_convert_order_status.__doc__ = Client.futures_v1_get_convert_order_status.__doc__\n            \n"
  },
  {
    "path": "binance/base_client.py",
    "content": "from base64 import b64encode\nfrom pathlib import Path\nimport random\nfrom typing import Dict, Optional, List, Tuple, Union, Any\n\nimport asyncio\nimport hashlib\nimport hmac\nimport logging\nimport time\nfrom Crypto.PublicKey import RSA, ECC\nfrom Crypto.Hash import SHA256\nfrom Crypto.Signature import pkcs1_15, eddsa\nimport urllib.parse as _urlencode\nfrom operator import itemgetter\nfrom urllib.parse import urlencode\n\nfrom binance.ws.websocket_api import WebsocketAPI\n\nfrom .helpers import get_loop\n\n\nclass BaseClient:\n    API_URL = \"https://api{}.binance.{}/api\"\n    API_TESTNET_URL = \"https://testnet.binance.vision/api\"\n    API_DEMO_URL = \"https://demo-api.binance.com/api\"\n    MARGIN_API_URL = \"https://api{}.binance.{}/sapi\"\n    WEBSITE_URL = \"https://www.binance.{}\"\n    FUTURES_URL = \"https://fapi.binance.{}/fapi\"\n    FUTURES_TESTNET_URL = \"https://testnet.binancefuture.com/fapi\"\n    FUTURES_DEMO_URL = \"https://demo-fapi.binance.com/fapi\"\n    FUTURES_DATA_URL = \"https://fapi.binance.{}/futures/data\"\n    FUTURES_DATA_TESTNET_URL = \"https://testnet.binancefuture.com/futures/data\"\n    FUTURES_COIN_URL = \"https://dapi.binance.{}/dapi\"\n    FUTURES_COIN_TESTNET_URL = \"https://testnet.binancefuture.com/dapi\"\n    FUTURES_COIN_DEMO_URL = \"https://demo-dapi.binance.com/dapi\"\n    FUTURES_COIN_DATA_URL = \"https://dapi.binance.{}/futures/data\"\n    FUTURES_COIN_DATA_TESTNET_URL = \"https://testnet.binancefuture.com/futures/data\"\n    OPTIONS_URL = \"https://eapi.binance.{}/eapi\"\n    OPTIONS_TESTNET_URL = \"https://testnet.binanceops.{}/eapi\"\n    PAPI_URL = \"https://papi.binance.{}/papi\"\n    WS_API_URL = \"wss://ws-api.binance.{}/ws-api/v3\"\n    WS_API_TESTNET_URL = \"wss://ws-api.testnet.binance.vision/ws-api/v3\"\n    WS_API_DEMO_URL = \"wss://demo-ws-api.binance.com/ws-api/v3\"\n    WS_FUTURES_URL = \"wss://ws-fapi.binance.{}/ws-fapi/v1\"\n    WS_FUTURES_TESTNET_URL = \"wss://testnet.binancefuture.com/ws-fapi/v1\"\n    WS_FUTURES_DEMO_URL = \"wss://testnet.binancefuture.com/ws-fapi/v1\"\n    PUBLIC_API_VERSION = \"v3\"\n    PRIVATE_API_VERSION = \"v3\"\n    MARGIN_API_VERSION = \"v1\"\n    MARGIN_API_VERSION2 = \"v2\"\n    MARGIN_API_VERSION3 = \"v3\"\n    MARGIN_API_VERSION4 = \"v4\"\n    FUTURES_API_VERSION = \"v1\"\n    FUTURES_API_VERSION2 = \"v2\"\n    FUTURES_API_VERSION3 = \"v3\"\n    OPTIONS_API_VERSION = \"v1\"\n    PORTFOLIO_API_VERSION = \"v1\"\n    PORTFOLIO_API_VERSION2 = \"v2\"\n\n    BASE_ENDPOINT_DEFAULT = \"\"\n    BASE_ENDPOINT_1 = \"1\"\n    BASE_ENDPOINT_2 = \"2\"\n    BASE_ENDPOINT_3 = \"3\"\n    BASE_ENDPOINT_4 = \"4\"\n\n    REQUEST_TIMEOUT: float = 10\n\n    REQUEST_RECVWINDOW: int = 10000  # 10 seconds\n\n    SYMBOL_TYPE_SPOT = \"SPOT\"\n\n    ORDER_STATUS_NEW = \"NEW\"\n    ORDER_STATUS_PARTIALLY_FILLED = \"PARTIALLY_FILLED\"\n    ORDER_STATUS_FILLED = \"FILLED\"\n    ORDER_STATUS_CANCELED = \"CANCELED\"\n    ORDER_STATUS_PENDING_CANCEL = \"PENDING_CANCEL\"\n    ORDER_STATUS_REJECTED = \"REJECTED\"\n    ORDER_STATUS_EXPIRED = \"EXPIRED\"\n\n    KLINE_INTERVAL_1SECOND = \"1s\"\n    KLINE_INTERVAL_1MINUTE = \"1m\"\n    KLINE_INTERVAL_3MINUTE = \"3m\"\n    KLINE_INTERVAL_5MINUTE = \"5m\"\n    KLINE_INTERVAL_15MINUTE = \"15m\"\n    KLINE_INTERVAL_30MINUTE = \"30m\"\n    KLINE_INTERVAL_1HOUR = \"1h\"\n    KLINE_INTERVAL_2HOUR = \"2h\"\n    KLINE_INTERVAL_4HOUR = \"4h\"\n    KLINE_INTERVAL_6HOUR = \"6h\"\n    KLINE_INTERVAL_8HOUR = \"8h\"\n    KLINE_INTERVAL_12HOUR = \"12h\"\n    KLINE_INTERVAL_1DAY = \"1d\"\n    KLINE_INTERVAL_3DAY = \"3d\"\n    KLINE_INTERVAL_1WEEK = \"1w\"\n    KLINE_INTERVAL_1MONTH = \"1M\"\n\n    SIDE_BUY = \"BUY\"\n    SIDE_SELL = \"SELL\"\n\n    ORDER_TYPE_LIMIT = \"LIMIT\"\n    ORDER_TYPE_MARKET = \"MARKET\"\n    ORDER_TYPE_STOP_LOSS = \"STOP_LOSS\"\n    ORDER_TYPE_STOP_LOSS_LIMIT = \"STOP_LOSS_LIMIT\"\n    ORDER_TYPE_TAKE_PROFIT = \"TAKE_PROFIT\"\n    ORDER_TYPE_TAKE_PROFIT_LIMIT = \"TAKE_PROFIT_LIMIT\"\n    ORDER_TYPE_LIMIT_MAKER = \"LIMIT_MAKER\"\n\n    FUTURE_ORDER_TYPE_LIMIT = \"LIMIT\"\n    FUTURE_ORDER_TYPE_MARKET = \"MARKET\"\n    FUTURE_ORDER_TYPE_STOP = \"STOP\"\n    FUTURE_ORDER_TYPE_STOP_MARKET = \"STOP_MARKET\"\n    FUTURE_ORDER_TYPE_TAKE_PROFIT = \"TAKE_PROFIT\"\n    FUTURE_ORDER_TYPE_TAKE_PROFIT_MARKET = \"TAKE_PROFIT_MARKET\"\n    FUTURE_ORDER_TYPE_LIMIT_MAKER = \"LIMIT_MAKER\"\n\n    TIME_IN_FORCE_GTC = \"GTC\"  # Good till cancelled\n    TIME_IN_FORCE_IOC = \"IOC\"  # Immediate or cancel\n    TIME_IN_FORCE_FOK = \"FOK\"  # Fill or kill\n\n    ORDER_RESP_TYPE_ACK = \"ACK\"\n    ORDER_RESP_TYPE_RESULT = \"RESULT\"\n    ORDER_RESP_TYPE_FULL = \"FULL\"\n\n    # For accessing the data returned by Client.aggregate_trades().\n    AGG_ID = \"a\"\n    AGG_PRICE = \"p\"\n    AGG_QUANTITY = \"q\"\n    AGG_FIRST_TRADE_ID = \"f\"\n    AGG_LAST_TRADE_ID = \"l\"\n    AGG_TIME = \"T\"\n    AGG_BUYER_MAKES = \"m\"\n    AGG_BEST_MATCH = \"M\"\n\n    # new asset transfer api enum\n    SPOT_TO_FIAT = \"MAIN_C2C\"\n    SPOT_TO_USDT_FUTURE = \"MAIN_UMFUTURE\"\n    SPOT_TO_COIN_FUTURE = \"MAIN_CMFUTURE\"\n    SPOT_TO_MARGIN_CROSS = \"MAIN_MARGIN\"\n    SPOT_TO_MINING = \"MAIN_MINING\"\n    FIAT_TO_SPOT = \"C2C_MAIN\"\n    FIAT_TO_USDT_FUTURE = \"C2C_UMFUTURE\"\n    FIAT_TO_MINING = \"C2C_MINING\"\n    USDT_FUTURE_TO_SPOT = \"UMFUTURE_MAIN\"\n    USDT_FUTURE_TO_FIAT = \"UMFUTURE_C2C\"\n    USDT_FUTURE_TO_MARGIN_CROSS = \"UMFUTURE_MARGIN\"\n    COIN_FUTURE_TO_SPOT = \"CMFUTURE_MAIN\"\n    MARGIN_CROSS_TO_SPOT = \"MARGIN_MAIN\"\n    MARGIN_CROSS_TO_USDT_FUTURE = \"MARGIN_UMFUTURE\"\n    MINING_TO_SPOT = \"MINING_MAIN\"\n    MINING_TO_USDT_FUTURE = \"MINING_UMFUTURE\"\n    MINING_TO_FIAT = \"MINING_C2C\"\n\n    ## order ids\n    SPOT_ORDER_PREFIX = \"x-HNA2TXFJ\"\n    CONTRACT_ORDER_PREFIX = \"x-Cb7ytekJ\"\n\n    def __init__(\n        self,\n        api_key: Optional[str] = None,\n        api_secret: Optional[str] = None,\n        requests_params: Optional[Dict[str, Any]] = None,\n        tld: str = \"com\",\n        base_endpoint: str = BASE_ENDPOINT_DEFAULT,\n        testnet: bool = False,\n        demo: bool = False,\n        private_key: Optional[Union[str, Path]] = None,\n        private_key_pass: Optional[str] = None,\n        loop: Optional[asyncio.AbstractEventLoop] = None,\n        time_unit: Optional[str] = None,\n        verbose: bool = False,\n    ):\n        \"\"\"Binance API Client constructor\n\n        :param api_key: Api Key\n        :type api_key: str.\n        :param api_secret: Api Secret\n        :type api_secret: str.\n        :param requests_params: optional - Dictionary of requests params to use for all calls\n        :type requests_params: dict.\n        :param testnet: Use testnet environment - only available for vanilla options at the moment\n        :type testnet: bool\n        :param private_key: Path to private key, or string of file contents\n        :type private_key: optional - str or Path\n        :param private_key_pass: Password of private key\n        :type private_key_pass: optional - str\n        :param time_unit: Time unit to use for requests. Supported values: \"MILLISECOND\", \"MICROSECOND\"\n        :type time_unit: optional - str\n        :param verbose: Enable verbose logging for debugging\n        :type verbose: bool\n\n        \"\"\"\n\n        self.tld = tld\n        self.verbose = verbose\n        self.logger = logging.getLogger(__name__)\n\n        # Set logger level based on verbose flag\n        # Users can override this by configuring logging externally\n        if verbose:\n            self.logger.setLevel(logging.DEBUG)\n        self.API_URL = self.API_URL.format(base_endpoint, tld)\n        self.MARGIN_API_URL = self.MARGIN_API_URL.format(base_endpoint, tld)\n        self.WEBSITE_URL = self.WEBSITE_URL.format(tld)\n        self.FUTURES_URL = self.FUTURES_URL.format(tld)\n        self.FUTURES_DATA_URL = self.FUTURES_DATA_URL.format(tld)\n        self.FUTURES_COIN_URL = self.FUTURES_COIN_URL.format(tld)\n        self.FUTURES_COIN_DATA_URL = self.FUTURES_COIN_DATA_URL.format(tld)\n        self.OPTIONS_URL = self.OPTIONS_URL.format(tld)\n        self.OPTIONS_TESTNET_URL = self.OPTIONS_TESTNET_URL.format(tld)\n\n        self.API_KEY = api_key\n        self.API_SECRET = api_secret\n        self.TIME_UNIT = time_unit\n        self._is_rsa = False\n        self.PRIVATE_KEY: Any = self._init_private_key(private_key, private_key_pass)\n        self.session = self._init_session()\n        self._requests_params = requests_params\n        self.response = None\n        self.testnet = testnet\n        self.demo = demo\n        self.timestamp_offset = 0\n        ws_api_url = self.WS_API_URL.format(tld)\n        if testnet:\n            ws_api_url = self.WS_API_TESTNET_URL\n        elif demo:\n            ws_api_url = self.WS_API_DEMO_URL\n        if self.TIME_UNIT:\n            ws_api_url += f\"?timeUnit={self.TIME_UNIT}\"\n        # Extract proxy from requests_params for WebSocket connections\n        https_proxy = None\n        if requests_params and 'proxies' in requests_params:\n            https_proxy = requests_params['proxies'].get('https') or requests_params['proxies'].get('http')\n        \n        self.ws_api = WebsocketAPI(url=ws_api_url, tld=tld, https_proxy=https_proxy)\n        ws_future_url = self.WS_FUTURES_URL.format(tld)\n        if testnet:\n            ws_future_url = self.WS_FUTURES_TESTNET_URL\n        elif demo:\n            ws_future_url = self.WS_FUTURES_DEMO_URL\n        self.ws_future = WebsocketAPI(url=ws_future_url, tld=tld, https_proxy=https_proxy)\n        self.loop = loop or get_loop()\n\n    def _get_headers(self) -> Dict:\n        headers = {\n            \"Accept\": \"application/json\",\n            \"Content-Type\": \"application/json\",\n            \"User-Agent\": \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36\",  # noqa\n        }\n        if self.API_KEY:\n            assert self.API_KEY\n            headers[\"X-MBX-APIKEY\"] = self.API_KEY\n        if self.TIME_UNIT:\n            assert self.TIME_UNIT\n            headers[\"X-MBX-TIME-UNIT\"] = self.TIME_UNIT\n        return headers\n\n    def _init_session(self):\n        raise NotImplementedError\n\n    def _init_private_key(\n        self,\n        private_key: Optional[Union[str, Path]],\n        private_key_pass: Optional[str] = None,\n    ):\n        if not private_key:\n            return\n        if isinstance(private_key, Path):\n            with open(private_key, \"r\") as f:\n                private_key = f.read()\n        if len(private_key) > 120:\n            self._is_rsa = True\n            return RSA.import_key(private_key, passphrase=private_key_pass)\n        return ECC.import_key(private_key)\n\n    def _create_api_uri(\n        self, path: str, signed: bool = True, version: str = PUBLIC_API_VERSION\n    ) -> str:\n        url = self.API_URL\n        if self.testnet:\n            url = self.API_TESTNET_URL\n        elif self.demo:\n            url = self.API_DEMO_URL\n        v = self.PRIVATE_API_VERSION if signed else version\n        return url + \"/\" + v + \"/\" + path\n\n    def _create_margin_api_uri(self, path: str, version: int = 1) -> str:\n        options = {\n            1: self.MARGIN_API_VERSION,\n            2: self.MARGIN_API_VERSION2,\n            3: self.MARGIN_API_VERSION3,\n            4: self.MARGIN_API_VERSION4,\n        }\n        return self.MARGIN_API_URL + \"/\" + options[version] + \"/\" + path\n\n    def _create_papi_api_uri(self, path: str, version: int = 1) -> str:\n        options = {1: self.PORTFOLIO_API_VERSION, 2: self.PORTFOLIO_API_VERSION2}\n        return self.PAPI_URL.format(self.tld) + \"/\" + options[version] + \"/\" + path\n\n    def _create_website_uri(self, path: str) -> str:\n        return self.WEBSITE_URL + \"/\" + path\n\n    def _create_futures_api_uri(self, path: str, version: int = 1) -> str:\n        url = self.FUTURES_URL\n        if self.testnet:\n            url = self.FUTURES_TESTNET_URL\n        elif self.demo:\n            url = self.FUTURES_DEMO_URL\n        options = {\n            1: self.FUTURES_API_VERSION,\n            2: self.FUTURES_API_VERSION2,\n            3: self.FUTURES_API_VERSION3,\n        }\n        return url + \"/\" + options[version] + \"/\" + path\n\n    def _create_futures_data_api_uri(self, path: str) -> str:\n        url = self.FUTURES_DATA_URL\n        if self.testnet:\n            url = self.FUTURES_DATA_TESTNET_URL\n        return url + \"/\" + path\n\n    def _create_futures_coin_api_url(self, path: str, version: int = 1) -> str:\n        url = self.FUTURES_COIN_URL\n        if self.testnet:\n            url = self.FUTURES_COIN_TESTNET_URL\n        elif self.demo:\n            url = self.FUTURES_COIN_DEMO_URL\n        options = {\n            1: self.FUTURES_API_VERSION,\n            2: self.FUTURES_API_VERSION2,\n            3: self.FUTURES_API_VERSION3,\n        }\n        return url + \"/\" + options[version] + \"/\" + path\n\n    def _create_futures_coin_data_api_url(self, path: str, version: int = 1) -> str:\n        url = self.FUTURES_COIN_DATA_URL\n        if self.testnet:\n            url = self.FUTURES_COIN_DATA_TESTNET_URL\n        return url + \"/\" + path\n\n    def _create_options_api_uri(self, path: str) -> str:\n        url = self.OPTIONS_URL\n        if self.testnet:\n            url = self.OPTIONS_TESTNET_URL\n        return url + \"/\" + self.OPTIONS_API_VERSION + \"/\" + path\n\n    def _rsa_signature(self, query_string: str):\n        assert self.PRIVATE_KEY\n        h = SHA256.new(query_string.encode(\"utf-8\"))\n        signature = pkcs1_15.new(self.PRIVATE_KEY).sign(h)  # type: ignore\n        res = b64encode(signature).decode()\n        # return self.encode_uri_component(res)\n        return res\n\n    @staticmethod\n    def encode_uri_component(uri, safe=\"~()*!.'\"):\n        return _urlencode.quote(uri, safe=safe)\n\n    @staticmethod\n    def convert_to_dict(list_tuples):\n        dictionary = dict((key, value) for key, value in list_tuples)\n        return dictionary\n\n    def _require_tld(self, required_tld: str, endpoint_name: str = \"endpoint\") -> None:\n        \"\"\"Validate client is configured for required TLD.\n\n        :param required_tld: The required TLD (e.g., \"us\")\n        :param endpoint_name: Description of the endpoint for error messages\n        :raises BinanceRegionException: If the client TLD doesn't match\n        \"\"\"\n        if self.tld != required_tld:\n            from binance.exceptions import BinanceRegionException\n\n            raise BinanceRegionException(required_tld, self.tld, endpoint_name)\n\n    def _ed25519_signature(self, query_string: str):\n        assert self.PRIVATE_KEY\n        res = b64encode(\n            eddsa.new(self.PRIVATE_KEY, \"rfc8032\").sign(query_string.encode())\n        ).decode()  # type: ignore\n        # return self.encode_uri_component(res)\n        return res\n\n    def _hmac_signature(self, query_string: str) -> str:\n        assert self.API_SECRET, \"API Secret required for private endpoints\"\n        m = hmac.new(\n            self.API_SECRET.encode(\"utf-8\"),\n            query_string.encode(\"utf-8\"),\n            hashlib.sha256,\n        )\n        return m.hexdigest()\n\n    def _generate_signature(self, data: Dict, uri_encode=True) -> str:\n        sig_func = self._hmac_signature\n        if self.PRIVATE_KEY:\n            if self._is_rsa:\n                sig_func = self._rsa_signature\n            else:\n                sig_func = self._ed25519_signature\n        query_string = \"&\".join([f\"{d[0]}={_urlencode.quote(d[1]) if d[0] == 'symbol' else d[1]}\" for d in self._order_params(data)])\n        res = sig_func(query_string)\n        return self.encode_uri_component(res) if uri_encode else res\n\n    def _sign_ws_params(self, params, signature_func):\n        if \"signature\" in params:\n            return params\n        params.setdefault(\"apiKey\", self.API_KEY)\n        params.setdefault(\"timestamp\", int(time.time() * 1000 + self.timestamp_offset))\n        params = dict(sorted(params.items()))\n        return {**params, \"signature\": signature_func(params)}\n\n    def _generate_ws_api_signature(self, data: Dict) -> str:\n        sig_func = self._hmac_signature\n        if self.PRIVATE_KEY:\n            if self._is_rsa:\n                sig_func = self._rsa_signature\n            else:\n                sig_func = self._ed25519_signature\n        query_string = urlencode(data)\n        return sig_func(query_string)\n\n    async def _ws_futures_api_request(self, method: str, signed: bool, params: dict):\n        \"\"\"Send request and wait for response\"\"\"\n        id = params.pop(\"id\", self.uuid22())\n        payload = {\n            \"id\": id,\n            \"method\": method,\n            \"params\": params,\n        }\n        if signed:\n            payload[\"params\"] = self._sign_ws_params(params, self._generate_signature)\n        return await self.ws_future.request(id, payload)\n\n    def _ws_futures_api_request_sync(self, method: str, signed: bool, params: dict):\n        self.loop = get_loop()\n        return self.loop.run_until_complete(\n            self._ws_futures_api_request(method, signed, params)\n        )\n\n    async def _make_sync(self, method):\n        return asyncio.run(method)\n\n    async def _ws_api_request(self, method: str, signed: bool, params: dict):\n        \"\"\"Send request and wait for response\"\"\"\n        id = params.pop(\"id\", self.uuid22())\n        payload = {\n            \"id\": id,\n            \"method\": method,\n            \"params\": params,\n        }\n        if signed:\n            payload[\"params\"] = self._sign_ws_params(\n                params, self._generate_ws_api_signature\n            )\n        return await self.ws_api.request(id, payload)\n\n    def _ws_api_request_sync(self, method: str, signed: bool, params: dict):\n        \"\"\"Send request to WS API and wait for response\"\"\"\n        self.loop = get_loop()\n        return self.loop.run_until_complete(\n            self._ws_api_request(method, signed, params)\n        )\n\n    @staticmethod\n    def _get_version(version: int, **kwargs) -> int:\n        if \"data\" in kwargs and \"version\" in kwargs[\"data\"]:\n            version_override = kwargs[\"data\"].get(\"version\")\n            del kwargs[\"data\"][\"version\"]\n            return version_override\n        return version\n\n    @staticmethod\n    def uuid22(length=22):\n        return format(random.getrandbits(length * 4), \"x\")\n\n    @staticmethod\n    def _order_params(data: Dict) -> List[Tuple[str, str]]:\n        \"\"\"Convert params to list with signature as last element\n\n        :param data:\n        :return:\n\n        \"\"\"\n        data = dict(filter(lambda el: el[1] is not None, data.items()))\n        has_signature = False\n        params = []\n        for key, value in data.items():\n            if key == \"signature\":\n                has_signature = True\n            else:\n                params.append((key, str(value)))\n        # sort parameters by key\n        params.sort(key=itemgetter(0))\n        if has_signature:\n            params.append((\"signature\", data[\"signature\"]))\n        return params\n\n    def _get_request_kwargs(\n        self, method, signed: bool, force_params: bool = False, **kwargs\n    ) -> Dict:\n        # set default requests timeout\n        kwargs[\"timeout\"] = self.REQUEST_TIMEOUT\n\n        # add our global requests params\n        if self._requests_params:\n            kwargs.update(self._requests_params)\n\n        data = kwargs.get(\"data\", None)\n        if data and isinstance(data, dict):\n            kwargs[\"data\"] = data\n            # find any requests params passed and apply them\n            if \"requests_params\" in kwargs[\"data\"]:\n                # merge requests params into kwargs\n                kwargs.update(kwargs[\"data\"][\"requests_params\"])\n                del kwargs[\"data\"][\"requests_params\"]\n\n        if signed:\n            # generate signature\n            kwargs[\"data\"][\"timestamp\"] = int(\n                time.time() * 1000 + self.timestamp_offset\n            )\n            if self.REQUEST_RECVWINDOW:\n                kwargs[\"data\"][\"recvWindow\"] = self.REQUEST_RECVWINDOW\n            kwargs[\"data\"][\"signature\"] = self._generate_signature(kwargs[\"data\"])\n\n        # sort get and post params to match signature order\n        if data:\n            # sort post params and remove any arguments with values of None\n            kwargs[\"data\"] = self._order_params(kwargs[\"data\"])\n            # Remove any arguments with values of None.\n            null_args = [\n                i for i, (key, value) in enumerate(kwargs[\"data\"]) if value is None\n            ]\n            for i in reversed(null_args):\n                del kwargs[\"data\"][i]\n\n        # if get request assign data array to params value for requests lib\n        if data and (method == \"get\" or force_params):\n            kwargs[\"params\"] = \"&\".join(\n                \"%s=%s\" % (data[0], _urlencode.quote(data[1]) if data[0] == 'symbol' else data[1]) for data in kwargs[\"data\"]\n            )\n            del kwargs[\"data\"]\n\n        # Temporary fix for Signature issue while using batchOrders in AsyncClient\n        if \"params\" in kwargs.keys():\n            if (\n                \"batchOrders\" in kwargs[\"params\"]\n                or \"orderidlist\" in kwargs[\"params\"]\n                or \"origclientorderidlist\" in kwargs[\"params\"]\n            ):\n                kwargs[\"data\"] = kwargs[\"params\"]\n                del kwargs[\"params\"]\n\n        return kwargs\n"
  },
  {
    "path": "binance/client.py",
    "content": "from pathlib import Path\nfrom typing import Dict, Optional, List, Union, Any\n\nimport requests\nimport time\nimport warnings\nfrom urllib.parse import urlencode, quote\n\nfrom .base_client import BaseClient\n\nfrom .helpers import (\n    convert_list_to_json_array,\n    interval_to_milliseconds,\n    convert_ts_str,\n)\nfrom .exceptions import (\n    BinanceAPIException,\n    BinanceRequestException,\n    NotImplementedException,\n)\nfrom .enums import HistoricalKlinesType\n\n\nclass Client(BaseClient):\n    def __init__(\n        self,\n        api_key: Optional[str] = None,\n        api_secret: Optional[str] = None,\n        requests_params: Optional[Dict[str, Any]] = None,\n        tld: str = \"com\",\n        base_endpoint: str = BaseClient.BASE_ENDPOINT_DEFAULT,\n        testnet: bool = False,\n        demo: bool = False,\n        private_key: Optional[Union[str, Path]] = None,\n        private_key_pass: Optional[str] = None,\n        ping: Optional[bool] = True,\n        time_unit: Optional[str] = None,\n        verbose: bool = False,\n    ):\n        super().__init__(\n            api_key,\n            api_secret,\n            requests_params,\n            tld,\n            base_endpoint,\n            testnet,\n            demo,\n            private_key,\n            private_key_pass,\n            time_unit=time_unit,\n            verbose=verbose,\n        )\n\n        # init DNS and SSL cert\n        if ping:\n            self.ping()\n\n    def _init_session(self) -> requests.Session:\n        headers = self._get_headers()\n\n        session = requests.session()\n        session.headers.update(headers)\n        return session\n\n    def _request(\n        self, method, uri: str, signed: bool, force_params: bool = False, **kwargs\n    ):\n        headers = {}\n        if method.upper() in [\"POST\", \"PUT\", \"DELETE\"]:\n            headers.update({\"Content-Type\": \"application/x-www-form-urlencoded\"})\n\n        if \"data\" in kwargs:\n            for key in kwargs[\"data\"]:\n                if key == \"headers\":\n                    headers.update(kwargs[\"data\"][key])\n                    del kwargs[\"data\"][key]\n                    break\n\n        kwargs = self._get_request_kwargs(method, signed, force_params, **kwargs)\n\n        data = kwargs.get(\"data\")\n        if data is not None:\n            del kwargs[\"data\"]\n\n        if signed and self.PRIVATE_KEY and data: # handle issues with signing using eddsa/rsa and POST requests\n            dict_data = Client.convert_to_dict(data)\n            signature = dict_data[\"signature\"] if \"signature\" in dict_data else  None\n            if signature:\n                del dict_data[\"signature\"]\n            url_encoded_data = urlencode(dict_data)\n            data = f\"{url_encoded_data}&signature={signature}\"\n\n        self.response = getattr(self.session, method)(uri, headers=headers, data=data, **kwargs)\n\n        if self.verbose:\n            self.logger.debug(\n                \"\\nRequest: %s %s\\nRequestHeaders: %s\\nRequestBody: %s\\nResponse: %s\\nResponseHeaders: %s\\nResponseBody: %s\",\n                method.upper(),\n                uri,\n                headers,\n                data,\n                self.response.status_code,\n                dict(self.response.headers),\n                self.response.text[:1000] if self.response.text else None\n            )\n\n        return self._handle_response(self.response)\n\n    @staticmethod\n    def _handle_response(response: requests.Response):\n        \"\"\"Internal helper for handling API responses from the Binance server.\n        Raises the appropriate exceptions when necessary; otherwise, returns the\n        response.\n        \"\"\"\n        if not (200 <= response.status_code < 300):\n            raise BinanceAPIException(response, response.status_code, response.text)\n\n        if response.text == \"\":\n            return {}\n\n        try:\n            return response.json()\n        except ValueError:\n            raise BinanceRequestException(\"Invalid Response: %s\" % response.text)\n\n    def _request_api(\n        self,\n        method,\n        path: str,\n        signed: bool = False,\n        version=BaseClient.PUBLIC_API_VERSION,\n        **kwargs,\n    ):\n        uri = self._create_api_uri(path, signed, version)\n        return self._request(method, uri, signed, **kwargs)\n\n    def _request_futures_api(\n        self, method, path, signed=False, version: int = 1, **kwargs\n    ) -> Dict:\n        version = self._get_version(version, **kwargs)\n        uri = self._create_futures_api_uri(path, version)\n        force_params = kwargs.pop(\"force_params\", False)\n\n        return self._request(method, uri, signed, force_params, **kwargs)\n\n    def _request_futures_data_api(self, method, path, signed=False, **kwargs) -> Dict:\n        uri = self._create_futures_data_api_uri(path)\n\n        force_params = kwargs.pop(\"force_params\", True)\n        return self._request(method, uri, signed, force_params, **kwargs)\n\n    def _request_futures_coin_api(\n        self, method, path, signed=False, version=1, **kwargs\n    ) -> Dict:\n        version = self._get_version(version, **kwargs)\n        uri = self._create_futures_coin_api_url(path, version=version)\n\n        force_params = kwargs.pop(\"force_params\", False)\n        return self._request(method, uri, signed, force_params, **kwargs)\n\n    def _request_futures_coin_data_api(\n        self, method, path, signed=False, version=1, **kwargs\n    ) -> Dict:\n        version = self._get_version(version, **kwargs)\n        uri = self._create_futures_coin_data_api_url(path, version=version)\n\n        force_params = kwargs.pop(\"force_params\", True)\n        return self._request(method, uri, signed, force_params, **kwargs)\n\n    def _request_options_api(self, method, path, signed=False, **kwargs) -> Dict:\n        \"\"\"\n        https://developers.binance.com/docs/derivatives/option/market-data\n        \"\"\"\n        uri = self._create_options_api_uri(path)\n\n        force_params = kwargs.pop(\"force_params\", True)\n        return self._request(method, uri, signed, force_params, **kwargs)\n\n    def _request_margin_api(\n        self, method, path, signed=False, version=1, **kwargs\n    ) -> Dict:\n        version = self._get_version(version, **kwargs)\n        uri = self._create_margin_api_uri(path, version)\n\n        force_params = kwargs.pop(\"force_params\", False)\n        return self._request(method, uri, signed, force_params, **kwargs)\n\n    def _request_papi_api(\n        self, method, path, signed=False, version=1, **kwargs\n    ) -> Dict:\n        version = self._get_version(version, **kwargs)\n        uri = self._create_papi_api_uri(path, version)\n        force_params = kwargs.pop(\"force_params\", False)\n        return self._request(method, uri, signed, force_params, **kwargs)\n\n    def _request_website(self, method, path, signed=False, **kwargs) -> Dict:\n        uri = self._create_website_uri(path)\n        return self._request(method, uri, signed, **kwargs)\n\n    def _get(self, path, signed=False, version=BaseClient.PUBLIC_API_VERSION, **kwargs):\n        return self._request_api(\"get\", path, signed, version, **kwargs)\n\n    def _post(\n        self, path, signed=False, version=BaseClient.PUBLIC_API_VERSION, **kwargs\n    ) -> Dict:\n        return self._request_api(\"post\", path, signed, version, **kwargs)\n\n    def _put(\n        self, path, signed=False, version=BaseClient.PUBLIC_API_VERSION, **kwargs\n    ) -> Dict:\n        return self._request_api(\"put\", path, signed, version, **kwargs)\n\n    def _delete(\n        self, path, signed=False, version=BaseClient.PUBLIC_API_VERSION, **kwargs\n    ) -> Dict:\n        return self._request_api(\"delete\", path, signed, version, **kwargs)\n\n    # Exchange Endpoints\n\n    def get_products(self) -> Dict:\n        \"\"\"Return list of products currently listed on Binance\n\n        Use get_exchange_info() call instead\n\n        :returns: list - List of product dictionaries\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        products = self._request_website(\n            \"get\",\n            \"bapi/asset/v2/public/asset-service/product/get-products?includeEtf=true\",\n        )\n        return products\n\n    def get_exchange_info(self) -> Dict:\n        \"\"\"Return rate limits and list of symbols\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/general-endpoints#exchange-information\n\n        :returns: list - List of product dictionaries\n\n        .. code-block:: python\n\n            {\n                \"timezone\": \"UTC\",\n                \"serverTime\": 1508631584636,\n                \"rateLimits\": [\n                    {\n                        \"rateLimitType\": \"REQUESTS\",\n                        \"interval\": \"MINUTE\",\n                        \"limit\": 1200\n                    },\n                    {\n                        \"rateLimitType\": \"ORDERS\",\n                        \"interval\": \"SECOND\",\n                        \"limit\": 10\n                    },\n                    {\n                        \"rateLimitType\": \"ORDERS\",\n                        \"interval\": \"DAY\",\n                        \"limit\": 100000\n                    }\n                ],\n                \"exchangeFilters\": [],\n                \"symbols\": [\n                    {\n                        \"symbol\": \"ETHBTC\",\n                        \"status\": \"TRADING\",\n                        \"baseAsset\": \"ETH\",\n                        \"baseAssetPrecision\": 8,\n                        \"quoteAsset\": \"BTC\",\n                        \"quotePrecision\": 8,\n                        \"orderTypes\": [\"LIMIT\", \"MARKET\"],\n                        \"icebergAllowed\": false,\n                        \"filters\": [\n                            {\n                                \"filterType\": \"PRICE_FILTER\",\n                                \"minPrice\": \"0.00000100\",\n                                \"maxPrice\": \"100000.00000000\",\n                                \"tickSize\": \"0.00000100\"\n                            }, {\n                                \"filterType\": \"LOT_SIZE\",\n                                \"minQty\": \"0.00100000\",\n                                \"maxQty\": \"100000.00000000\",\n                                \"stepSize\": \"0.00100000\"\n                            }, {\n                                \"filterType\": \"MIN_NOTIONAL\",\n                                \"minNotional\": \"0.00100000\"\n                            }\n                        ]\n                    }\n                ]\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n\n        return self._get(\"exchangeInfo\")\n\n    def get_symbol_info(self, symbol) -> Optional[Dict]:\n        \"\"\"Return information about a symbol\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/general-endpoints#exchange-information\n\n        :param symbol: required e.g. BNBBTC\n        :type symbol: str\n\n        :returns: Dict if found, None if not\n\n        .. code-block:: python\n\n            {\n                \"symbol\": \"ETHBTC\",\n                \"status\": \"TRADING\",\n                \"baseAsset\": \"ETH\",\n                \"baseAssetPrecision\": 8,\n                \"quoteAsset\": \"BTC\",\n                \"quotePrecision\": 8,\n                \"orderTypes\": [\"LIMIT\", \"MARKET\"],\n                \"icebergAllowed\": false,\n                \"filters\": [\n                    {\n                        \"filterType\": \"PRICE_FILTER\",\n                        \"minPrice\": \"0.00000100\",\n                        \"maxPrice\": \"100000.00000000\",\n                        \"tickSize\": \"0.00000100\"\n                    }, {\n                        \"filterType\": \"LOT_SIZE\",\n                        \"minQty\": \"0.00100000\",\n                        \"maxQty\": \"100000.00000000\",\n                        \"stepSize\": \"0.00100000\"\n                    }, {\n                        \"filterType\": \"MIN_NOTIONAL\",\n                        \"minNotional\": \"0.00100000\"\n                    }\n                ]\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n\n        res = self.get_exchange_info()\n\n        for item in res[\"symbols\"]:\n            if item[\"symbol\"] == symbol.upper():\n                return item\n\n        return None\n\n    # General Endpoints\n\n    def ping(self) -> Dict:\n        \"\"\"Test connectivity to the Rest API.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/general-endpoints#test-connectivity\n\n        :returns: Empty array\n\n        .. code-block:: python\n\n            {}\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._get(\"ping\")\n\n    def get_server_time(self) -> Dict:\n        \"\"\"Test connectivity to the Rest API and get the current server time.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/general-endpoints#check-server-time\n\n        :returns: Current server time\n\n        .. code-block:: python\n\n            {\n                \"serverTime\": 1499827319559\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._get(\"time\")\n\n    # Market Data Endpoints\n\n    def get_all_tickers(self) -> List[Dict[str, str]]:\n        \"\"\"Latest price for all symbols.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/market-data-endpoints#symbol-price-ticker\n\n        :returns: List of market tickers\n\n        .. code-block:: python\n\n            [\n                {\n                    \"symbol\": \"LTCBTC\",\n                    \"price\": \"4.00000200\"\n                },\n                {\n                    \"symbol\": \"ETHBTC\",\n                    \"price\": \"0.07946600\"\n                }\n            ]\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        response = self._get(\"ticker/price\")\n        if isinstance(response, list) and all(isinstance(item, dict) for item in response):\n            return response\n        raise TypeError(\"Expected a list of dictionaries\")\n\n    def get_orderbook_tickers(self, **params) -> Dict:\n        \"\"\"Best price/qty on the order book for all symbols.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/market-data-endpoints#symbol-order-book-ticker\n\n        :param symbol: optional\n        :type symbol: str\n        :param symbols: optional accepted format  [\"BTCUSDT\",\"BNBUSDT\"] or %5B%22BTCUSDT%22,%22BNBUSDT%22%5D\n        :type symbols: str\n\n        :returns: List of order book market entries\n\n        .. code-block:: python\n\n            [\n                {\n                    \"symbol\": \"LTCBTC\",\n                    \"bidPrice\": \"4.00000000\",\n                    \"bidQty\": \"431.00000000\",\n                    \"askPrice\": \"4.00000200\",\n                    \"askQty\": \"9.00000000\"\n                },\n                {\n                    \"symbol\": \"ETHBTC\",\n                    \"bidPrice\": \"0.07946700\",\n                    \"bidQty\": \"9.00000000\",\n                    \"askPrice\": \"100000.00000000\",\n                    \"askQty\": \"1000.00000000\"\n                }\n            ]\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        data = {}\n        if \"symbol\" in params:\n            data[\"symbol\"] = params[\"symbol\"]\n        elif \"symbols\" in params:\n            data[\"symbols\"] = params[\"symbols\"]\n        return self._get(\n            \"ticker/bookTicker\", data=data\n        )\n\n    def get_order_book(self, **params) -> Dict:\n        \"\"\"Get the Order Book for the market\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/market-data-endpoints#order-book\n\n        :param symbol: required\n        :type symbol: str\n        :param limit:  Default 100; max 1000\n        :type limit: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"lastUpdateId\": 1027024,\n                \"bids\": [\n                    [\n                        \"4.00000000\",     # PRICE\n                        \"431.00000000\",   # QTY\n                        []                # Can be ignored\n                    ]\n                ],\n                \"asks\": [\n                    [\n                        \"4.00000200\",\n                        \"12.00000000\",\n                        []\n                    ]\n                ]\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._get(\"depth\", data=params)\n\n    def get_recent_trades(self, **params) -> Dict:\n        \"\"\"Get recent trades (up to last 500).\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/market-data-endpoints#recent-trades-list\n\n        :param symbol: required\n        :type symbol: str\n        :param limit:  Default 500; max 1000.\n        :type limit: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            [\n                {\n                    \"id\": 28457,\n                    \"price\": \"4.00000100\",\n                    \"qty\": \"12.00000000\",\n                    \"time\": 1499865549590,\n                    \"isBuyerMaker\": true,\n                    \"isBestMatch\": true\n                }\n            ]\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._get(\"trades\", data=params)\n\n    def get_historical_trades(self, **params) -> Dict:\n        \"\"\"Get older trades.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/market-data-endpoints#old-trade-lookup\n\n        :param symbol: required\n        :type symbol: str\n        :param limit:  Default 500; max 1000.\n        :type limit: int\n        :param fromId:  TradeId to fetch from. Default gets most recent trades.\n        :type fromId: str\n\n        :returns: API response\n\n        .. code-block:: python\n\n            [\n                {\n                    \"id\": 28457,\n                    \"price\": \"4.00000100\",\n                    \"qty\": \"12.00000000\",\n                    \"time\": 1499865549590,\n                    \"isBuyerMaker\": true,\n                    \"isBestMatch\": true\n                }\n            ]\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._get(\n            \"historicalTrades\", data=params\n        )\n\n    def get_aggregate_trades(self, **params) -> Dict:\n        \"\"\"Get compressed, aggregate trades. Trades that fill at the time,\n        from the same order, with the same price will have the quantity aggregated.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/market-data-endpoints#compressedaggregate-trades-list\n\n        :param symbol: required\n        :type symbol: str\n        :param fromId:  ID to get aggregate trades from INCLUSIVE.\n        :type fromId: str\n        :param startTime: Timestamp in ms to get aggregate trades from INCLUSIVE.\n        :type startTime: int\n        :param endTime: Timestamp in ms to get aggregate trades until INCLUSIVE.\n        :type endTime: int\n        :param limit:  Default 500; max 1000.\n        :type limit: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            [\n                {\n                    \"a\": 26129,         # Aggregate tradeId\n                    \"p\": \"0.01633102\",  # Price\n                    \"q\": \"4.70443515\",  # Quantity\n                    \"f\": 27781,         # First tradeId\n                    \"l\": 27781,         # Last tradeId\n                    \"T\": 1498793709153, # Timestamp\n                    \"m\": true,          # Was the buyer the maker?\n                    \"M\": true           # Was the trade the best price match?\n                }\n            ]\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._get(\"aggTrades\", data=params)\n\n    def aggregate_trade_iter(self, symbol: str, start_str=None, last_id=None):\n        \"\"\"Iterate over aggregate trade data from (start_time or last_id) to\n        the end of the history so far.\n\n        If start_time is specified, start with the first trade after\n        start_time. Meant to initialise a local cache of trade data.\n\n        If last_id is specified, start with the trade after it. This is meant\n        for updating a pre-existing local trade data cache.\n\n        Only allows start_str or last_id—not both. Not guaranteed to work\n        right if you're running more than one of these simultaneously. You\n        will probably hit your rate limit.\n\n        See dateparser docs for valid start and end string formats http://dateparser.readthedocs.io/en/latest/\n\n        If using offset strings for dates add \"UTC\" to date string e.g. \"now UTC\", \"11 hours ago UTC\"\n\n        :param symbol: Symbol string e.g. ETHBTC\n        :type symbol: str\n        :param start_str: Start date string in UTC format or timestamp in milliseconds. The iterator will\n        return the first trade occurring later than this time.\n        :type start_str: str|int\n        :param last_id: aggregate trade ID of the last known aggregate trade.\n        Not a regular trade ID. See https://binance-docs.github.io/apidocs/spot/en/#compressed-aggregate-trades-list\n\n        :returns: an iterator of JSON objects, one per trade. The format of\n        each object is identical to Client.aggregate_trades().\n\n        :type last_id: int\n        \"\"\"\n        if start_str is not None and last_id is not None:\n            raise ValueError(\n                \"start_time and last_id may not be simultaneously specified.\"\n            )\n\n        # If there's no last_id, get one.\n        if last_id is None:\n            # Without a last_id, we actually need the first trade.  Normally,\n            # we'd get rid of it. See the next loop.\n            if start_str is None:\n                trades = self.get_aggregate_trades(symbol=symbol, fromId=0)\n            else:\n                # The difference between startTime and endTime should be less\n                # or equal than an hour and the result set should contain at\n                # least one trade.\n                start_ts = convert_ts_str(start_str)\n                # If the resulting set is empty (i.e. no trades in that interval)\n                # then we just move forward hour by hour until we find at least one\n                # trade or reach present moment\n                while True:\n                    end_ts = start_ts + (60 * 60 * 1000)\n                    trades = self.get_aggregate_trades(\n                        symbol=symbol, startTime=start_ts, endTime=end_ts\n                    )\n                    if len(trades) > 0:\n                        break\n                    # If we reach present moment and find no trades then there is\n                    # nothing to iterate, so we're done\n                    if end_ts > int(time.time() * 1000):\n                        return\n                    start_ts = end_ts\n            for t in trades:\n                yield t\n            last_id = trades[-1][self.AGG_ID]\n\n        while True:\n            # There is no need to wait between queries, to avoid hitting the\n            # rate limit. We're using blocking IO, and as long as we're the\n            # only thread running calls like this, Binance will automatically\n            # add the right delay time on their end, forcing us to wait for\n            # data. That really simplifies this function's job. Binance is\n            # fucking awesome.\n            trades = self.get_aggregate_trades(symbol=symbol, fromId=last_id)\n            # fromId=n returns a set starting with id n, but we already have\n            # that one. So get rid of the first item in the result set.\n            trades = trades[1:]\n            if len(trades) == 0:\n                return\n            for t in trades:\n                yield t\n            last_id = trades[-1][self.AGG_ID]\n\n    def get_ui_klines(self, **params) -> Dict:\n        \"\"\"Kline/candlestick bars for a symbol with UI enhancements. Klines are uniquely identified by their open time.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/market-data-endpoints#uiklines\n\n        :param symbol: required\n        :type symbol: str\n        :param interval: required - The interval for the klines (e.g., 1m, 3m, 5m, etc.)\n        :type interval: str\n        :param limit: optional - Default 500; max 1000.\n        :type limit: int\n        :param startTime: optional - Start time in milliseconds\n        :type startTime: int\n        :param endTime: optional - End time in milliseconds\n        :type endTime: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            [\n                [\n                    1499040000000,      # Open time\n                    \"0.01634790\",       # Open\n                    \"0.80000000\",       # High\n                    \"0.01575800\",       # Low\n                    \"0.01577100\",       # Close\n                    \"148976.11427815\",  # Volume\n                    1499644799999,      # Close time\n                    \"2434.19055334\",    # Quote asset volume\n                    308,                # Number of trades\n                    \"1756.87402397\",    # Taker buy base asset volume\n                    \"28.46694368\",      # Taker buy quote asset volume\n                    \"17928899.62484339\" # Can be ignored\n                ]\n            ]\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._get(\"uiKlines\", data=params)\n\n    def get_klines(self, **params) -> Dict:\n        \"\"\"Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/market-data-endpoints#klinecandlestick-data\n\n        :param symbol: required\n        :type symbol: str\n        :param interval: -\n        :type interval: str\n        :param limit: - Default 500; max 1000.\n        :type limit: int\n        :param startTime:\n        :type startTime: int\n        :param endTime:\n        :type endTime: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            [\n                [\n                    1499040000000,      # Open time\n                    \"0.01634790\",       # Open\n                    \"0.80000000\",       # High\n                    \"0.01575800\",       # Low\n                    \"0.01577100\",       # Close\n                    \"148976.11427815\",  # Volume\n                    1499644799999,      # Close time\n                    \"2434.19055334\",    # Quote asset volume\n                    308,                # Number of trades\n                    \"1756.87402397\",    # Taker buy base asset volume\n                    \"28.46694368\",      # Taker buy quote asset volume\n                    \"17928899.62484339\" # Can be ignored\n                ]\n            ]\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._get(\"klines\", data=params)\n\n    def _klines(\n        self, klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT, **params\n    ) -> Dict:\n        \"\"\"Get klines of spot (get_klines) or futures (futures_klines) endpoints.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/market-data-endpoints#klinecandlestick-data\n        https://developers.binance.com/docs/derivatives/option/market-data/Kline-Candlestick-Data\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Kline-Candlestick-Data\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Index-Price-Kline-Candlestick-Data\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Mark-Price-Kline-Candlestick-Data\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Premium-Index-Kline-Data\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api/Kline-Candlestick-Data\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api/Index-Price-Kline-Candlestick-Data\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api/Mark-Price-Kline-Candlestick-Data\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api/Premium-Index-Kline-Data\n\n        :param klines_type: Historical klines type: SPOT or FUTURES\n        :type klines_type: HistoricalKlinesType\n\n        :return: klines, see get_klines\n\n        \"\"\"\n        if \"endTime\" in params and not params[\"endTime\"]:\n            del params[\"endTime\"]\n\n        if HistoricalKlinesType.SPOT == klines_type:\n            return self.get_klines(**params)\n        elif HistoricalKlinesType.FUTURES == klines_type:\n            return self.futures_klines(**params)\n        elif HistoricalKlinesType.FUTURES_COIN == klines_type:\n            return self.futures_coin_klines(**params)\n        elif HistoricalKlinesType.FUTURES_MARK_PRICE == klines_type:\n            return self.futures_mark_price_klines(**params)\n        elif HistoricalKlinesType.FUTURES_INDEX_PRICE == klines_type:\n            return self.futures_index_price_klines(**params)\n        elif HistoricalKlinesType.FUTURES_COIN_MARK_PRICE == klines_type:\n            return self.futures_coin_mark_price_klines(**params)\n        elif HistoricalKlinesType.FUTURES_COIN_INDEX_PRICE == klines_type:\n            return self.futures_coin_index_price_klines(**params)\n        else:\n            raise NotImplementedException(klines_type)\n\n    def _get_earliest_valid_timestamp(\n        self,\n        symbol,\n        interval,\n        klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT,\n    ):\n        \"\"\"Get the earliest valid open timestamp from Binance\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/market-data-endpoints#klinecandlestick-data\n        https://developers.binance.com/docs/derivatives/option/market-data/Kline-Candlestick-Data\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Kline-Candlestick-Data\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Index-Price-Kline-Candlestick-Data\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Mark-Price-Kline-Candlestick-Data\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Premium-Index-Kline-Data\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api/Kline-Candlestick-Data\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api/Index-Price-Kline-Candlestick-Data\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api/Mark-Price-Kline-Candlestick-Data\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api/Premium-Index-Kline-Data\n\n        :param symbol: Name of symbol pair e.g. BNBBTC\n        :type symbol: str\n        :param interval: Binance Kline interval\n        :type interval: str\n        :param klines_type: Historical klines type: SPOT or FUTURES\n        :type klines_type: HistoricalKlinesType\n\n        :return: first valid timestamp\n\n        \"\"\"\n        kline = self._klines(\n            klines_type=klines_type,\n            symbol=symbol,\n            interval=interval,\n            limit=1,\n            startTime=0,\n            endTime=int(time.time() * 1000),\n        )\n        return kline[0][0]\n\n    def get_historical_klines(\n        self,\n        symbol,\n        interval,\n        start_str=None,\n        end_str=None,\n        limit=None,\n        klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT,\n    ):\n        \"\"\"Get Historical Klines from Binance\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/market-data-endpoints#klinecandlestick-data\n        https://developers.binance.com/docs/derivatives/option/market-data/Kline-Candlestick-Data\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Kline-Candlestick-Data\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Index-Price-Kline-Candlestick-Data\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Mark-Price-Kline-Candlestick-Data\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Premium-Index-Kline-Data\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api/Kline-Candlestick-Data\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api/Index-Price-Kline-Candlestick-Data\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api/Mark-Price-Kline-Candlestick-Data\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api/Premium-Index-Kline-Data\n\n        :param symbol: Name of symbol pair e.g. BNBBTC\n        :type symbol: str\n        :param interval: Binance Kline interval\n        :type interval: str\n        :param start_str: optional - start date string in UTC format or timestamp in milliseconds\n        :type start_str: str|int\n        :param end_str: optional - end date string in UTC format or timestamp in milliseconds (default will fetch everything up to now)\n        :type end_str: str|int\n        :param limit: Default 1000; max 1000.\n        :type limit: int\n        :param klines_type: Historical klines type: SPOT or FUTURES\n        :type klines_type: HistoricalKlinesType\n\n        :return: list of OHLCV values (Open time, Open, High, Low, Close, Volume, Close time, Quote asset volume, Number of trades, Taker buy base asset volume, Taker buy quote asset volume, Ignore)\n\n        \"\"\"\n        return self._historical_klines(\n            symbol,\n            interval,\n            start_str=start_str,\n            end_str=end_str,\n            limit=limit,\n            klines_type=klines_type,\n        )\n\n    def _historical_klines(\n        self,\n        symbol,\n        interval,\n        start_str=None,\n        end_str=None,\n        limit=None,\n        klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT,\n    ):\n        \"\"\"Get Historical Klines from Binance (spot or futures)\n\n        See dateparser docs for valid start and end string formats https://dateparser.readthedocs.io/en/latest/\n\n        If using offset strings for dates add \"UTC\" to date string e.g. \"now UTC\", \"11 hours ago UTC\"\n\n        :param symbol: Name of symbol pair e.g. BNBBTC\n        :type symbol: str\n        :param interval: Binance Kline interval\n        :type interval: str\n        :param start_str: optional - start date string in UTC format or timestamp in milliseconds\n        :type start_str: str|int\n        :param end_str: optional - end date string in UTC format or timestamp in milliseconds (default will fetch everything up to now)\n        :type end_str: None|str|int\n        :param limit: Default 1000; max 1000.\n        :type limit: int\n        :param klines_type: Historical klines type: SPOT or FUTURES\n        :type klines_type: HistoricalKlinesType\n\n        :return: list of OHLCV values (Open time, Open, High, Low, Close, Volume, Close time, Quote asset volume, Number of trades, Taker buy base asset volume, Taker buy quote asset volume, Ignore)\n\n        \"\"\"\n\n        initial_limit_set = True\n        if limit is None:\n            limit = 1000\n            initial_limit_set = False\n\n        # init our list\n        output_data = []\n\n        # convert interval to useful value in seconds\n        timeframe = interval_to_milliseconds(interval)\n\n        # if a start time was passed convert it\n        start_ts = convert_ts_str(start_str)\n\n        # establish first available start timestamp\n        if start_ts is not None:\n            first_valid_ts = self._get_earliest_valid_timestamp(\n                symbol, interval, klines_type\n            )\n            start_ts = max(start_ts, first_valid_ts)\n\n        # if an end time was passed convert it\n        end_ts = convert_ts_str(end_str)\n        if end_ts and start_ts and end_ts <= start_ts:\n            return output_data\n\n        idx = 0\n        while True:\n            # fetch the klines from start_ts up to max 500 entries or the end_ts if set\n            temp_data = self._klines(\n                klines_type=klines_type,\n                symbol=symbol,\n                interval=interval,\n                limit=limit,\n                startTime=start_ts,\n                endTime=end_ts,\n            )\n\n            # append this loops data to our output data\n            if temp_data:\n                output_data += temp_data\n\n            # check if output_data is greater than limit and truncate if needed and break loop\n            if initial_limit_set and len(output_data) > limit:\n                output_data = output_data[:limit]\n                break\n\n            # handle the case where exactly the limit amount of data was returned last loop\n            # check if we received less than the required limit and exit the loop\n            if not len(temp_data) or len(temp_data) < limit:\n                # exit the while loop\n                break\n\n            # increment next call by our timeframe\n            start_ts = temp_data[-1][0] + timeframe\n\n            # exit loop if we reached end_ts before reaching <limit> klines\n            if end_ts and start_ts >= end_ts:\n                break\n\n            # sleep after every 3rd call to be kind to the API\n            idx += 1\n            if idx % 3 == 0:\n                time.sleep(1)\n\n        return output_data\n\n    def get_historical_klines_generator(\n        self,\n        symbol,\n        interval,\n        start_str=None,\n        end_str=None,\n        limit=None,\n        klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT,\n    ):\n        \"\"\"Get Historical Klines generator from Binance\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/market-data-endpoints#klinecandlestick-data\n        https://developers.binance.com/docs/derivatives/option/market-data/Kline-Candlestick-Data\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Kline-Candlestick-Data\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Index-Price-Kline-Candlestick-Data\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Mark-Price-Kline-Candlestick-Data\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Premium-Index-Kline-Data\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api/Kline-Candlestick-Data\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api/Index-Price-Kline-Candlestick-Data\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api/Mark-Price-Kline-Candlestick-Data\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api/Premium-Index-Kline-Data\n\n        :param symbol: Name of symbol pair e.g. BNBBTC\n        :type symbol: str\n        :param interval: Binance Kline interval\n        :type interval: str\n        :param start_str: optional - Start date string in UTC format or timestamp in milliseconds\n        :type start_str: str|int\n        :param end_str: optional - end date string in UTC format or timestamp in milliseconds (default will fetch everything up to now)\n        :type end_str: str|int\n        :param limit: amount of candles to return per request (default 1000)\n        :type limit: int\n        :param klines_type: Historical klines type: SPOT or FUTURES\n        :type klines_type: HistoricalKlinesType\n\n        :return: generator of OHLCV values\n\n        \"\"\"\n\n        return self._historical_klines_generator(\n            symbol, interval, start_str, end_str, limit, klines_type=klines_type\n        )\n\n    def _historical_klines_generator(\n        self,\n        symbol,\n        interval,\n        start_str=None,\n        end_str=None,\n        limit=None,\n        klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT,\n    ):\n        \"\"\"Get Historical Klines generator from Binance (spot or futures)\n\n        See dateparser docs for valid start and end string formats https://dateparser.readthedocs.io/en/latest/\n\n        If using offset strings for dates add \"UTC\" to date string e.g. \"now UTC\", \"11 hours ago UTC\"\n\n        :param symbol: Name of symbol pair e.g. BNBBTC\n        :type symbol: str\n        :param interval: Binance Kline interval\n        :type interval: str\n        :param start_str: optional - Start date string in UTC format or timestamp in milliseconds\n        :type start_str: str|int\n        :param end_str: optional - end date string in UTC format or timestamp in milliseconds (default will fetch everything up to now)\n        :type end_str: str|int\n        :param klines_type: Historical klines type: SPOT or FUTURES\n        :type klines_type: HistoricalKlinesType\n\n        :return: generator of OHLCV values\n\n        \"\"\"\n\n        initial_limit_set = True\n        if limit is None:\n            limit = 1000\n            initial_limit_set = False\n\n        # convert interval to useful value in seconds\n        timeframe = interval_to_milliseconds(interval)\n\n        # if a start time was passed convert it\n        start_ts = convert_ts_str(start_str)\n\n        # establish first available start timestamp\n        if start_ts is not None:\n            first_valid_ts = self._get_earliest_valid_timestamp(\n                symbol, interval, klines_type\n            )\n            start_ts = max(start_ts, first_valid_ts)\n\n        # if an end time was passed convert it\n        end_ts = convert_ts_str(end_str)\n        if end_ts and start_ts and end_ts <= start_ts:\n            return\n\n        idx = 0\n        while True:\n            # fetch the klines from start_ts up to max 500 entries or the end_ts if set\n            output_data = self._klines(\n                klines_type=klines_type,\n                symbol=symbol,\n                interval=interval,\n                limit=limit,\n                startTime=start_ts,\n                endTime=end_ts,\n            )\n\n            # yield data\n            if output_data:\n                for o in output_data:\n                    yield o\n\n            # handle the case where exactly the limit amount of data was returned last loop\n            # check if we received less than the required limit and exit the loop\n            if not len(output_data) or len(output_data) < limit:\n                # exit the while loop\n                break\n\n            # set our start timestamp using the last value in the array\n            # increment next call by our timeframe\n            start_ts = output_data[-1][0] + timeframe\n\n            # exit loop if we reached end_ts before reaching <limit> klines\n            if end_ts and start_ts >= end_ts:\n                break\n\n            # sleep after every 3rd call to be kind to the API\n            idx += 1\n            if idx % 3 == 0:\n                time.sleep(1)\n\n    def get_avg_price(self, **params):\n        \"\"\"Current average price for a symbol.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/market-data-endpoints#current-average-price\n\n        :param symbol:\n        :type symbol: str\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"mins\": 5,\n                \"price\": \"9.35751834\"\n            }\n        \"\"\"\n        return self._get(\"avgPrice\", data=params)\n\n    def get_ticker(self, **params):\n        \"\"\"24 hour price change statistics.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/market-data-endpoints#24hr-ticker-price-change-statistics\n\n        :param symbol:\n        :type symbol: str\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"priceChange\": \"-94.99999800\",\n                \"priceChangePercent\": \"-95.960\",\n                \"weightedAvgPrice\": \"0.29628482\",\n                \"prevClosePrice\": \"0.10002000\",\n                \"lastPrice\": \"4.00000200\",\n                \"bidPrice\": \"4.00000000\",\n                \"askPrice\": \"4.00000200\",\n                \"openPrice\": \"99.00000000\",\n                \"highPrice\": \"100.00000000\",\n                \"lowPrice\": \"0.10000000\",\n                \"volume\": \"8913.30000000\",\n                \"openTime\": 1499783499040,\n                \"closeTime\": 1499869899040,\n                \"fristId\": 28385,   # First tradeId\n                \"lastId\": 28460,    # Last tradeId\n                \"count\": 76         # Trade count\n            }\n\n        OR\n\n        .. code-block:: python\n\n            [\n                {\n                    \"priceChange\": \"-94.99999800\",\n                    \"priceChangePercent\": \"-95.960\",\n                    \"weightedAvgPrice\": \"0.29628482\",\n                    \"prevClosePrice\": \"0.10002000\",\n                    \"lastPrice\": \"4.00000200\",\n                    \"bidPrice\": \"4.00000000\",\n                    \"askPrice\": \"4.00000200\",\n                    \"openPrice\": \"99.00000000\",\n                    \"highPrice\": \"100.00000000\",\n                    \"lowPrice\": \"0.10000000\",\n                    \"volume\": \"8913.30000000\",\n                    \"openTime\": 1499783499040,\n                    \"closeTime\": 1499869899040,\n                    \"fristId\": 28385,   # First tradeId\n                    \"lastId\": 28460,    # Last tradeId\n                    \"count\": 76         # Trade count\n                }\n            ]\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._get(\"ticker/24hr\", data=params)\n\n    def get_symbol_ticker(self, **params):\n        \"\"\"Latest price for a symbol or symbols.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/market-data-endpoints#symbol-price-ticker\n\n        :param symbol:\n        :type symbol: str\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"symbol\": \"LTCBTC\",\n                \"price\": \"4.00000200\"\n            }\n\n        OR\n\n        .. code-block:: python\n\n            [\n                {\n                    \"symbol\": \"LTCBTC\",\n                    \"price\": \"4.00000200\"\n                },\n                {\n                    \"symbol\": \"ETHBTC\",\n                    \"price\": \"0.07946600\"\n                }\n            ]\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._get(\"ticker/price\", data=params)\n\n    def get_symbol_ticker_window(self, **params):\n        \"\"\"Latest price for a symbol or symbols.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/market-data-endpoints#rolling-window-price-change-statistics\n\n        :param symbol:\n        :type symbol: str\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"symbol\": \"LTCBTC\",\n                \"price\": \"4.00000200\"\n            }\n\n        OR\n\n        .. code-block:: python\n\n            [\n                {\n                    \"symbol\": \"LTCBTC\",\n                    \"price\": \"4.00000200\"\n                },\n                {\n                    \"symbol\": \"ETHBTC\",\n                    \"price\": \"0.07946600\"\n                }\n            ]\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._get(\"ticker\", data=params)\n\n    def get_orderbook_ticker(self, **params):\n        \"\"\"Latest price for a symbol or symbols.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/market-data-endpoints#symbol-order-book-ticker\n\n        :param symbol:\n        :type symbol: str\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"symbol\": \"LTCBTC\",\n                \"bidPrice\": \"4.00000000\",\n                \"bidQty\": \"431.00000000\",\n                \"askPrice\": \"4.00000200\",\n                \"askQty\": \"9.00000000\"\n            }\n\n        OR\n\n        .. code-block:: python\n\n            [\n                {\n                    \"symbol\": \"LTCBTC\",\n                    \"bidPrice\": \"4.00000000\",\n                    \"bidQty\": \"431.00000000\",\n                    \"askPrice\": \"4.00000200\",\n                    \"askQty\": \"9.00000000\"\n                },\n                {\n                    \"symbol\": \"ETHBTC\",\n                    \"bidPrice\": \"0.07946700\",\n                    \"bidQty\": \"9.00000000\",\n                    \"askPrice\": \"100000.00000000\",\n                    \"askQty\": \"1000.00000000\"\n                }\n            ]\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._get(\n            \"ticker/bookTicker\", data=params\n        )\n\n    # Account Endpoints\n\n    def create_order(self, **params):\n        \"\"\"Send in a new order\n\n        Any order with an icebergQty MUST have timeInForce set to GTC.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/trading-endpoints#new-order-trade\n\n        :param symbol: required\n        :type symbol: str\n        :param side: required\n        :type side: str\n        :param type: required\n        :type type: str\n        :param timeInForce: required if limit order\n        :type timeInForce: str\n        :param quantity: required\n        :type quantity: decimal\n        :param quoteOrderQty: amount the user wants to spend (when buying) or receive (when selling)\n            of the quote asset, applicable to MARKET orders\n        :type quoteOrderQty: decimal\n        :param price: required\n        :type price: str\n        :param newClientOrderId: A unique id for the order. Automatically generated if not sent.\n        :type newClientOrderId: str\n        :param icebergQty: Used with LIMIT, STOP_LOSS_LIMIT, and TAKE_PROFIT_LIMIT to create an iceberg order.\n        :type icebergQty: decimal\n        :param newOrderRespType: Set the response JSON. ACK, RESULT, or FULL; default: RESULT.\n        :type newOrderRespType: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        Response ACK:\n\n        .. code-block:: python\n\n            {\n                \"symbol\":\"LTCBTC\",\n                \"orderId\": 1,\n                \"clientOrderId\": \"myOrder1\" # Will be newClientOrderId\n                \"transactTime\": 1499827319559\n            }\n\n        Response RESULT:\n\n        .. code-block:: python\n\n            {\n                \"symbol\": \"BTCUSDT\",\n                \"orderId\": 28,\n                \"clientOrderId\": \"6gCrw2kRUAF9CvJDGP16IP\",\n                \"transactTime\": 1507725176595,\n                \"price\": \"0.00000000\",\n                \"origQty\": \"10.00000000\",\n                \"executedQty\": \"10.00000000\",\n                \"cummulativeQuoteQty\": \"10.00000000\",\n                \"status\": \"FILLED\",\n                \"timeInForce\": \"GTC\",\n                \"type\": \"MARKET\",\n                \"side\": \"SELL\"\n            }\n\n        Response FULL:\n\n        .. code-block:: python\n\n            {\n                \"symbol\": \"BTCUSDT\",\n                \"orderId\": 28,\n                \"clientOrderId\": \"6gCrw2kRUAF9CvJDGP16IP\",\n                \"transactTime\": 1507725176595,\n                \"price\": \"0.00000000\",\n                \"origQty\": \"10.00000000\",\n                \"executedQty\": \"10.00000000\",\n                \"cummulativeQuoteQty\": \"10.00000000\",\n                \"status\": \"FILLED\",\n                \"timeInForce\": \"GTC\",\n                \"type\": \"MARKET\",\n                \"side\": \"SELL\",\n                \"fills\": [\n                    {\n                        \"price\": \"4000.00000000\",\n                        \"qty\": \"1.00000000\",\n                        \"commission\": \"4.00000000\",\n                        \"commissionAsset\": \"USDT\"\n                    },\n                    {\n                        \"price\": \"3999.00000000\",\n                        \"qty\": \"5.00000000\",\n                        \"commission\": \"19.99500000\",\n                        \"commissionAsset\": \"USDT\"\n                    },\n                    {\n                        \"price\": \"3998.00000000\",\n                        \"qty\": \"2.00000000\",\n                        \"commission\": \"7.99600000\",\n                        \"commissionAsset\": \"USDT\"\n                    },\n                    {\n                        \"price\": \"3997.00000000\",\n                        \"qty\": \"1.00000000\",\n                        \"commission\": \"3.99700000\",\n                        \"commissionAsset\": \"USDT\"\n                    },\n                    {\n                        \"price\": \"3995.00000000\",\n                        \"qty\": \"1.00000000\",\n                        \"commission\": \"3.99500000\",\n                        \"commissionAsset\": \"USDT\"\n                    }\n                ]\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException\n\n        \"\"\"\n        if \"newClientOrderId\" not in params:\n            params[\"newClientOrderId\"] = self.SPOT_ORDER_PREFIX + self.uuid22()\n        return self._post(\"order\", True, data=params)\n\n    def order_limit(self, timeInForce=BaseClient.TIME_IN_FORCE_GTC, **params):\n        \"\"\"Send in a new limit order\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/trading-endpoints#new-order-trade\n\n        Any order with an icebergQty MUST have timeInForce set to GTC.\n\n        :param symbol: required\n        :type symbol: str\n        :param side: required\n        :type side: str\n        :param quantity: required\n        :type quantity: decimal\n        :param price: required\n        :type price: str\n        :param timeInForce: default Good till cancelled\n        :type timeInForce: str\n        :param newClientOrderId: A unique id for the order. Automatically generated if not sent.\n        :type newClientOrderId: str\n        :param icebergQty: Used with LIMIT, STOP_LOSS_LIMIT, and TAKE_PROFIT_LIMIT to create an iceberg order.\n        :type icebergQty: decimal\n        :param newOrderRespType: Set the response JSON. ACK, RESULT, or FULL; default: RESULT.\n        :type newOrderRespType: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        See order endpoint for full response options\n\n        :raises: BinanceRequestException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException\n\n        \"\"\"\n        params.update({\"type\": self.ORDER_TYPE_LIMIT, \"timeInForce\": timeInForce})\n        return self.create_order(**params)\n\n    def order_limit_buy(self, timeInForce=BaseClient.TIME_IN_FORCE_GTC, **params):\n        \"\"\"Send in a new limit buy order\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/trading-endpoints#new-order-trade\n\n        Any order with an icebergQty MUST have timeInForce set to GTC.\n\n        :param symbol: required\n        :type symbol: str\n        :param quantity: required\n        :type quantity: decimal\n        :param price: required\n        :type price: str\n        :param timeInForce: default Good till cancelled\n        :type timeInForce: str\n        :param newClientOrderId: A unique id for the order. Automatically generated if not sent.\n        :type newClientOrderId: str\n        :param stopPrice: Used with stop orders\n        :type stopPrice: decimal\n        :param icebergQty: Used with iceberg orders\n        :type icebergQty: decimal\n        :param newOrderRespType: Set the response JSON. ACK, RESULT, or FULL; default: RESULT.\n        :type newOrderRespType: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        See order endpoint for full response options\n\n        :raises: BinanceRequestException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException\n\n        \"\"\"\n        params.update({\n            \"side\": self.SIDE_BUY,\n        })\n        return self.order_limit(timeInForce=timeInForce, **params)\n\n    def order_limit_sell(self, timeInForce=BaseClient.TIME_IN_FORCE_GTC, **params):\n        \"\"\"Send in a new limit sell order\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/trading-endpoints#new-order-trade\n\n        :param symbol: required\n        :type symbol: str\n        :param quantity: required\n        :type quantity: decimal\n        :param price: required\n        :type price: str\n        :param timeInForce: default Good till cancelled\n        :type timeInForce: str\n        :param newClientOrderId: A unique id for the order. Automatically generated if not sent.\n        :type newClientOrderId: str\n        :param stopPrice: Used with stop orders\n        :type stopPrice: decimal\n        :param icebergQty: Used with iceberg orders\n        :type icebergQty: decimal\n        :param newOrderRespType: Set the response JSON. ACK, RESULT, or FULL; default: RESULT.\n        :type newOrderRespType: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        See order endpoint for full response options\n\n        :raises: BinanceRequestException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException\n\n        \"\"\"\n        params.update({\"side\": self.SIDE_SELL})\n        return self.order_limit(timeInForce=timeInForce, **params)\n\n    def order_market(self, **params):\n        \"\"\"Send in a new market order\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/trading-endpoints#new-order-trade\n\n        :param symbol: required\n        :type symbol: str\n        :param side: required\n        :type side: str\n        :param quantity: required\n        :type quantity: decimal\n        :param quoteOrderQty: amount the user wants to spend (when buying) or receive (when selling)\n            of the quote asset\n        :type quoteOrderQty: decimal\n        :param newClientOrderId: A unique id for the order. Automatically generated if not sent.\n        :type newClientOrderId: str\n        :param newOrderRespType: Set the response JSON. ACK, RESULT, or FULL; default: RESULT.\n        :type newOrderRespType: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        See order endpoint for full response options\n\n        :raises: BinanceRequestException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException\n\n        \"\"\"\n        params.update({\"type\": self.ORDER_TYPE_MARKET})\n        return self.create_order(**params)\n\n    def order_market_buy(self, **params):\n        \"\"\"Send in a new market buy order\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/trading-endpoints#new-order-trade\n\n        :param symbol: required\n        :type symbol: str\n        :param quantity: required\n        :type quantity: decimal\n        :param quoteOrderQty: the amount the user wants to spend of the quote asset\n        :type quoteOrderQty: decimal\n        :param newClientOrderId: A unique id for the order. Automatically generated if not sent.\n        :type newClientOrderId: str\n        :param newOrderRespType: Set the response JSON. ACK, RESULT, or FULL; default: RESULT.\n        :type newOrderRespType: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        See order endpoint for full response options\n\n        :raises: BinanceRequestException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException\n\n        \"\"\"\n        params.update({\"side\": self.SIDE_BUY})\n        return self.order_market(**params)\n\n    def order_market_sell(self, **params):\n        \"\"\"Send in a new market sell order\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/trading-endpoints#new-order-trade\n\n        :param symbol: required\n        :type symbol: str\n        :param quantity: required\n        :type quantity: decimal\n        :param quoteOrderQty: the amount the user wants to receive of the quote asset\n        :type quoteOrderQty: decimal\n        :param newClientOrderId: A unique id for the order. Automatically generated if not sent.\n        :type newClientOrderId: str\n        :param newOrderRespType: Set the response JSON. ACK, RESULT, or FULL; default: RESULT.\n        :type newOrderRespType: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        See order endpoint for full response options\n\n        :raises: BinanceRequestException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException\n\n        \"\"\"\n        params.update({\"side\": self.SIDE_SELL})\n        return self.order_market(**params)\n\n    def create_oco_order(self, **params):\n        \"\"\"Send in an one-cancels-the-other (OCO) pair, where activation of one order immediately cancels the other.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/trading-endpoints#new-order-list---oco-trade\n\n        An OCO has 2 orders called the above order and below order.\n        One of the orders must be a LIMIT_MAKER/TAKE_PROFIT/TAKE_PROFIT_LIMIT order and the other must be STOP_LOSS or STOP_LOSS_LIMIT order.\n\n        Price restrictions:\n        If the OCO is on the SELL side:\n            LIMIT_MAKER/TAKE_PROFIT_LIMIT price > Last Traded Price > STOP_LOSS/STOP_LOSS_LIMIT stopPrice\n            TAKE_PROFIT stopPrice > Last Traded Price > STOP_LOSS/STOP_LOSS_LIMIT stopPrice\n        If the OCO is on the BUY side:\n            LIMIT_MAKER/TAKE_PROFIT_LIMIT price < Last Traded Price < stopPrice\n            TAKE_PROFIT stopPrice < Last Traded Price < STOP_LOSS/STOP_LOSS_LIMIT stopPrice\n\n        Weight: 1\n\n        :param symbol: required\n        :type symbol: str\n        :param listClientOrderId: Arbitrary unique ID among open order lists. Automatically generated if not sent.\n        :type listClientOrderId: str\n        :param side: required - BUY or SELL\n        :type side: str\n        :param quantity: required - Quantity for both orders of the order list\n        :type quantity: decimal\n        :param aboveType: required - STOP_LOSS_LIMIT, STOP_LOSS, LIMIT_MAKER, TAKE_PROFIT, TAKE_PROFIT_LIMIT\n        :type aboveType: str\n        :param aboveClientOrderId: Arbitrary unique ID among open orders for the above order\n        :type aboveClientOrderId: str\n        :param aboveIcebergQty: Note that this can only be used if aboveTimeInForce is GTC\n        :type aboveIcebergQty: decimal\n        :param abovePrice: Can be used if aboveType is STOP_LOSS_LIMIT, LIMIT_MAKER, or TAKE_PROFIT_LIMIT\n        :type abovePrice: decimal\n        :param aboveStopPrice: Can be used if aboveType is STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, TAKE_PROFIT_LIMIT\n        :type aboveStopPrice: decimal\n        :param aboveTrailingDelta: See Trailing Stop order FAQ\n        :type aboveTrailingDelta: int\n        :param aboveTimeInForce: Required if aboveType is STOP_LOSS_LIMIT or TAKE_PROFIT_LIMIT\n        :type aboveTimeInForce: str\n        :param aboveStrategyId: Arbitrary numeric value identifying the above order within an order strategy\n        :type aboveStrategyId: int\n        :param aboveStrategyType: Arbitrary numeric value identifying the above order strategy (>= 1000000)\n        :type aboveStrategyType: int\n        :param belowType: required - STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, TAKE_PROFIT_LIMIT\n        :type belowType: str\n        :param belowClientOrderId: Arbitrary unique ID among open orders for the below order\n        :type belowClientOrderId: str\n        :param belowIcebergQty: Note that this can only be used if belowTimeInForce is GTC\n        :type belowIcebergQty: decimal\n        :param belowPrice: Can be used if belowType is STOP_LOSS_LIMIT, LIMIT_MAKER, or TAKE_PROFIT_LIMIT\n        :type belowPrice: decimal\n        :param belowStopPrice: Can be used if belowType is STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT or TAKE_PROFIT_LIMIT\n        :type belowStopPrice: decimal\n        :param belowTrailingDelta: See Trailing Stop order FAQ\n        :type belowTrailingDelta: int\n        :param belowTimeInForce: Required if belowType is STOP_LOSS_LIMIT or TAKE_PROFIT_LIMIT\n        :type belowTimeInForce: str\n        :param belowStrategyId: Arbitrary numeric value identifying the below order within an order strategy\n        :type belowStrategyId: int\n        :param belowStrategyType: Arbitrary numeric value identifying the below order strategy (>= 1000000)\n        :type belowStrategyType: int\n        :param newOrderRespType: Select response format: ACK, RESULT, FULL\n        :type newOrderRespType: str\n        :param selfTradePreventionMode: The allowed enums is dependent on what is configured on the symbol\n        :type selfTradePreventionMode: str\n        :param recvWindow: The value cannot be greater than 60000\n        :type recvWindow: int\n        :param timestamp: required\n        :type timestamp: int\n\n        :returns: API response\n\n            {\n                \"orderListId\": 1,\n                \"contingencyType\": \"OCO\",\n                \"listStatusType\": \"EXEC_STARTED\",\n                \"listOrderStatus\": \"EXECUTING\",\n                \"listClientOrderId\": \"lH1YDkuQKWiXVXHPSKYEIp\",\n                \"transactionTime\": 1710485608839,\n                \"symbol\": \"LTCBTC\",\n                \"orders\": [\n                    {\n                        \"symbol\": \"LTCBTC\",\n                        \"orderId\": 10,\n                        \"clientOrderId\": \"44nZvqpemY7sVYgPYbvPih\"\n                    },\n                    {\n                        \"symbol\": \"LTCBTC\",\n                        \"orderId\": 11,\n                        \"clientOrderId\": \"NuMp0nVYnciDiFmVqfpBqK\"\n                    }\n                ],\n                \"orderReports\": [\n                    {\n                        \"symbol\": \"LTCBTC\",\n                        \"orderId\": 10,\n                        \"orderListId\": 1,\n                        \"clientOrderId\": \"44nZvqpemY7sVYgPYbvPih\",\n                        \"transactTime\": 1710485608839,\n                        \"price\": \"1.00000000\",\n                        \"origQty\": \"5.00000000\",\n                        \"executedQty\": \"0.00000000\",\n                        \"origQuoteOrderQty\": \"0.000000\",\n                        \"cummulativeQuoteQty\": \"0.00000000\",\n                        \"status\": \"NEW\",\n                        \"timeInForce\": \"GTC\",\n                        \"type\": \"STOP_LOSS_LIMIT\",\n                        \"side\": \"SELL\",\n                        \"stopPrice\": \"1.00000000\",\n                        \"workingTime\": -1,\n                        \"icebergQty\": \"1.00000000\",\n                        \"selfTradePreventionMode\": \"NONE\"\n                    },\n                    {\n                        \"symbol\": \"LTCBTC\",\n                        \"orderId\": 11,\n                        \"orderListId\": 1,\n                        \"clientOrderId\": \"NuMp0nVYnciDiFmVqfpBqK\",\n                        \"transactTime\": 1710485608839,\n                        \"price\": \"3.00000000\",\n                        \"origQty\": \"5.00000000\",\n                        \"executedQty\": \"0.00000000\",\n                        \"origQuoteOrderQty\": \"0.000000\",\n                        \"cummulativeQuoteQty\": \"0.00000000\",\n                        \"status\": \"NEW\",\n                        \"timeInForce\": \"GTC\",\n                        \"type\": \"LIMIT_MAKER\",\n                        \"side\": \"SELL\",\n                        \"workingTime\": 1710485608839,\n                        \"selfTradePreventionMode\": \"NONE\"\n                    }\n                ]\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException, BinanceOrderException,\n                BinanceOrderMinAmountException, BinanceOrderMinPriceException,\n                BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException,\n                BinanceOrderInactiveSymbolException\n\n        \"\"\"\n        if \"listClientOrderId\" not in params:\n            params[\"listClientOrderId\"] = self.SPOT_ORDER_PREFIX + self.uuid22()\n        return self._post(\"orderList/oco\", True, data=params)\n\n    def order_oco_buy(self, **params):\n        \"\"\"Send in a new OCO buy order\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/trading-endpoints#new-order-list---oco-trade\n\n        :param symbol: required\n        :type symbol: str\n        :param listClientOrderId: A unique id for the list order. Automatically generated if not sent.\n        :type listClientOrderId: str\n        :param quantity: required\n        :type quantity: decimal\n        :param limitClientOrderId: A unique id for the limit order. Automatically generated if not sent.\n        :type limitClientOrderId: str\n        :param price: required\n        :type price: str\n        :param limitIcebergQty: Used to make the LIMIT_MAKER leg an iceberg order.\n        :type limitIcebergQty: decimal\n        :param stopClientOrderId: A unique id for the stop order. Automatically generated if not sent.\n        :type stopClientOrderId: str\n        :param stopPrice: required\n        :type stopPrice: str\n        :param stopLimitPrice: If provided, stopLimitTimeInForce is required.\n        :type stopLimitPrice: str\n        :param stopIcebergQty: Used with STOP_LOSS_LIMIT leg to make an iceberg order.\n        :type stopIcebergQty: decimal\n        :param stopLimitTimeInForce: Valid values are GTC/FOK/IOC.\n        :type stopLimitTimeInForce: str\n        :param newOrderRespType: Set the response JSON. ACK, RESULT, or FULL; default: RESULT.\n        :type newOrderRespType: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        See OCO order endpoint for full response options\n\n        :raises: BinanceRequestException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException\n\n        \"\"\"\n        params.update({\"side\": self.SIDE_BUY})\n        return self.create_oco_order(**params)\n\n    def order_oco_sell(self, **params):\n        \"\"\"Send in a new OCO sell order\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/trading-endpoints#new-order-list---oco-trade\n\n        :param symbol: required\n        :type symbol: str\n        :param listClientOrderId: A unique id for the list order. Automatically generated if not sent.\n        :type listClientOrderId: str\n        :param quantity: required\n        :type quantity: decimal\n        :param limitClientOrderId: A unique id for the limit order. Automatically generated if not sent.\n        :type limitClientOrderId: str\n        :param price: required\n        :type price: str\n        :param limitIcebergQty: Used to make the LIMIT_MAKER leg an iceberg order.\n        :type limitIcebergQty: decimal\n        :param stopClientOrderId: A unique id for the stop order. Automatically generated if not sent.\n        :type stopClientOrderId: str\n        :param stopPrice: required\n        :type stopPrice: str\n        :param stopLimitPrice: If provided, stopLimitTimeInForce is required.\n        :type stopLimitPrice: str\n        :param stopIcebergQty: Used with STOP_LOSS_LIMIT leg to make an iceberg order.\n        :type stopIcebergQty: decimal\n        :param stopLimitTimeInForce: Valid values are GTC/FOK/IOC.\n        :type stopLimitTimeInForce: str\n        :param newOrderRespType: Set the response JSON. ACK, RESULT, or FULL; default: RESULT.\n        :type newOrderRespType: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        See OCO order endpoint for full response options\n\n        :raises: BinanceRequestException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException\n\n        \"\"\"\n        params.update({\"side\": self.SIDE_SELL})\n        return self.create_oco_order(**params)\n\n    def create_test_order(self, **params):\n        \"\"\"Test new order creation and signature/recvWindow long. Creates and validates a new order but does not send it into the matching engine.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/trading-endpoints#test-new-order-trade\n\n        :param symbol: required\n        :type symbol: str\n        :param side: required\n        :type side: str\n        :param type: required\n        :type type: str\n        :param timeInForce: required if limit order\n        :type timeInForce: str\n        :param quantity: required\n        :type quantity: decimal\n        :param price: required\n        :type price: str\n        :param newClientOrderId: A unique id for the order. Automatically generated if not sent.\n        :type newClientOrderId: str\n        :param icebergQty: Used with iceberg orders\n        :type icebergQty: decimal\n        :param newOrderRespType: Set the response JSON. ACK, RESULT, or FULL; default: RESULT.\n        :type newOrderRespType: str\n        :param recvWindow: The number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {}\n\n        :raises: BinanceRequestException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException, BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException, BinanceOrderInactiveSymbolException\n\n\n        \"\"\"\n        return self._post(\"order/test\", True, data=params)\n\n    def get_order(self, **params):\n        \"\"\"Check an order's status. Either orderId or origClientOrderId must be sent.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/account-endpoints#query-order-user_data\n\n        :param symbol: required\n        :type symbol: str\n        :param orderId: The unique order id\n        :type orderId: int\n        :param origClientOrderId: optional\n        :type origClientOrderId: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"symbol\": \"LTCBTC\",\n                \"orderId\": 1,\n                \"clientOrderId\": \"myOrder1\",\n                \"price\": \"0.1\",\n                \"origQty\": \"1.0\",\n                \"executedQty\": \"0.0\",\n                \"status\": \"NEW\",\n                \"timeInForce\": \"GTC\",\n                \"type\": \"LIMIT\",\n                \"side\": \"BUY\",\n                \"stopPrice\": \"0.0\",\n                \"icebergQty\": \"0.0\",\n                \"time\": 1499827319559\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._get(\"order\", True, data=params)\n\n    def get_all_orders(self, **params):\n        \"\"\"Get all account orders; active, canceled, or filled.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/account-endpoints#all-orders-user_data\n\n        :param symbol: required\n        :type symbol: str\n        :param orderId: The unique order id\n        :type orderId: int\n        :param startTime: optional\n        :type startTime: int\n        :param endTime: optional\n        :type endTime: int\n        :param limit: Default 500; max 1000.\n        :type limit: int\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            [\n                {\n                    \"symbol\": \"LTCBTC\",\n                    \"orderId\": 1,\n                    \"clientOrderId\": \"myOrder1\",\n                    \"price\": \"0.1\",\n                    \"origQty\": \"1.0\",\n                    \"executedQty\": \"0.0\",\n                    \"status\": \"NEW\",\n                    \"timeInForce\": \"GTC\",\n                    \"type\": \"LIMIT\",\n                    \"side\": \"BUY\",\n                    \"stopPrice\": \"0.0\",\n                    \"icebergQty\": \"0.0\",\n                    \"time\": 1499827319559\n                }\n            ]\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._get(\"allOrders\", True, data=params)\n\n    def cancel_order(self, **params):\n        \"\"\"Cancel an active order. Either orderId or origClientOrderId must be sent.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/trading-endpoints#cancel-order-trade\n\n        :param symbol: required\n        :type symbol: str\n        :param orderId: The unique order id\n        :type orderId: int\n        :param origClientOrderId: optional\n        :type origClientOrderId: str\n        :param newClientOrderId: Used to uniquely identify this cancel. Automatically generated by default.\n        :type newClientOrderId: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"symbol\": \"LTCBTC\",\n                \"origClientOrderId\": \"myOrder1\",\n                \"orderId\": 1,\n                \"clientOrderId\": \"cancelMyOrder1\"\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._delete(\"order\", True, data=params)\n\n    def cancel_all_open_orders(self, **params):\n        \"\"\"\n        Cancel all open orders on a symbol.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/trading-endpoints#cancel-all-open-orders-on-a-symbol-trade\n\n        :param symbol: required\n        :type symbol: str\n\n        :returns: API response\n        \"\"\"\n        return self._delete(\"openOrders\", True, data=params)\n\n    def cancel_replace_order(self, **params):\n        \"\"\"Cancels an existing order and places a new order on the same symbol.\n\n        Filters and Order Count are evaluated before the processing of the cancellation and order placement occurs.\n\n        A new order that was not attempted (i.e. when newOrderResult: NOT_ATTEMPTED), will still increase the order count by 1.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/trading-endpoints#cancel-an-existing-order-and-send-a-new-order-trade\n\n        :param symbol: required\n        :type symbol: str\n        :param side: required\n        :type side: enum\n        :param type: required\n        :type type: enum\n        :param cancelReplaceMode: required - STOP_ON_FAILURE or ALLOW_FAILURE\n        :type cancelReplaceMode: enum\n        :param timeInForce: optional\n        :type timeInForce: enum\n        :param quantity: optional\n        :type quantity: decimal\n        :param quoteOrderQty: optional\n        :type quoteOrderQty: decimal\n        :param price: optional\n        :type price: decimal\n        :param cancelNewClientOrderId: optional - Used to uniquely identify this cancel. Automatically generated by default.\n        :type cancelNewClientOrderId: str\n        :param cancelOrigClientOrderId: optional - Either the cancelOrigClientOrderId or cancelOrderId must be provided. If both are provided, cancelOrderId takes precedence.\n        :type cancelOrigClientOrderId: str\n        :param cancelOrderId: optional - Either the cancelOrigClientOrderId or cancelOrderId must be provided. If both are provided, cancelOrderId takes precedence.\n        :type cancelOrderId: long\n        :param newClientOrderId: optional - Used to identify the new order.\n        :type newClientOrderId: str\n        :param strategyId: optional\n        :type strategyId: int\n        :param strategyType: optional - The value cannot be less than 1000000.\n        :type strategyType: int\n        :param stopPrice: optional\n        :type stopPrice: decimal\n        :param trailingDelta: optional\n        :type trailingDelta: long\n        :param icebergQty: optional\n        :type icebergQty: decimal\n        :param newOrderRespType: optional - ACK, RESULT or FULL. MARKET and LIMIT orders types default to FULL; all other orders default to ACK\n        :type newOrderRespType: enum\n        :param selfTradePreventionMode: optional - EXPIRE_TAKER, EXPIRE_MAKER, EXPIRE_BOTH or NONE.\n        :type selfTradePreventionMode: enum\n        :param cancelRestrictions: optional - ONLY_NEW or ONLY_PARTIALLY_FILLED\n        :type cancelRestrictions: enum\n        :param recvWindow: optional - The value cannot be greater than 60000\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            //Both the cancel order placement and new order placement succeeded.\n            {\n                \"cancelResult\": \"SUCCESS\",\n                \"newOrderResult\": \"SUCCESS\",\n                \"cancelResponse\": {\n                    \"symbol\": \"BTCUSDT\",\n                    \"origClientOrderId\": \"DnLo3vTAQcjha43lAZhZ0y\",\n                    \"orderId\": 9,\n                    \"orderListId\": -1,\n                    \"clientOrderId\": \"osxN3JXAtJvKvCqGeMWMVR\",\n                    \"transactTime\": 1684804350068,\n                    \"price\": \"0.01000000\",\n                    \"origQty\": \"0.000100\",\n                    \"executedQty\": \"0.00000000\",\n                    \"cummulativeQuoteQty\": \"0.00000000\",\n                    \"status\": \"CANCELED\",\n                    \"timeInForce\": \"GTC\",\n                    \"type\": \"LIMIT\",\n                    \"side\": \"SELL\",\n                    \"selfTradePreventionMode\": \"NONE\"\n                },\n                \"newOrderResponse\": {\n                    \"symbol\": \"BTCUSDT\",\n                    \"orderId\": 10,\n                    \"orderListId\": -1,\n                    \"clientOrderId\": \"wOceeeOzNORyLiQfw7jd8S\",\n                    \"transactTime\": 1652928801803,\n                    \"price\": \"0.02000000\",\n                    \"origQty\": \"0.040000\",\n                    \"executedQty\": \"0.00000000\",\n                    \"cummulativeQuoteQty\": \"0.00000000\",\n                    \"status\": \"NEW\",\n                    \"timeInForce\": \"GTC\",\n                    \"type\": \"LIMIT\",\n                    \"side\": \"BUY\",\n                    \"workingTime\": 1669277163808,\n                    \"fills\": [],\n                    \"selfTradePreventionMode\": \"NONE\"\n\n                }\n            }\n        Similar to POST /api/v3/order, additional mandatory parameters are determined by type.\n\n        Response format varies depending on whether the processing of the message succeeded, partially succeeded, or failed.\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        if \"newClientOrderId\" not in params:\n            params[\"newClientOrderId\"] = self.SPOT_ORDER_PREFIX + self.uuid22()\n        return self._post(\"order/cancelReplace\", True, data=params)\n\n    def get_open_orders(self, **params):\n        \"\"\"Get all open orders on a symbol.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/account-endpoints#current-open-orders-user_data\n\n        :param symbol: optional\n        :type symbol: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            [\n                {\n                    \"symbol\": \"LTCBTC\",\n                    \"orderId\": 1,\n                    \"clientOrderId\": \"myOrder1\",\n                    \"price\": \"0.1\",\n                    \"origQty\": \"1.0\",\n                    \"executedQty\": \"0.0\",\n                    \"status\": \"NEW\",\n                    \"timeInForce\": \"GTC\",\n                    \"type\": \"LIMIT\",\n                    \"side\": \"BUY\",\n                    \"stopPrice\": \"0.0\",\n                    \"icebergQty\": \"0.0\",\n                    \"time\": 1499827319559\n                }\n            ]\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._get(\"openOrders\", True, data=params)\n\n    def get_open_oco_orders(self, **params):\n        \"\"\"Get all open orders on a symbol.\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/account-endpoints#query-open-order-lists-user_data\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n        :returns: API response\n        .. code-block:: python\n            [\n                {\n                    \"orderListId\": 31,\n                    \"contingencyType\": \"OCO\",\n                    \"listStatusType\": \"EXEC_STARTED\",\n                    \"listOrderStatus\": \"EXECUTING\",\n                    \"listClientOrderId\": \"wuB13fmulKj3YjdqWEcsnp\",\n                    \"transactionTime\": 1565246080644,\n                    \"symbol\": \"LTCBTC\",\n                    \"orders\": [\n                        {\n                            \"symbol\": \"LTCBTC\",\n                            \"orderId\": 4,\n                            \"clientOrderId\": \"r3EH2N76dHfLoSZWIUw1bT\"\n                        },\n                        {\n                            \"symbol\": \"LTCBTC\",\n                            \"orderId\": 5,\n                            \"clientOrderId\": \"Cv1SnyPD3qhqpbjpYEHbd2\"\n                        }\n                    ]\n                }\n            ]\n        :raises: BinanceRequestException, BinanceAPIException\n        \"\"\"\n        return self._get(\"openOrderList\", True, data=params)\n\n    # User Stream Endpoints\n    def get_account(self, **params):\n        \"\"\"Get current account information.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/account-endpoints#account-information-user_data\n\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"makerCommission\": 15,\n                \"takerCommission\": 15,\n                \"buyerCommission\": 0,\n                \"sellerCommission\": 0,\n                \"canTrade\": true,\n                \"canWithdraw\": true,\n                \"canDeposit\": true,\n                \"balances\": [\n                    {\n                        \"asset\": \"BTC\",\n                        \"free\": \"4723846.89208129\",\n                        \"locked\": \"0.00000000\"\n                    },\n                    {\n                        \"asset\": \"LTC\",\n                        \"free\": \"4763368.68006011\",\n                        \"locked\": \"0.00000000\"\n                    }\n                ]\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._get(\"account\", True, data=params)\n\n    def get_asset_balance(self, asset=None, **params):\n        \"\"\"Get current asset balance.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/account-endpoints#account-information-user_data\n\n        :param asset: optional - the asset to get the balance of\n        :type asset: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: dictionary or None if not found\n\n        .. code-block:: python\n\n            {\n                \"asset\": \"BTC\",\n                \"free\": \"4723846.89208129\",\n                \"locked\": \"0.00000000\"\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        res = self.get_account(**params)\n        # find asset balance in list of balances\n        if \"balances\" in res:\n            if asset:\n                for bal in res[\"balances\"]:\n                    if bal[\"asset\"].lower() == asset.lower():\n                        return bal\n            else:\n                return res[\"balances\"]\n        return None\n\n    def get_my_trades(self, **params):\n        \"\"\"Get trades for a specific symbol.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/account-endpoints#account-trade-list-user_data\n\n        :param symbol: required\n        :type symbol: str\n        :param startTime: optional\n        :type startTime: int\n        :param endTime: optional\n        :type endTime: int\n        :param limit: Default 500; max 1000.\n        :type limit: int\n        :param fromId: TradeId to fetch from. Default gets most recent trades.\n        :type fromId: int\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            [\n                {\n                    \"id\": 28457,\n                    \"price\": \"4.00000100\",\n                    \"qty\": \"12.00000000\",\n                    \"commission\": \"10.10000000\",\n                    \"commissionAsset\": \"BNB\",\n                    \"time\": 1499865549590,\n                    \"isBuyer\": true,\n                    \"isMaker\": false,\n                    \"isBestMatch\": true\n                }\n            ]\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._get(\"myTrades\", True, data=params)\n\n    def get_current_order_count(self, **params):\n        \"\"\"Displays the user's current order count usage for all intervals.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/account-endpoints#query-unfilled-order-count-user_data\n\n        :returns: API response\n\n        .. code-block:: python\n            [\n\n                {\n                    \"rateLimitType\": \"ORDERS\",\n                    \"interval\": \"SECOND\",\n                    \"intervalNum\": 10,\n                    \"limit\": 10000,\n                    \"count\": 0\n                },\n                {\n                    \"rateLimitType\": \"ORDERS\",\n                    \"interval\": \"DAY\",\n                    \"intervalNum\": 1,\n                    \"limit\": 20000,\n                    \"count\": 0\n                }\n            ]\n\n        \"\"\"\n        return self._get(\"rateLimit/order\", True, data=params)\n\n    def get_prevented_matches(self, **params):\n        \"\"\"Displays the list of orders that were expired because of STP.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/account-endpoints#query-prevented-matches-user_data\n\n        :param symbol: required\n        :type symbol: str\n        :param preventedMatchId: optional\n        :type preventedMatchId: int\n        :param orderId: optional\n        :type orderId: int\n        :param fromPreventedMatchId: optional\n        :type fromPreventedMatchId: int\n        :param limit: optional, Default: 500; Max: 1000\n        :type limit: int\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n            [\n                {\n                    \"symbol\": \"BTCUSDT\",\n                    \"preventedMatchId\": 1,\n                    \"takerOrderId\": 5,\n                    \"makerOrderId\": 3,\n                    \"tradeGroupId\": 1,\n                    \"selfTradePreventionMode\": \"EXPIRE_MAKER\",\n                    \"price\": \"1.100000\",\n                    \"makerPreventedQuantity\": \"1.300000\",\n                    \"transactTime\": 1669101687094\n                }\n            ]\n        \"\"\"\n        return self._get(\"myPreventedMatches\", True, data=params)\n\n    def get_allocations(self, **params):\n        \"\"\"Retrieves allocations resulting from SOR order placement.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/rest-api/account-endpoints#query-allocations-user_data\n\n        :param symbol: required\n        :type symbol: str\n        :param startTime: optional\n        :type startTime: int\n        :param endTime: optional\n        :type endTime: int\n        :param fromAllocationId: optional\n        :type fromAllocationId: int\n        :param orderId: optional\n        :type orderId: int\n        :param limit: optional, Default: 500; Max: 1000\n        :type limit: int\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n            [\n                {\n                    \"symbol\": \"BTCUSDT\",\n                    \"allocationId\": 0,\n                    \"allocationType\": \"SOR\",\n                    \"orderId\": 1,\n                    \"orderListId\": -1,\n                    \"price\": \"1.00000000\",\n                    \"qty\": \"5.00000000\",\n                    \"quoteQty\": \"5.00000000\",\n                    \"commission\": \"0.00000000\",\n                    \"commissionAsset\": \"BTC\",\n                    \"time\": 1687506878118,\n                    \"isBuyer\": true,\n                    \"isMaker\": false,\n                    \"isAllocator\": false\n                }\n            ]\n        \"\"\"\n        return self._get(\"myAllocations\", True, data=params)\n\n    def get_system_status(self):\n        \"\"\"Get system status detail.\n\n        https://developers.binance.com/docs/wallet/others/system-status\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"status\": 0,        # 0: normal，1：system maintenance\n                \"msg\": \"normal\"     # normal or System maintenance.\n            }\n\n        :raises: BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\"get\", \"system/status\")\n\n    def get_account_status(self, version=1, **params):\n        \"\"\"Get account status detail.\n\n        https://binance-docs.github.io/apidocs/spot/en/#account-status-sapi-user_data\n        https://developers.binance.com/docs/wallet/account/account-status\n        :param version: the api version\n        :param version: int\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"data\": \"Normal\"\n            }\n\n        \"\"\"\n        if self.tld == \"us\":\n            path = \"accountStatus\"\n        else:\n            path = \"account/status\"\n        return self._request_margin_api(\"get\", path, True, version, data=params)\n\n    def get_account_api_trading_status(self, **params):\n        \"\"\"Fetch account api trading status detail.\n\n        https://developers.binance.com/docs/wallet/account/account-api-trading-status\n\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"data\": {          // API trading status detail\n                    \"isLocked\": false,   // API trading function is locked or not\n                    \"plannedRecoverTime\": 0,  // If API trading function is locked, this is the planned recover time\n                    \"triggerCondition\": {\n                            \"GCR\": 150,  // Number of GTC orders\n                            \"IFER\": 150, // Number of FOK/IOC orders\n                            \"UFR\": 300   // Number of orders\n                    },\n                    \"indicators\": {  // The indicators updated every 30 seconds\n                         \"BTCUSDT\": [  // The symbol\n                            {\n                                \"i\": \"UFR\",  // Unfilled Ratio (UFR)\n                                \"c\": 20,     // Count of all orders\n                                \"v\": 0.05,   // Current UFR value\n                                \"t\": 0.995   // Trigger UFR value\n                            },\n                            {\n                                \"i\": \"IFER\", // IOC/FOK Expiration Ratio (IFER)\n                                \"c\": 20,     // Count of FOK/IOC orders\n                                \"v\": 0.99,   // Current IFER value\n                                \"t\": 0.99    // Trigger IFER value\n                            },\n                            {\n                                \"i\": \"GCR\",  // GTC Cancellation Ratio (GCR)\n                                \"c\": 20,     // Count of GTC orders\n                                \"v\": 0.99,   // Current GCR value\n                                \"t\": 0.99    // Trigger GCR value\n                            }\n                        ],\n                        \"ETHUSDT\": [\n                            {\n                                \"i\": \"UFR\",\n                                \"c\": 20,\n                                \"v\": 0.05,\n                                \"t\": 0.995\n                            },\n                            {\n                                \"i\": \"IFER\",\n                                \"c\": 20,\n                                \"v\": 0.99,\n                                \"t\": 0.99\n                            },\n                            {\n                                \"i\": \"GCR\",\n                                \"c\": 20,\n                                \"v\": 0.99,\n                                \"t\": 0.99\n                            }\n                        ]\n                    },\n                    \"updateTime\": 1547630471725\n                }\n            }\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"account/apiTradingStatus\", True, data=params\n        )\n\n    def get_account_api_permissions(self, **params):\n        \"\"\"Fetch api key permissions.\n\n        https://developers.binance.com/docs/wallet/account/api-key-permission\n\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n               \"ipRestrict\": false,\n               \"createTime\": 1623840271000,\n               \"enableWithdrawals\": false,   // This option allows you to withdraw via API. You must apply the IP Access Restriction filter in order to enable withdrawals\n               \"enableInternalTransfer\": true,  // This option authorizes this key to transfer funds between your master account and your sub account instantly\n               \"permitsUniversalTransfer\": true,  // Authorizes this key to be used for a dedicated universal transfer API to transfer multiple supported currencies. Each business's own transfer API rights are not affected by this authorization\n               \"enableVanillaOptions\": false,  //  Authorizes this key to Vanilla options trading\n               \"enableReading\": true,\n               \"enableFutures\": false,  //  API Key created before your futures account opened does not support futures API service\n               \"enableMargin\": false,   //  This option can be adjusted after the Cross Margin account transfer is completed\n               \"enableSpotAndMarginTrading\": false, // Spot and margin trading\n               \"tradingAuthorityExpirationTime\": 1628985600000  // Expiration time for spot and margin trading permission\n            }\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"account/apiRestrictions\", True, data=params\n        )\n\n    def get_dust_assets(self, **params):\n        \"\"\"Get assets that can be converted into BNB\n\n        https://developers.binance.com/docs/wallet/asset/assets-can-convert-bnb\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"details\": [\n                    {\n                        \"asset\": \"ADA\",\n                        \"assetFullName\": \"ADA\",\n                        \"amountFree\": \"6.21\",   //Convertible amount\n                        \"toBTC\": \"0.00016848\",  //BTC amount\n                        \"toBNB\": \"0.01777302\",  //BNB amount（Not deducted commission fee）\n                        \"toBNBOffExchange\": \"0.01741756\", //BNB amount（Deducted commission fee）\n                        \"exchange\": \"0.00035546\" //Commission fee\n                    }\n                ],\n                \"totalTransferBtc\": \"0.00016848\",\n                \"totalTransferBNB\": \"0.01777302\",\n                \"dribbletPercentage\": \"0.02\"     //Commission fee\n            }\n\n        \"\"\"\n        return self._request_margin_api(\"post\", \"asset/dust-btc\", True, data=params)\n\n    def get_dust_log(self, **params):\n        \"\"\"Get log of small amounts exchanged for BNB.\n\n        https://developers.binance.com/docs/wallet/asset/dust-log\n\n        :param startTime: optional\n        :type startTime: int\n        :param endTime: optional\n        :type endTime: int\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"total\": 8,   //Total counts of exchange\n                \"userAssetDribblets\": [\n                    {\n                        \"totalTransferedAmount\": \"0.00132256\",   // Total transfered BNB amount for this exchange.\n                        \"totalServiceChargeAmount\": \"0.00002699\",    //Total service charge amount for this exchange.\n                        \"transId\": 45178372831,\n                        \"userAssetDribbletDetails\": [           //Details of  this exchange.\n                            {\n                                \"transId\": 4359321,\n                                \"serviceChargeAmount\": \"0.000009\",\n                                \"amount\": \"0.0009\",\n                                \"operateTime\": 1615985535000,\n                                \"transferedAmount\": \"0.000441\",\n                                \"fromAsset\": \"USDT\"\n                            },\n                            {\n                                \"transId\": 4359321,\n                                \"serviceChargeAmount\": \"0.00001799\",\n                                \"amount\": \"0.0009\",\n                                \"operateTime\": \"2018-05-03 17:07:04\",\n                                \"transferedAmount\": \"0.00088156\",\n                                \"fromAsset\": \"ETH\"\n                            }\n                        ]\n                    },\n                    {\n                        \"operateTime\":1616203180000,\n                        \"totalTransferedAmount\": \"0.00058795\",\n                        \"totalServiceChargeAmount\": \"0.000012\",\n                        \"transId\": 4357015,\n                        \"userAssetDribbletDetails\": [\n                            {\n                                \"transId\": 4357015,\n                                \"serviceChargeAmount\": \"0.00001\"\n                                \"amount\": \"0.001\",\n                                \"operateTime\": 1616203180000,\n                                \"transferedAmount\": \"0.00049\",\n                                \"fromAsset\": \"USDT\"\n                            },\n                            {\n                                \"transId\": 4357015,\n                                \"serviceChargeAmount\": \"0.000002\"\n                                \"amount\": \"0.0001\",\n                                \"operateTime\": 1616203180000,\n                                \"transferedAmount\": \"0.00009795\",\n                                \"fromAsset\": \"ETH\"\n                            }\n                        ]\n                    }\n                ]\n            }\n\n        \"\"\"\n        return self._request_margin_api(\"get\", \"asset/dribblet\", True, data=params)\n\n    def transfer_dust(self, **params):\n        \"\"\"Convert dust assets to BNB.\n\n        https://developers.binance.com/docs/wallet/asset/dust-transfer\n\n        :param asset: The asset being converted. e.g: 'ONE'\n        :type asset: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        .. code-block:: python\n\n            result = client.transfer_dust(asset='ONE')\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"totalServiceCharge\":\"0.02102542\",\n                \"totalTransfered\":\"1.05127099\",\n                \"transferResult\":[\n                    {\n                        \"amount\":\"0.03000000\",\n                        \"fromAsset\":\"ETH\",\n                        \"operateTime\":1563368549307,\n                        \"serviceChargeAmount\":\"0.00500000\",\n                        \"tranId\":2970932918,\n                        \"transferedAmount\":\"0.25000000\"\n                    }\n                ]\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\"post\", \"asset/dust\", True, data=params)\n\n    def get_asset_dividend_history(self, **params):\n        \"\"\"Query asset dividend record.\n\n        https://developers.binance.com/docs/wallet/asset/assets-divided-record\n\n        :param asset: optional\n        :type asset: str\n        :param startTime: optional\n        :type startTime: long\n        :param endTime: optional\n        :type endTime: long\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        .. code-block:: python\n\n            result = client.get_asset_dividend_history()\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"rows\":[\n                    {\n                        \"amount\":\"10.00000000\",\n                        \"asset\":\"BHFT\",\n                        \"divTime\":1563189166000,\n                        \"enInfo\":\"BHFT distribution\",\n                        \"tranId\":2968885920\n                    },\n                    {\n                        \"amount\":\"10.00000000\",\n                        \"asset\":\"BHFT\",\n                        \"divTime\":1563189165000,\n                        \"enInfo\":\"BHFT distribution\",\n                        \"tranId\":2968885920\n                    }\n                ],\n                \"total\":2\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\"get\", \"asset/assetDividend\", True, data=params)\n\n    def make_universal_transfer(self, **params):\n        \"\"\"User Universal Transfer\n\n        https://developers.binance.com/docs/wallet/asset/user-universal-transfer\n\n        :param type: required\n        :type type: str (ENUM)\n        :param asset: required\n        :type asset: str\n        :param amount: required\n        :type amount: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        .. code-block:: python\n\n            transfer_status = client.make_universal_transfer(params)\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"tranId\":13526853623\n            }\n\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"post\", \"asset/transfer\", signed=True, data=params\n        )\n\n    def query_universal_transfer_history(self, **params):\n        \"\"\"Query User Universal Transfer History\n\n        https://developers.binance.com/docs/wallet/asset/query-user-universal-transfer\n\n        :param type: required\n        :type type: str (ENUM)\n        :param startTime: optional\n        :type startTime: int\n        :param endTime: optional\n        :type endTime: int\n        :param current: optional - Default 1\n        :type current: int\n        :param size: required - Default 10, Max 100\n        :type size: int\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        .. code-block:: python\n\n            transfer_status = client.query_universal_transfer_history(params)\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"total\":2,\n                \"rows\":[\n                    {\n                        \"asset\":\"USDT\",\n                        \"amount\":\"1\",\n                        \"type\":\"MAIN_UMFUTURE\"\n                        \"status\": \"CONFIRMED\",\n                        \"tranId\": 11415955596,\n                        \"timestamp\":1544433328000\n                    },\n                    {\n                        \"asset\":\"USDT\",\n                        \"amount\":\"2\",\n                        \"type\":\"MAIN_UMFUTURE\",\n                        \"status\": \"CONFIRMED\",\n                        \"tranId\": 11366865406,\n                        \"timestamp\":1544433328000\n                    }\n                ]\n            }\n\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"asset/transfer\", signed=True, data=params\n        )\n\n    def get_trade_fee(self, **params):\n        \"\"\"Get trade fee.\n\n        https://developers.binance.com/docs/wallet/asset/trade-fee\n\n        :param symbol: optional\n        :type symbol: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            [\n                {\n                    \"symbol\": \"ADABNB\",\n                    \"makerCommission\": \"0.001\",\n                    \"takerCommission\": \"0.001\"\n                },\n                {\n                    \"symbol\": \"BNBBTC\",\n                    \"makerCommission\": \"0.001\",\n                    \"takerCommission\": \"0.001\"\n                }\n            ]\n\n        \"\"\"\n        if self.tld == \"us\":\n            endpoint = \"asset/query/trading-fee\"\n        else:\n            endpoint = \"asset/tradeFee\"\n\n        return self._request_margin_api(\"get\", endpoint, True, data=params)\n\n    def get_asset_details(self, **params):\n        \"\"\"Fetch details on assets.\n\n        https://developers.binance.com/docs/wallet/asset\n\n        :param asset: optional\n        :type asset: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                    \"CTR\": {\n                        \"minWithdrawAmount\": \"70.00000000\", //min withdraw amount\n                        \"depositStatus\": false,//deposit status (false if ALL of networks' are false)\n                        \"withdrawFee\": 35, // withdraw fee\n                        \"withdrawStatus\": true, //withdraw status (false if ALL of networks' are false)\n                        \"depositTip\": \"Delisted, Deposit Suspended\" //reason\n                    },\n                    \"SKY\": {\n                        \"minWithdrawAmount\": \"0.02000000\",\n                        \"depositStatus\": true,\n                        \"withdrawFee\": 0.01,\n                        \"withdrawStatus\": true\n                    }\n            }\n\n        \"\"\"\n        return self._request_margin_api(\"get\", \"asset/assetDetail\", True, data=params)\n\n    def get_spot_delist_schedule(self, **params):\n        \"\"\"Get symbols delist schedule for spot\n\n        https://developers.binance.com/docs/wallet/others/delist-schedule\n\n        :param recvWindow: optional - the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n            [\n                {\n                    \"delistTime\": 1686161202000,\n                    \"symbols\": [\n                        \"ADAUSDT\",\n                        \"BNBUSDT\"\n                    ]\n                },\n                {\n                    \"delistTime\": 1686222232000,\n                    \"symbols\": [\n                        \"ETHUSDT\"\n                    ]\n                }\n            ]\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"spot/delist-schedule\", False, data=params\n        )\n\n    # Withdraw Endpoints\n\n    def withdraw(self, **params):\n        \"\"\"Submit a withdraw request.\n\n        https://developers.binance.com/docs/wallet/capital/withdraw\n\n        Assumptions:\n\n        - You must have Withdraw permissions enabled on your API key\n        - You must have withdrawn to the address specified through the website and approved the transaction via email\n\n        :param coin: required\n        :type coin: str\n        :param withdrawOrderId: optional - client id for withdraw\n        :type withdrawOrderId: str\n        :param network: optional\n        :type network: str\n        :param address: optional\n        :type address: str\n        :type addressTag: optional - Secondary address identifier for coins like XRP,XMR etc.\n        :param amount: required\n        :type amount: decimal\n        :param transactionFeeFlag: required - When making internal transfer, true for returning the fee to the destination account; false for returning the fee back to the departure account. Default false.\n        :type transactionFeeFlag: bool\n        :param name: optional - Description of the address, default asset value passed will be used\n        :type name: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"id\":\"7213fea8e94b4a5593d507237e5a555b\"\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"post\", \"capital/withdraw/apply\", True, data=params\n        )\n\n    def get_deposit_history(self, **params):\n        \"\"\"Fetch deposit history.\n\n        https://developers.binance.com/docs/wallet/capital/deposite-history\n\n        :param coin: optional\n        :type coin: str\n        :type status: optional - 0(0:pending,1:success) optional\n        :type status: int\n        :param startTime: optional\n        :type startTime: long\n        :param endTime: optional\n        :type endTime: long\n        :param offset: optional - default:0\n        :type offset: long\n        :param limit: optional\n        :type limit: long\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            [\n                {\n                    \"amount\":\"0.00999800\",\n                    \"coin\":\"PAXG\",\n                    \"network\":\"ETH\",\n                    \"status\":1,\n                    \"address\":\"0x788cabe9236ce061e5a892e1a59395a81fc8d62c\",\n                    \"addressTag\":\"\",\n                    \"txId\":\"0xaad4654a3234aa6118af9b4b335f5ae81c360b2394721c019b5d1e75328b09f3\",\n                    \"insertTime\":1599621997000,\n                    \"transferType\":0,\n                    \"confirmTimes\":\"12/12\"\n                },\n                {\n                    \"amount\":\"0.50000000\",\n                    \"coin\":\"IOTA\",\n                    \"network\":\"IOTA\",\n                    \"status\":1,\n                    \"address\":\"SIZ9VLMHWATXKV99LH99CIGFJFUMLEHGWVZVNNZXRJJVWBPHYWPPBOSDORZ9EQSHCZAMPVAPGFYQAUUV9DROOXJLNW\",\n                    \"addressTag\":\"\",\n                    \"txId\":\"ESBFVQUTPIWQNJSPXFNHNYHSQNTGKRVKPRABQWTAXCDWOAKDKYWPTVG9BGXNVNKTLEJGESAVXIKIZ9999\",\n                    \"insertTime\":1599620082000,\n                    \"transferType\":0,\n                    \"confirmTimes\":\"1/1\"\n                }\n            ]\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"capital/deposit/hisrec\", True, data=params\n        )\n\n    def get_withdraw_history(self, **params):\n        \"\"\"Fetch withdraw history.\n\n        https://developers.binance.com/docs/wallet/capital/withdraw-history\n\n        :param coin: optional\n        :type coin: str\n        :type status: 0(0:Email Sent,1:Cancelled 2:Awaiting Approval 3:Rejected 4:Processing 5:Failure 6Completed) optional\n        :type status: int\n        :param offset: optional - default:0\n        :type offset: int\n        :param limit: optional\n        :type limit: int\n        :param startTime: optional - Default: 90 days from current timestamp\n        :type startTime: int\n        :param endTime: optional - Default: present timestamp\n        :type endTime: int\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            [\n                {\n                    \"address\": \"0x94df8b352de7f46f64b01d3666bf6e936e44ce60\",\n                    \"amount\": \"8.91000000\",\n                    \"applyTime\": \"2019-10-12 11:12:02\",\n                    \"coin\": \"USDT\",\n                    \"id\": \"b6ae22b3aa844210a7041aee7589627c\",\n                    \"withdrawOrderId\": \"WITHDRAWtest123\", // will not be returned if there's no withdrawOrderId for this withdraw.\n                    \"network\": \"ETH\",\n                    \"transferType\": 0,   // 1 for internal transfer, 0 for external transfer\n                    \"status\": 6,\n                    \"txId\": \"0xb5ef8c13b968a406cc62a93a8bd80f9e9a906ef1b3fcf20a2e48573c17659268\"\n                },\n                {\n                    \"address\": \"1FZdVHtiBqMrWdjPyRPULCUceZPJ2WLCsB\",\n                    \"amount\": \"0.00150000\",\n                    \"applyTime\": \"2019-09-24 12:43:45\",\n                    \"coin\": \"BTC\",\n                    \"id\": \"156ec387f49b41df8724fa744fa82719\",\n                    \"network\": \"BTC\",\n                    \"status\": 6,\n                    \"txId\": \"60fd9007ebfddc753455f95fafa808c4302c836e4d1eebc5a132c36c1d8ac354\"\n                }\n            ]\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"capital/withdraw/history\", True, data=params\n        )\n\n    def get_withdraw_history_id(self, withdraw_id, **params):\n        \"\"\"Fetch withdraw history.\n\n        https://binance-docs.github.io/apidocs/spot/en/#withdraw-history-supporting-network-user_data\n\n        :param withdraw_id: required\n        :type withdraw_id: str\n        :param asset: optional\n        :type asset: str\n        :type status: 0(0:Email Sent,1:Cancelled 2:Awaiting Approval 3:Rejected 4:Processing 5:Failure 6Completed) optional\n        :type status: int\n        :param startTime: optional\n        :type startTime: long\n        :param endTime: optional\n        :type endTime: long\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"id\":\"7213fea8e94b4a5593d507237e5a555b\",\n                \"withdrawOrderId\": None,\n                \"amount\": 0.99,\n                \"transactionFee\": 0.01,\n                \"address\": \"0x6915f16f8791d0a1cc2bf47c13a6b2a92000504b\",\n                \"asset\": \"ETH\",\n                \"txId\": \"0xdf33b22bdb2b28b1f75ccd201a4a4m6e7g83jy5fc5d5a9d1340961598cfcb0a1\",\n                \"applyTime\": 1508198532000,\n                \"status\": 4\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        result = self.get_withdraw_history(**params)\n\n        for entry in result:\n            if \"id\" in entry and entry[\"id\"] == withdraw_id:\n                return entry\n\n        raise Exception(\"There is no entry with withdraw id\", result)\n\n    def get_deposit_address(self, coin: str, network: Optional[str] = None, **params):\n        \"\"\"Fetch a deposit address for a symbol\n\n        https://developers.binance.com/docs/wallet/capital/deposite-address\n\n        :param coin: required\n        :type coin: str\n        :param network: optional\n        :type network: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"address\": \"1HPn8Rx2y6nNSfagQBKy27GB99Vbzg89wv\",\n                \"coin\": \"BTC\",\n                \"tag\": \"\",\n                \"url\": \"https://btc.com/1HPn8Rx2y6nNSfagQBKy27GB99Vbzg89wv\"\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        params[\"coin\"] = coin\n        if network:\n            params[\"network\"] = network\n        return self._request_margin_api(\n            \"get\", \"capital/deposit/address\", True, data=params\n        )\n\n    # User Stream Endpoints\n\n    def stream_get_listen_key(self):\n        \"\"\"Start a new user data stream and return the listen key\n        If a stream already exists it should return the same key.\n        If the stream becomes invalid a new key is returned.\n\n        Can be used to keep the user stream alive.\n\n        https://binance-docs.github.io/apidocs/spot/en/#listen-key-spot\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"listenKey\": \"pqia91ma19a5s61cv6a81va65sdf19v8a65a1a5s61cv6a81va65sdf19v8a65a1\"\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        res = self._post(\n            \"userDataStream\", False, data={}\n        )\n        return res[\"listenKey\"]\n\n    def stream_keepalive(self, listenKey):\n        \"\"\"PING a user data stream to prevent a time out.\n\n        https://binance-docs.github.io/apidocs/spot/en/#listen-key-spot\n\n        :param listenKey: required\n        :type listenKey: str\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {}\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        params = {\"listenKey\": listenKey}\n        return self._put(\n            \"userDataStream\", False, data=params\n        )\n\n    def stream_close(self, listenKey):\n        \"\"\"Close out a user data stream.\n\n        https://binance-docs.github.io/apidocs/spot/en/#listen-key-spot\n\n        :param listenKey: required\n        :type listenKey: str\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {}\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        params = {\"listenKey\": listenKey}\n        return self._delete(\n            \"userDataStream\", False, data=params, version=self.PRIVATE_API_VERSION\n        )\n\n    # Margin Trading Endpoints\n\n    def get_margin_account(self, **params):\n        \"\"\"Query cross-margin account details\n\n        https://developers.binance.com/docs/margin_trading/account/Query-Cross-Margin-Account-Details\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"borrowEnabled\": true,\n                \"marginLevel\": \"11.64405625\",\n                \"totalAssetOfBtc\": \"6.82728457\",\n                \"totalLiabilityOfBtc\": \"0.58633215\",\n                \"totalNetAssetOfBtc\": \"6.24095242\",\n                \"tradeEnabled\": true,\n                \"transferEnabled\": true,\n                \"userAssets\": [\n                    {\n                        \"asset\": \"BTC\",\n                        \"borrowed\": \"0.00000000\",\n                        \"free\": \"0.00499500\",\n                        \"interest\": \"0.00000000\",\n                        \"locked\": \"0.00000000\",\n                        \"netAsset\": \"0.00499500\"\n                    },\n                    {\n                        \"asset\": \"BNB\",\n                        \"borrowed\": \"201.66666672\",\n                        \"free\": \"2346.50000000\",\n                        \"interest\": \"0.00000000\",\n                        \"locked\": \"0.00000000\",\n                        \"netAsset\": \"2144.83333328\"\n                    },\n                    {\n                        \"asset\": \"ETH\",\n                        \"borrowed\": \"0.00000000\",\n                        \"free\": \"0.00000000\",\n                        \"interest\": \"0.00000000\",\n                        \"locked\": \"0.00000000\",\n                        \"netAsset\": \"0.00000000\"\n                    },\n                    {\n                        \"asset\": \"USDT\",\n                        \"borrowed\": \"0.00000000\",\n                        \"free\": \"0.00000000\",\n                        \"interest\": \"0.00000000\",\n                        \"locked\": \"0.00000000\",\n                        \"netAsset\": \"0.00000000\"\n                    }\n                ]\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\"get\", \"margin/account\", True, data=params)\n\n    def get_isolated_margin_account(self, **params):\n        \"\"\"Query isolated margin account details\n\n        https://developers.binance.com/docs/margin_trading/account/Query-Isolated-Margin-Account-Info\n\n        :param symbols: optional up to 5 margin pairs as a comma separated string\n        :type asset: str\n\n        .. code:: python\n\n            account_info = client.get_isolated_margin_account()\n            account_info = client.get_isolated_margin_account(symbols=\"BTCUSDT,ETHUSDT\")\n\n        :returns: API response\n\n        .. code-block:: python\n\n            If \"symbols\" is not sent:\n\n                {\n                \"assets\":[\n                    {\n                        \"baseAsset\":\n                        {\n                        \"asset\": \"BTC\",\n                        \"borrowEnabled\": true,\n                        \"borrowed\": \"0.00000000\",\n                        \"free\": \"0.00000000\",\n                        \"interest\": \"0.00000000\",\n                        \"locked\": \"0.00000000\",\n                        \"netAsset\": \"0.00000000\",\n                        \"netAssetOfBtc\": \"0.00000000\",\n                        \"repayEnabled\": true,\n                        \"totalAsset\": \"0.00000000\"\n                        },\n                        \"quoteAsset\":\n                        {\n                        \"asset\": \"USDT\",\n                        \"borrowEnabled\": true,\n                        \"borrowed\": \"0.00000000\",\n                        \"free\": \"0.00000000\",\n                        \"interest\": \"0.00000000\",\n                        \"locked\": \"0.00000000\",\n                        \"netAsset\": \"0.00000000\",\n                        \"netAssetOfBtc\": \"0.00000000\",\n                        \"repayEnabled\": true,\n                        \"totalAsset\": \"0.00000000\"\n                        },\n                        \"symbol\": \"BTCUSDT\"\n                        \"isolatedCreated\": true,\n                        \"marginLevel\": \"0.00000000\",\n                        \"marginLevelStatus\": \"EXCESSIVE\", // \"EXCESSIVE\", \"NORMAL\", \"MARGIN_CALL\", \"PRE_LIQUIDATION\", \"FORCE_LIQUIDATION\"\n                        \"marginRatio\": \"0.00000000\",\n                        \"indexPrice\": \"10000.00000000\"\n                        \"liquidatePrice\": \"1000.00000000\",\n                        \"liquidateRate\": \"1.00000000\"\n                        \"tradeEnabled\": true\n                    }\n                    ],\n                    \"totalAssetOfBtc\": \"0.00000000\",\n                    \"totalLiabilityOfBtc\": \"0.00000000\",\n                    \"totalNetAssetOfBtc\": \"0.00000000\"\n                }\n\n            If \"symbols\" is sent:\n\n                {\n                \"assets\":[\n                    {\n                        \"baseAsset\":\n                        {\n                        \"asset\": \"BTC\",\n                        \"borrowEnabled\": true,\n                        \"borrowed\": \"0.00000000\",\n                        \"free\": \"0.00000000\",\n                        \"interest\": \"0.00000000\",\n                        \"locked\": \"0.00000000\",\n                        \"netAsset\": \"0.00000000\",\n                        \"netAssetOfBtc\": \"0.00000000\",\n                        \"repayEnabled\": true,\n                        \"totalAsset\": \"0.00000000\"\n                        },\n                        \"quoteAsset\":\n                        {\n                        \"asset\": \"USDT\",\n                        \"borrowEnabled\": true,\n                        \"borrowed\": \"0.00000000\",\n                        \"free\": \"0.00000000\",\n                        \"interest\": \"0.00000000\",\n                        \"locked\": \"0.00000000\",\n                        \"netAsset\": \"0.00000000\",\n                        \"netAssetOfBtc\": \"0.00000000\",\n                        \"repayEnabled\": true,\n                        \"totalAsset\": \"0.00000000\"\n                        },\n                        \"symbol\": \"BTCUSDT\"\n                        \"isolatedCreated\": true,\n                        \"marginLevel\": \"0.00000000\",\n                        \"marginLevelStatus\": \"EXCESSIVE\", // \"EXCESSIVE\", \"NORMAL\", \"MARGIN_CALL\", \"PRE_LIQUIDATION\", \"FORCE_LIQUIDATION\"\n                        \"marginRatio\": \"0.00000000\",\n                        \"indexPrice\": \"10000.00000000\"\n                        \"liquidatePrice\": \"1000.00000000\",\n                        \"liquidateRate\": \"1.00000000\"\n                        \"tradeEnabled\": true\n                    }\n                    ]\n                }\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"margin/isolated/account\", True, data=params\n        )\n\n    def enable_isolated_margin_account(self, **params):\n        \"\"\"Enable isolated margin account for a specific symbol.\n\n        https://developers.binance.com/docs/margin_trading/account/Enable-Isolated-Margin-Account\n\n        :param symbol:\n        :type asset: str\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n              \"success\": true,\n              \"symbol\": \"BTCUSDT\"\n            }\n\n\n        \"\"\"\n        return self._request_margin_api(\n            \"post\", \"margin/isolated/account\", True, data=params\n        )\n\n    def disable_isolated_margin_account(self, **params):\n        \"\"\"Disable isolated margin account for a specific symbol. Each trading pair can only\n        be deactivated once every 24 hours.\n\n        https://developers.binance.com/docs/margin_trading/account/Disable-Isolated-Margin-Account\n\n        :param symbol:\n        :type asset: str\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n              \"success\": true,\n              \"symbol\": \"BTCUSDT\"\n            }\n\n        \"\"\"\n        return self._request_margin_api(\n            \"delete\", \"margin/isolated/account\", True, data=params\n        )\n\n    def get_enabled_isolated_margin_account_limit(self, **params):\n        \"\"\"Query enabled isolated margin account limit.\n\n        https://developers.binance.com/docs/margin_trading/account/Query-Enabled-Isolated-Margin-Account-Limit\n\n        :returns: API response\n\n        .. code-block:: python\n            {\n                \"enabledAccount\": 5,\n                \"maxAccount\": 20\n            }\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"margin/isolated/accountLimit\", True, data=params\n        )\n\n    def get_margin_dustlog(self, **params):\n        \"\"\"\n        Query the historical information of user's margin account small-value asset conversion BNB.\n\n        https://binance-docs.github.io/apidocs/spot/en/#margin-dustlog-user_data\n\n        :param startTime: optional\n        :type startTime: long\n        :param endTime: optional\n        :type endTime: long\n\n        :returns: API response\n\n        .. code-block:: python\n            {\n                \"total\": 8, //Total counts of exchange\n                \"userAssetDribblets\": [\n                    {\n                        \"operateTime\": 1615985535000,\n                        \"totalTransferedAmount\": \"0.00132256\", // Total transfered BNB amount for this exchange.\n                        \"totalServiceChargeAmount\": \"0.00002699\", //Total service charge amount for this exchange.\n                        \"transId\": 45178372831,\n                        \"userAssetDribbletDetails\": [ //Details of  this exchange.\n                            {\n                                \"transId\": 4359321,\n                                \"serviceChargeAmount\": \"0.000009\",\n                                \"amount\": \"0.0009\",\n                                \"operateTime\": 1615985535000,\n                                \"transferedAmount\": \"0.000441\",\n                                \"fromAsset\": \"USDT\"\n                            },\n                            {\n                                \"transId\": 4359321,\n                                \"serviceChargeAmount\": \"0.00001799\",\n                                \"amount\": \"0.0009\",\n                                \"operateTime\": 1615985535000,\n                                \"transferedAmount\": \"0.00088156\",\n                                \"fromAsset\": \"ETH\"\n                            }\n                        ]\n                    },\n                    {\n                        \"operateTime\":1616203180000,\n                        \"totalTransferedAmount\": \"0.00058795\",\n                        \"totalServiceChargeAmount\": \"0.000012\",\n                        \"transId\": 4357015,\n                        \"userAssetDribbletDetails\": [\n                            {\n                                \"transId\": 4357015,\n                                \"serviceChargeAmount\": \"0.00001\",\n                                \"amount\": \"0.001\",\n                                \"operateTime\": 1616203180000,\n                                \"transferedAmount\": \"0.00049\",\n                                \"fromAsset\": \"USDT\"\n                            },\n                            {\n                                \"transId\": 4357015,\n                                \"serviceChargeAmount\": \"0.000002\",\n                                \"amount\": \"0.0001\",\n                                \"operateTime\": 1616203180000,\n                                \"transferedAmount\": \"0.00009795\",\n                                \"fromAsset\": \"ETH\"\n                            }\n                        ]\n                    }\n                ]\n            }\n\n        \"\"\"\n        return self._request_margin_api(\"get\", \"margin/dribblet\", True, data=params)\n\n    def get_margin_dust_assets(self, **params):\n        \"\"\"Get margin assets that can be converted into BNB.\n\n        https://binance-docs.github.io/apidocs/spot/en/#margin-dustlog-user_data\n\n        :returns: API response\n\n        .. code-block:: python\n            {\n                \"details\": [\n                    {\n                        \"asset\": \"ADA\",\n                        \"assetFullName\": \"ADA\",\n                        \"amountFree\": \"6.21\",\n                        \"toBTC\": \"0.00016848\",\n                        \"toBNB\": \"0.01777302\",\n                        \"toBNBOffExchange\": \"0.01741756\",\n                        \"exchange\": \"0.00035546\"\n                    }\n                ],\n                \"totalTransferBtc\": \"0.00016848\",\n                \"totalTransferBNB\": \"0.01777302\",\n                \"dribbletPercentage\": \"0.02\"\n            }\n\n        \"\"\"\n        return self._request_margin_api(\"get\", \"margin/dust\", True, data=params)\n\n    def transfer_margin_dust(self, **params):\n        \"\"\"Convert dust assets to BNB.\n\n        https://binance-docs.github.io/apidocs/spot/en/#dust-transfer-trade\n\n        :returns: API response\n\n        .. code-block:: python\n            {\n                \"totalServiceCharge\":\"0.02102542\",\n                \"totalTransfered\":\"1.05127099\",\n                \"transferResult\":[\n                    {\n                        \"amount\":\"0.03000000\",\n                        \"fromAsset\":\"ETH\",\n                        \"operateTime\":1563368549307,\n                        \"serviceChargeAmount\":\"0.00500000\",\n                        \"tranId\":2970932918,\n                        \"transferedAmount\":\"0.25000000\"\n                    },\n                    {\n                        \"amount\":\"0.09000000\",\n                        \"fromAsset\":\"LTC\",\n                        \"operateTime\":1563368549404,\n                        \"serviceChargeAmount\":\"0.01548000\",\n                        \"tranId\":2970932918,\n                        \"transferedAmount\":\"0.77400000\"\n                    }\n                ]\n            }\n\n        \"\"\"\n        return self._request_margin_api(\"post\", \"margin/dust\", True, data=params)\n\n    def get_cross_margin_collateral_ratio(self, **params):\n        \"\"\"\n        https://developers.binance.com/docs/margin_trading/market-data\n\n        :param none\n\n        :returns: API response\n\n        .. code-block:: python\n            [\n              {\n                \"collaterals\": [\n                  {\n                    \"minUsdValue\": \"0\",\n                    \"maxUsdValue\": \"13000000\",\n                    \"discountRate\": \"1\"\n                  },\n                  {\n                    \"minUsdValue\": \"13000000\",\n                    \"maxUsdValue\": \"20000000\",\n                    \"discountRate\": \"0.975\"\n                  },\n                  {\n                    \"minUsdValue\": \"20000000\",\n                    \"discountRate\": \"0\"\n                  }\n                ],\n                \"assetNames\": [\n                  \"BNX\"\n                ]\n              },\n              {\n                \"collaterals\": [\n                  {\n                    \"minUsdValue\": \"0\",\n                    \"discountRate\": \"1\"\n                  }\n                ],\n                \"assetNames\": [\n                  \"BTC\",\n                  \"BUSD\",\n                  \"ETH\",\n                  \"USDT\"\n                ]\n              }\n            ]\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"margin/crossMarginCollateralRatio\", True, data=params\n        )\n\n    def get_small_liability_exchange_assets(self, **params):\n        \"\"\"Query the coins which can be small liability exchange\n\n        https://developers.binance.com/docs/margin_trading/trade/Get-Small-Liability-Exchange-Coin-List\n\n        :returns: API response\n\n        .. code-block:: python\n            [\n                {\n                  \"asset\": \"ETH\",\n                  \"interest\": \"0.00083334\",\n                  \"principal\": \"0.001\",\n                  \"liabilityAsset\": \"USDT\",\n                  \"liabilityQty\": 0.3552\n                }\n            ]\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"margin/exchange-small-liability\", True, data=params\n        )\n\n    def exchange_small_liability_assets(self, **params):\n        \"\"\"Cross Margin Small Liability Exchange\n\n        https://developers.binance.com/docs/margin_trading/trade/Small-Liability-Exchange\n\n        :param assetNames: The assets list of small liability exchange\n        :type assetNames: array\n\n        :returns: API response\n\n        .. code-block:: python\n        none\n\n        \"\"\"\n        return self._request_margin_api(\n            \"post\", \"margin/exchange-small-liability\", True, data=params\n        )\n\n    def get_small_liability_exchange_history(self, **params):\n        \"\"\"Get Small liability Exchange History\n\n        https://developers.binance.com/docs/margin_trading/trade/Get-Small-Liability-Exchange-History\n\n        :param current: Currently querying page. Start from 1. Default:1\n        :type current: int\n        :param size: Default:10, Max:100\n        :type size: int\n        :param startTime: Default: 30 days from current timestamp\n        :type startTime: long\n        :param endTime: Default: present timestamp\n        :type endTIme: long\n\n        :returns: API response\n\n        .. code-block:: python\n            {\n                \"total\": 1,\n                \"rows\": [\n                  {\n                    \"asset\": \"ETH\",\n                    \"amount\": \"0.00083434\",\n                    \"targetAsset\": \"BUSD\",\n                    \"targetAmount\": \"1.37576819\",\n                    \"bizType\": \"EXCHANGE_SMALL_LIABILITY\",\n                    \"timestamp\": 1672801339253\n                  }\n                ]\n            }\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"margin/exchange-small-liability-history\", True, data=params\n        )\n\n    def get_future_hourly_interest_rate(self, **params):\n        \"\"\"Get user the next hourly estimate interest\n\n        https://developers.binance.com/docs/margin_trading/borrow-and-repay\n\n        :param assets: List of assets, separated by commas, up to 20\n        :type assets: str\n        :param isIsolated: for isolated margin or not, \"TRUE\", \"FALSE\"\n        :type isIsolated: bool\n\n        :returns: API response\n\n        .. code-block:: python\n            [\n                {\n                    \"asset\": \"BTC\",\n                    \"nextHourlyInterestRate\": \"0.00000571\"\n                },\n                {\n                    \"asset\": \"ETH\",\n                    \"nextHourlyInterestRate\": \"0.00000578\"\n                }\n            ]\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"margin/next-hourly-interest-rate\", True, data=params\n        )\n\n    def get_margin_capital_flow(self, **params):\n        \"\"\"Get cross or isolated margin capital flow\n\n        https://developers.binance.com/docs/margin_trading/account/Query-Cross-Isolated-Margin-Capital-Flow\n\n        :param asset: optional\n        :type asset: str\n        :param symbol: Required when querying isolated data\n        :type symbol: str\n        :param type: optional\n        :type type: string\n        :param startTime: Only supports querying the data of the last 90 days\n        :type startTime: long\n        :param endTime: optional\n        :type endTime: long\n        :param formId: If fromId is set, the data with id > fromId will be returned. Otherwise the latest data will be returned\n        :type formId: long\n        :param limit: The number of data items returned each time is limited. Default 500; Max 1000.\n        :type limit: long\n\n        :returns: API response\n\n        .. code-block:: python\n            [\n              {\n                \"id\": 123456,\n                \"tranId\": 123123,\n                \"timestamp\": 1691116657000,\n                \"asset\": \"USDT,\n                \"symbol\": \"BTCUSDT\",\n                \"type\": \"BORROW\",\n                \"amount\": \"101\"\n              },\n              {\n                \"id\": 123457,\n                \"tranId\": 123124,\n                \"timestamp\": 1691116658000,\n                \"asset\": \"BTC\",\n                \"symbol\": \"BTCUSDT\",\n                \"type\": \"REPAY\",\n                \"amount\": \"10\"\n              }\n            ]\n\n        \"\"\"\n        return self._request_margin_api(\"get\", \"margin/capital-flow\", True, data=params)\n\n    def get_margin_asset(self, **params):\n        \"\"\"Query cross-margin asset\n\n        https://binance-docs.github.io/apidocs/spot/en/#query-margin-asset-market_data\n\n        :param asset: name of the asset\n        :type asset: str\n\n        .. code-block:: python\n\n            asset_details = client.get_margin_asset(asset='BNB')\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"assetFullName\": \"Binance Coin\",\n                \"assetName\": \"BNB\",\n                \"isBorrowable\": false,\n                \"isMortgageable\": true,\n                \"userMinBorrow\": \"0.00000000\",\n                \"userMinRepay\": \"0.00000000\"\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\"get\", \"margin/asset\", data=params)\n\n    def get_margin_symbol(self, **params):\n        \"\"\"Query cross-margin symbol info\n\n        https://binance-docs.github.io/apidocs/spot/en/#query-cross-margin-pair-market_data\n\n        :param symbol: name of the symbol pair\n        :type symbol: str\n\n        .. code:: python\n\n            pair_details = client.get_margin_symbol(symbol='BTCUSDT')\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"id\":323355778339572400,\n                \"symbol\":\"BTCUSDT\",\n                \"base\":\"BTC\",\n                \"quote\":\"USDT\",\n                \"isMarginTrade\":true,\n                \"isBuyAllowed\":true,\n                \"isSellAllowed\":true\n            }\n\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\"get\", \"margin/pair\", data=params)\n\n    def get_margin_all_assets(self, **params):\n        \"\"\"Get All Margin Assets (MARKET_DATA)\n\n        https://developers.binance.com/docs/margin_trading/market-data/Get-All-Margin-Assets\n\n        .. code:: python\n\n            margin_assets = client.get_margin_all_assets()\n\n        :returns: API response\n\n        .. code-block:: python\n\n            [\n                {\n                    \"assetFullName\": \"USD coin\",\n                    \"assetName\": \"USDC\",\n                    \"isBorrowable\": true,\n                    \"isMortgageable\": true,\n                    \"userMinBorrow\": \"0.00000000\",\n                    \"userMinRepay\": \"0.00000000\"\n                },\n                {\n                    \"assetFullName\": \"BNB-coin\",\n                    \"assetName\": \"BNB\",\n                    \"isBorrowable\": true,\n                    \"isMortgageable\": true,\n                    \"userMinBorrow\": \"1.00000000\",\n                    \"userMinRepay\": \"0.00000000\"\n                }\n            ]\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\"get\", \"margin/allAssets\", data=params)\n\n    def get_margin_all_pairs(self, **params):\n        \"\"\"Get All Cross Margin Pairs (MARKET_DATA)\n\n        https://developers.binance.com/docs/margin_trading/market-data/Get-All-Cross-Margin-Pairs\n\n        .. code:: python\n\n            margin_pairs = client.get_margin_all_pairs()\n\n        :returns: API response\n\n        .. code-block:: python\n\n            [\n                {\n                    \"base\": \"BNB\",\n                    \"id\": 351637150141315861,\n                    \"isBuyAllowed\": true,\n                    \"isMarginTrade\": true,\n                    \"isSellAllowed\": true,\n                    \"quote\": \"BTC\",\n                    \"symbol\": \"BNBBTC\"\n                },\n                {\n                    \"base\": \"TRX\",\n                    \"id\": 351637923235429141,\n                    \"isBuyAllowed\": true,\n                    \"isMarginTrade\": true,\n                    \"isSellAllowed\": true,\n                    \"quote\": \"BTC\",\n                    \"symbol\": \"TRXBTC\"\n                }\n            ]\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\"get\", \"margin/allPairs\", data=params)\n\n    def create_isolated_margin_account(self, **params):\n        \"\"\"Create isolated margin account for symbol\n\n        https://binance-docs.github.io/apidocs/spot/en/#create-isolated-margin-account-margin\n\n        :param base: Base asset of symbol\n        :type base: str\n        :param quote: Quote asset of symbol\n        :type quote: str\n\n        .. code:: python\n\n            pair_details = client.create_isolated_margin_account(base='USDT', quote='BTC')\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"success\": true,\n                \"symbol\": \"BTCUSDT\"\n            }\n\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"post\", \"margin/isolated/create\", signed=True, data=params\n        )\n\n    def get_isolated_margin_symbol(self, **params):\n        \"\"\"Query isolated margin symbol info\n\n        https://binance-docs.github.io/apidocs/spot/en/#query-isolated-margin-symbol-user_data\n\n        :param symbol: name of the symbol pair\n        :type symbol: str\n\n        .. code:: python\n\n            pair_details = client.get_isolated_margin_symbol(symbol='BTCUSDT')\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n            \"symbol\":\"BTCUSDT\",\n            \"base\":\"BTC\",\n            \"quote\":\"USDT\",\n            \"isMarginTrade\":true,\n            \"isBuyAllowed\":true,\n            \"isSellAllowed\":true\n            }\n\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"margin/isolated/pair\", signed=True, data=params\n        )\n\n    def get_all_isolated_margin_symbols(self, **params):\n        \"\"\"Query isolated margin symbol info for all pairs\n\n        https://developers.binance.com/docs/margin_trading/market-data/Get-All-Isolated-Margin-Symbol\n\n        .. code:: python\n\n            pair_details = client.get_all_isolated_margin_symbols()\n\n        :returns: API response\n\n        .. code-block:: python\n\n            [\n                {\n                    \"base\": \"BNB\",\n                    \"isBuyAllowed\": true,\n                    \"isMarginTrade\": true,\n                    \"isSellAllowed\": true,\n                    \"quote\": \"BTC\",\n                    \"symbol\": \"BNBBTC\"\n                },\n                {\n                    \"base\": \"TRX\",\n                    \"isBuyAllowed\": true,\n                    \"isMarginTrade\": true,\n                    \"isSellAllowed\": true,\n                    \"quote\": \"BTC\",\n                    \"symbol\": \"TRXBTC\"\n                }\n            ]\n\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"margin/isolated/allPairs\", signed=True, data=params\n        )\n\n    def get_isolated_margin_fee_data(self, **params):\n        \"\"\"Get isolated margin fee data collection with any vip level or user's current specific data as https://www.binance.com/en/margin-fee\n\n        https://developers.binance.com/docs/margin_trading/account/Query-Isolated-Margin-Fee-Data\n\n        :param vipLevel: User's current specific margin data will be returned if vipLevel is omitted\n        :type vipLevel: int\n        :param symbol: optional\n        :type symbol: str\n\n        :returns: API response\n\n        .. code-block:: python\n            [\n                {\n                    \"vipLevel\": 0,\n                    \"symbol\": \"BTCUSDT\",\n                    \"leverage\": \"10\",\n                    \"data\": [\n                        {\n                            \"coin\": \"BTC\",\n                            \"dailyInterest\": \"0.00026125\",\n                            \"borrowLimit\": \"270\"\n                        },\n                        {\n                            \"coin\": \"USDT\",\n                            \"dailyInterest\": \"0.000475\",\n                            \"borrowLimit\": \"2100000\"\n                        }\n                    ]\n                }\n            ]\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"margin/isolatedMarginData\", True, data=params\n        )\n\n    def get_isolated_margin_tier_data(self, **params):\n        \"\"\"Get isolated margin tier data collection with any tier as https://www.binance.com/en/margin-data\n\n        https://developers.binance.com/docs/margin_trading/market-data/Query-Isolated-Margin-Tier-Data\n\n        :param symbol: required\n        :type symbol: str\n        :param tier: All margin tier data will be returned if tier is omitted\n        :type tier: int\n        :param recvWindow: optional: No more than 60000\n        :type recvWindow:\n\n        :returns: API response\n\n        .. code-block:: python\n            [\n                {\n                    \"symbol\": \"BTCUSDT\",\n                    \"tier\": 1,\n                    \"effectiveMultiple\": \"10\",\n                    \"initialRiskRatio\": \"1.111\",\n                    \"liquidationRiskRatio\": \"1.05\",\n                    \"baseAssetMaxBorrowable\": \"9\",\n                    \"quoteAssetMaxBorrowable\": \"70000\"\n                }\n            ]\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"margin/isolatedMarginTier\", True, data=params\n        )\n\n    def margin_manual_liquidation(self, **params):\n        \"\"\"\n\n        https://developers.binance.com/docs/margin_trading/trade/Margin-Manual-Liquidation\n\n\n\n        :param type: required\n        :type symbol: str: When type selected is \"ISOLATED\", symbol must be filled in\n\n        :returns: API response\n\n            [\n                {\n                    \"asset\": \"ETH\",\n                    \"interest\": \"0.00083334\",\n                    \"principal\": \"0.001\",\n                    \"liabilityAsset\": \"USDT\",\n                    \"liabilityQty\": 0.3552\n                }\n            ]\n\n        \"\"\"\n        return self._request_margin_api(\n            \"post\", \"margin/manual-liquidation\", True, data=params\n        )\n\n    def toggle_bnb_burn_spot_margin(self, **params):\n        \"\"\"Toggle BNB Burn On Spot Trade And Margin Interest\n\n        https://developers.binance.com/docs/wallet/asset/Toggle-BNB-Burn-On-Spot-Trade-And-Margin-Interest\n\n        :param spotBNBBurn: Determines whether to use BNB to pay for trading fees on SPOT\n        :type spotBNBBurn: bool\n        :param interestBNBBurn: Determines whether to use BNB to pay for margin loan's interest\n        :type interestBNBBurn: bool\n\n        .. code:: python\n\n            response = client.toggle_bnb_burn_spot_margin()\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n               \"spotBNBBurn\":true,\n               \"interestBNBBurn\": false\n            }\n\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\"post\", \"bnbBurn\", signed=True, data=params)\n\n    def get_bnb_burn_spot_margin(self, **params):\n        \"\"\"Get BNB Burn Status\n\n        https://developers.binance.com/docs/margin_trading/account/Get-BNB-Burn-Status\n\n        .. code:: python\n\n            status = client.get_bnb_burn_spot_margin()\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n               \"spotBNBBurn\":true,\n               \"interestBNBBurn\": false\n            }\n\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\"get\", \"bnbBurn\", signed=True, data=params)\n\n    def get_margin_price_index(self, **params):\n        \"\"\"Query margin priceIndex\n\n        https://developers.binance.com/docs/margin_trading/market-data/Query-Margin-PriceIndex\n\n        :param symbol: name of the symbol pair\n        :type symbol: str\n\n        .. code:: python\n\n            price_index_details = client.get_margin_price_index(symbol='BTCUSDT')\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"calcTime\": 1562046418000,\n                \"price\": \"0.00333930\",\n                \"symbol\": \"BNBBTC\"\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\"get\", \"margin/priceIndex\", data=params)\n\n    def transfer_margin_to_spot(self, **params):\n        \"\"\"Execute transfer between cross-margin account and spot account.\n\n        https://binance-docs.github.io/apidocs/spot/en/#cross-margin-account-transfer-margin\n\n        :param asset: name of the asset\n        :type asset: str\n        :param amount: amount to transfer\n        :type amount: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        .. code-block:: python\n\n            transfer = client.transfer_margin_to_spot(asset='BTC', amount='1.1')\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"tranId\": 100000001\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        params[\"type\"] = 2\n        return self._request_margin_api(\n            \"post\", \"margin/transfer\", signed=True, data=params\n        )\n\n    def transfer_spot_to_margin(self, **params):\n        \"\"\"Execute transfer between spot account and cross-margin account.\n\n        https://binance-docs.github.io/apidocs/spot/en/#cross-margin-account-transfer-margin\n\n        :param asset: name of the asset\n        :type asset: str\n        :param amount: amount to transfer\n        :type amount: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        .. code-block:: python\n\n            transfer = client.transfer_spot_to_margin(asset='BTC', amount='1.1')\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"tranId\": 100000001\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        params[\"type\"] = 1\n        return self._request_margin_api(\n            \"post\", \"margin/transfer\", signed=True, data=params\n        )\n\n    def transfer_isolated_margin_to_spot(self, **params):\n        \"\"\"Execute transfer between isolated margin account and spot account.\n\n        https://binance-docs.github.io/apidocs/spot/en/#isolated-margin-account-transfer-margin\n\n        :param asset: name of the asset\n        :type asset: str\n        :param symbol: pair symbol\n        :type symbol: str\n        :param amount: amount to transfer\n        :type amount: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        .. code-block:: python\n\n            transfer = client.transfer_isolated_margin_to_spot(asset='BTC',\n                                                                symbol='ETHBTC', amount='1.1')\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"tranId\": 100000001\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        params[\"transFrom\"] = \"ISOLATED_MARGIN\"\n        params[\"transTo\"] = \"SPOT\"\n        return self._request_margin_api(\n            \"post\", \"margin/isolated/transfer\", signed=True, data=params\n        )\n\n    def transfer_spot_to_isolated_margin(self, **params):\n        \"\"\"Execute transfer between spot account and isolated margin account.\n\n        https://binance-docs.github.io/apidocs/spot/en/#isolated-margin-account-transfer-margin\n\n        :param asset: name of the asset\n        :type asset: str\n        :param symbol: pair symbol\n        :type symbol: str\n        :param amount: amount to transfer\n        :type amount: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        .. code-block:: python\n\n            transfer = client.transfer_spot_to_isolated_margin(asset='BTC',\n                                                                symbol='ETHBTC', amount='1.1')\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"tranId\": 100000001\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        params[\"transFrom\"] = \"SPOT\"\n        params[\"transTo\"] = \"ISOLATED_MARGIN\"\n        return self._request_margin_api(\n            \"post\", \"margin/isolated/transfer\", signed=True, data=params\n        )\n\n    def get_isolated_margin_tranfer_history(self, **params):\n        \"\"\"Get transfers to isolated margin account.\n\n        https://binance-docs.github.io/apidocs/spot/en/#get-isolated-margin-transfer-history-user_data\n\n        :param asset: name of the asset\n        :type asset: str\n        :param symbol: pair required\n        :type symbol: str\n        :param transFrom: optional SPOT, ISOLATED_MARGIN\n        :param transFrom: str SPOT, ISOLATED_MARGIN\n        :param transTo: optional\n        :param transTo: str\n        :param startTime: optional\n        :type startTime: int\n        :param endTime: optional\n        :type endTime: int\n        :param current: Currently querying page. Start from 1. Default:1\n        :type current: str\n        :param size: Default:10 Max:100\n        :type size: int\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        .. code-block:: python\n\n            transfer = client.transfer_spot_to_isolated_margin(symbol='ETHBTC')\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n              \"rows\": [\n                {\n                  \"amount\": \"0.10000000\",\n                  \"asset\": \"BNB\",\n                  \"status\": \"CONFIRMED\",\n                  \"timestamp\": 1566898617000,\n                  \"txId\": 5240372201,\n                  \"transFrom\": \"SPOT\",\n                  \"transTo\": \"ISOLATED_MARGIN\"\n                },\n                {\n                  \"amount\": \"5.00000000\",\n                  \"asset\": \"USDT\",\n                  \"status\": \"CONFIRMED\",\n                  \"timestamp\": 1566888436123,\n                  \"txId\": 5239810406,\n                  \"transFrom\": \"ISOLATED_MARGIN\",\n                  \"transTo\": \"SPOT\"\n                }\n              ],\n              \"total\": 2\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"margin/isolated/transfer\", signed=True, data=params\n        )\n\n    def create_margin_loan(self, **params):\n        \"\"\"Apply for a loan in cross-margin or isolated-margin account.\n\n        https://binance-docs.github.io/apidocs/spot/en/#margin-account-borrow-margin\n\n        :param asset: name of the asset\n        :type asset: str\n        :param amount: amount to transfer\n        :type amount: str\n        :param isIsolated: set to 'TRUE' for isolated margin (default 'FALSE')\n        :type isIsolated: str\n        :param symbol: Isolated margin symbol (default blank for cross-margin)\n        :type symbol: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        .. code-block:: python\n\n            transaction = client.margin_create_loan(asset='BTC', amount='1.1')\n\n            transaction = client.margin_create_loan(asset='BTC', amount='1.1',\n                                                    isIsolated='TRUE', symbol='ETHBTC')\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"tranId\": 100000001\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\"post\", \"margin/loan\", signed=True, data=params)\n\n    def repay_margin_loan(self, **params):\n        \"\"\"Repay loan in cross-margin or isolated-margin account.\n\n        If amount is more than the amount borrowed, the full loan will be repaid.\n\n        https://binance-docs.github.io/apidocs/spot/en/#margin-account-repay-margin\n\n        :param asset: name of the asset\n        :type asset: str\n        :param amount: amount to transfer\n        :type amount: str\n        :param isIsolated: set to 'TRUE' for isolated margin (default 'FALSE')\n        :type isIsolated: str\n        :param symbol: Isolated margin symbol (default blank for cross-margin)\n        :type symbol: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        .. code-block:: python\n\n            transaction = client.margin_repay_loan(asset='BTC', amount='1.1')\n\n            transaction = client.margin_repay_loan(asset='BTC', amount='1.1',\n                                                    isIsolated='TRUE', symbol='ETHBTC')\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"tranId\": 100000001\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"post\", \"margin/repay\", signed=True, data=params\n        )\n\n    def create_margin_order(self, **params):\n        \"\"\"Post a new order for margin account.\n\n        https://developers.binance.com/docs/margin_trading/trade/Margin-Account-New-Order\n\n        :param symbol: required\n        :type symbol: str\n        :param isIsolated: set to 'TRUE' for isolated margin (default 'FALSE')\n        :type isIsolated: str\n        :param side: required\n        :type side: str\n        :param type: required\n        :type type: str\n        :param quantity: required\n        :type quantity: decimal\n        :param price: required\n        :type price: str\n        :param stopPrice: Used with STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, and TAKE_PROFIT_LIMIT orders.\n        :type stopPrice: str\n        :param timeInForce: required if limit order GTC,IOC,FOK\n        :type timeInForce: str\n        :param newClientOrderId: A unique id for the order. Automatically generated if not sent.\n        :type newClientOrderId: str\n        :param icebergQty: Used with LIMIT, STOP_LOSS_LIMIT, and TAKE_PROFIT_LIMIT to create an iceberg order.\n        :type icebergQty: str\n        :param newOrderRespType: Set the response JSON. ACK, RESULT, or FULL; MARKET and LIMIT order types default to\n            FULL, all other orders default to ACK.\n        :type newOrderRespType: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        Response ACK:\n\n        .. code-block:: python\n\n            {\n                \"symbol\": \"BTCUSDT\",\n                \"orderId\": 28,\n                \"clientOrderId\": \"6gCrw2kRUAF9CvJDGP16IP\",\n                \"transactTime\": 1507725176595\n            }\n\n        Response RESULT:\n\n        .. code-block:: python\n\n            {\n                \"symbol\": \"BTCUSDT\",\n                \"orderId\": 28,\n                \"clientOrderId\": \"6gCrw2kRUAF9CvJDGP16IP\",\n                \"transactTime\": 1507725176595,\n                \"price\": \"1.00000000\",\n                \"origQty\": \"10.00000000\",\n                \"executedQty\": \"10.00000000\",\n                \"cummulativeQuoteQty\": \"10.00000000\",\n                \"status\": \"FILLED\",\n                \"timeInForce\": \"GTC\",\n                \"type\": \"MARKET\",\n                \"side\": \"SELL\"\n            }\n\n        Response FULL:\n\n        .. code-block:: python\n\n            {\n                \"symbol\": \"BTCUSDT\",\n                \"orderId\": 28,\n                \"clientOrderId\": \"6gCrw2kRUAF9CvJDGP16IP\",\n                \"transactTime\": 1507725176595,\n                \"price\": \"1.00000000\",\n                \"origQty\": \"10.00000000\",\n                \"executedQty\": \"10.00000000\",\n                \"cummulativeQuoteQty\": \"10.00000000\",\n                \"status\": \"FILLED\",\n                \"timeInForce\": \"GTC\",\n                \"type\": \"MARKET\",\n                \"side\": \"SELL\",\n                \"fills\": [\n                    {\n                        \"price\": \"4000.00000000\",\n                        \"qty\": \"1.00000000\",\n                        \"commission\": \"4.00000000\",\n                        \"commissionAsset\": \"USDT\"\n                    },\n                    {\n                        \"price\": \"3999.00000000\",\n                        \"qty\": \"5.00000000\",\n                        \"commission\": \"19.99500000\",\n                        \"commissionAsset\": \"USDT\"\n                    },\n                    {\n                        \"price\": \"3998.00000000\",\n                        \"qty\": \"2.00000000\",\n                        \"commission\": \"7.99600000\",\n                        \"commissionAsset\": \"USDT\"\n                    },\n                    {\n                        \"price\": \"3997.00000000\",\n                        \"qty\": \"1.00000000\",\n                        \"commission\": \"3.99700000\",\n                        \"commissionAsset\": \"USDT\"\n                    },\n                    {\n                        \"price\": \"3995.00000000\",\n                        \"qty\": \"1.00000000\",\n                        \"commission\": \"3.99500000\",\n                        \"commissionAsset\": \"USDT\"\n                    }\n                ]\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException,\n            BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException,\n            BinanceOrderInactiveSymbolException\n\n        \"\"\"\n        if \"newClientOrderId\" not in params:\n            params[\"newClientOrderId\"] = self.SPOT_ORDER_PREFIX + self.uuid22()\n        return self._request_margin_api(\n            \"post\", \"margin/order\", signed=True, data=params\n        )\n\n    def cancel_margin_order(self, **params):\n        \"\"\"Cancel an active order for margin account.\n\n        Either orderId or origClientOrderId must be sent.\n\n        https://developers.binance.com/docs/margin_trading/trade/Margin-Account-Cancel-Order\n\n        :param symbol: required\n        :type symbol: str\n        :param isIsolated: set to 'TRUE' for isolated margin (default 'FALSE')\n        :type isIsolated: str\n        :param orderId:\n        :type orderId: str\n        :param origClientOrderId:\n        :type origClientOrderId: str\n        :param newClientOrderId: Used to uniquely identify this cancel. Automatically generated by default.\n        :type newClientOrderId: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n            {\n                \"symbol\": \"LTCBTC\",\n                \"orderId\": 28,\n                \"origClientOrderId\": \"myOrder1\",\n                \"clientOrderId\": \"cancelMyOrder1\",\n                \"transactTime\": 1507725176595,\n                \"price\": \"1.00000000\",\n                \"origQty\": \"10.00000000\",\n                \"executedQty\": \"8.00000000\",\n                \"cummulativeQuoteQty\": \"8.00000000\",\n                \"status\": \"CANCELED\",\n                \"timeInForce\": \"GTC\",\n                \"type\": \"LIMIT\",\n                \"side\": \"SELL\"\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"delete\", \"margin/order\", signed=True, data=params\n        )\n\n    def cancel_all_open_margin_orders(self, **params):\n        \"\"\"\n        Cancels all active orders on a symbol for margin account.\n\n        https://developers.binance.com/docs/margin_trading/trade/Margin-Account-Cancel-All-Open-Orders\n\n        :param symbol: required\n        :type symbol: str\n        :param isIsolated: set to 'TRUE' for isolated margin (default 'FALSE')\n        :type isIsolated: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n        :returns: API response\n\n        :raises: BinanceRequestException, BinanceAPIException\n        \"\"\"\n        return self._request_margin_api(\n            \"delete\", \"margin/openOrders\", signed=True, data=params\n        )\n\n    def set_margin_max_leverage(self, **params):\n        \"\"\"Adjust cross margin max leverage\n\n        https://developers.binance.com/docs/margin_trading/account\n\n        :param maxLeverage: required Can only adjust 3 or 5，Example: maxLeverage=3\n        :type maxLeverage: int\n\n        :returns: API response\n\n            {\n                \"success\": true\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"post\", \"margin/max-leverage\", signed=True, data=params\n        )\n\n    def get_margin_transfer_history(self, **params):\n        \"\"\"Query margin transfer history\n\n        https://developers.binance.com/docs/margin_trading/transfer\n\n        :param asset: optional\n        :type asset: str\n        :param type: optional Transfer Type: ROLL_IN, ROLL_OUT\n        :type type: str\n        :param archived: optional Default: false. Set to true for archived data from 6 months ago\n        :type archived: str\n        :param startTime: earliest timestamp to filter transactions\n        :type startTime: str\n        :param endTime: Used to uniquely identify this cancel. Automatically generated by default.\n        :type endTime: str\n        :param current: Currently querying page. Start from 1. Default:1\n        :type current: str\n        :param size: Default:10 Max:100\n        :type size: int\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n            {\n                \"rows\": [\n                    {\n                        \"amount\": \"0.10000000\",\n                        \"asset\": \"BNB\",\n                        \"status\": \"CONFIRMED\",\n                        \"timestamp\": 1566898617,\n                        \"txId\": 5240372201,\n                        \"type\": \"ROLL_IN\"\n                    },\n                    {\n                        \"amount\": \"5.00000000\",\n                        \"asset\": \"USDT\",\n                        \"status\": \"CONFIRMED\",\n                        \"timestamp\": 1566888436,\n                        \"txId\": 5239810406,\n                        \"type\": \"ROLL_OUT\"\n                    },\n                    {\n                        \"amount\": \"1.00000000\",\n                        \"asset\": \"EOS\",\n                        \"status\": \"CONFIRMED\",\n                        \"timestamp\": 1566888403,\n                        \"txId\": 5239808703,\n                        \"type\": \"ROLL_IN\"\n                    }\n                ],\n                \"total\": 3\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"margin/transfer\", signed=True, data=params\n        )\n\n    def get_margin_loan_details(self, **params):\n        \"\"\"Query loan record\n\n        txId or startTime must be sent. txId takes precedence.\n\n        https://binance-docs.github.io/apidocs/spot/en/#query-loan-record-user_data\n\n        :param asset: required\n        :type asset: str\n        :param isolatedSymbol: isolated symbol (if querying isolated margin)\n        :type isolatedSymbol: str\n        :param txId: the tranId in of the created loan\n        :type txId: str\n        :param startTime: earliest timestamp to filter transactions\n        :type startTime: str\n        :param endTime: Used to uniquely identify this cancel. Automatically generated by default.\n        :type endTime: str\n        :param current: Currently querying page. Start from 1. Default:1\n        :type current: str\n        :param size: Default:10 Max:100\n        :type size: int\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n            {\n                \"rows\": [\n                    {\n                        \"asset\": \"BNB\",\n                        \"principal\": \"0.84624403\",\n                        \"timestamp\": 1555056425000,\n                        //one of PENDING (pending to execution), CONFIRMED (successfully loaned), FAILED (execution failed, nothing happened to your account);\n                        \"status\": \"CONFIRMED\"\n                    }\n                ],\n                \"total\": 1\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\"get\", \"margin/loan\", signed=True, data=params)\n\n    def get_margin_repay_details(self, **params):\n        \"\"\"Query repay record\n\n        txId or startTime must be sent. txId takes precedence.\n\n        https://binance-docs.github.io/apidocs/spot/en/#query-repay-record-user_data\n\n        :param asset: required\n        :type asset: str\n        :param isolatedSymbol: isolated symbol (if querying isolated margin)\n        :type isolatedSymbol: str\n        :param txId: the tranId in of the created loan\n        :type txId: str\n        :param startTime:\n        :type startTime: str\n        :param endTime: Used to uniquely identify this cancel. Automatically generated by default.\n        :type endTime: str\n        :param current: Currently querying page. Start from 1. Default:1\n        :type current: str\n        :param size: Default:10 Max:100\n        :type size: int\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n            {\n                \"rows\": [\n                    {\n                        //Total amount repaid\n                        \"amount\": \"14.00000000\",\n                        \"asset\": \"BNB\",\n                        //Interest repaid\n                        \"interest\": \"0.01866667\",\n                        //Principal repaid\n                        \"principal\": \"13.98133333\",\n                        //one of PENDING (pending to execution), CONFIRMED (successfully loaned), FAILED (execution failed, nothing happened to your account);\n                        \"status\": \"CONFIRMED\",\n                        \"timestamp\": 1563438204000,\n                        \"txId\": 2970933056\n                    }\n                ],\n                \"total\": 1\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\"get\", \"margin/repay\", signed=True, data=params)\n\n    def get_cross_margin_data(self, **params):\n        \"\"\"Query Cross Margin Fee Data (USER_DATA)\n\n        https://developers.binance.com/docs/margin_trading/account/Query-Cross-Margin-Fee-Data\n\n        :param vipLevel: User's current specific margin data will be returned if vipLevel is omitted\n        :type vipLevel: int\n        :param coin\n        :type coin: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n        :returns: API response (example):\n            [\n                {\n                    \"vipLevel\": 0,\n                    \"coin\": \"BTC\",\n                    \"transferIn\": true,\n                    \"borrowable\": true,\n                    \"dailyInterest\": \"0.00026125\",\n                    \"yearlyInterest\": \"0.0953\",\n                    \"borrowLimit\": \"180\",\n                    \"marginablePairs\": [\n                        \"BNBBTC\",\n                        \"TRXBTC\",\n                        \"ETHBTC\",\n                        \"BTCUSDT\"\n                    ]\n                }\n            ]\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"margin/crossMarginData\", signed=True, data=params\n        )\n\n    def get_margin_interest_history(self, **params):\n        \"\"\"Get Interest History (USER_DATA)\n\n        https://developers.binance.com/docs/margin_trading/borrow-and-repay/Get-Interest-History\n\n        :param asset:\n        :type asset: str\n        :param isolatedSymbol: isolated symbol (if querying isolated margin)\n        :type isolatedSymbol: str\n        :param startTime:\n        :type startTime: str\n        :param endTime:\n        :type endTime: str\n        :param current: Currently querying page. Start from 1. Default:1\n        :type current: str\n        :param size: Default:10 Max:100\n        :type size: int\n        :param archived: Default: false. Set to true for archived data from 6 months ago\n        :type archived: bool\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n            {\n                \"rows\":[\n                    {\n                        \"isolatedSymbol\": \"BNBUSDT\", // isolated symbol, will not be returned for crossed margin\n                        \"asset\": \"BNB\",\n                        \"interest\": \"0.02414667\",\n                        \"interestAccuredTime\": 1566813600000,\n                        \"interestRate\": \"0.01600000\",\n                        \"principal\": \"36.22000000\",\n                        \"type\": \"ON_BORROW\"\n                    }\n                ],\n                \"total\": 1\n            }\n\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"margin/interestHistory\", signed=True, data=params\n        )\n\n    def get_margin_force_liquidation_rec(self, **params):\n        \"\"\"Get Force Liquidation Record (USER_DATA)\n\n        https://developers.binance.com/docs/margin_trading/trade\n\n        :param startTime:\n        :type startTime: str\n        :param endTime:\n        :type endTime: str\n        :param isolatedSymbol: isolated symbol (if querying isolated margin)\n        :type isolatedSymbol: str\n        :param current: Currently querying page. Start from 1. Default:1\n        :type current: str\n        :param size: Default:10 Max:100\n        :type size: int\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n            {\n                \"rows\": [\n                    {\n                        \"avgPrice\": \"0.00388359\",\n                        \"executedQty\": \"31.39000000\",\n                        \"orderId\": 180015097,\n                        \"price\": \"0.00388110\",\n                        \"qty\": \"31.39000000\",\n                        \"side\": \"SELL\",\n                        \"symbol\": \"BNBBTC\",\n                        \"timeInForce\": \"GTC\",\n                        \"isIsolated\": true,\n                        \"updatedTime\": 1558941374745\n                    }\n                ],\n                \"total\": 1\n            }\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"margin/forceLiquidationRec\", signed=True, data=params\n        )\n\n    def get_margin_order(self, **params):\n        \"\"\"Query margin accounts order\n\n        Either orderId or origClientOrderId must be sent.\n\n        For some historical orders cummulativeQuoteQty will be < 0, meaning the data is not available at this time.\n\n        https://developers.binance.com/docs/margin_trading/trade/Query-Margin-Account-Order\n\n        :param symbol: required\n        :type symbol: str\n        :param isIsolated: set to 'TRUE' for isolated margin (default 'FALSE')\n        :type isIsolated: str\n        :param orderId:\n        :type orderId: str\n        :param origClientOrderId:\n        :type origClientOrderId: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n            {\n                \"clientOrderId\": \"ZwfQzuDIGpceVhKW5DvCmO\",\n                \"cummulativeQuoteQty\": \"0.00000000\",\n                \"executedQty\": \"0.00000000\",\n                \"icebergQty\": \"0.00000000\",\n                \"isWorking\": true,\n                \"orderId\": 213205622,\n                \"origQty\": \"0.30000000\",\n                \"price\": \"0.00493630\",\n                \"side\": \"SELL\",\n                \"status\": \"NEW\",\n                \"stopPrice\": \"0.00000000\",\n                \"symbol\": \"BNBBTC\",\n                \"time\": 1562133008725,\n                \"timeInForce\": \"GTC\",\n                \"type\": \"LIMIT\",\n                \"updateTime\": 1562133008725\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\"get\", \"margin/order\", signed=True, data=params)\n\n    def get_open_margin_orders(self, **params):\n        \"\"\"Query margin accounts open orders\n\n        If the symbol is not sent, orders for all symbols will be returned in an array (cross-margin only).\n\n        If querying isolated margin orders, both the isIsolated='TRUE' and symbol=symbol_name must be set.\n\n        When all symbols are returned, the number of requests counted against the rate limiter is equal to the number\n        of symbols currently trading on the exchange.\n\n        https://developers.binance.com/docs/margin_trading/trade/Query-Margin-Account-Open-Orders\n\n        :param symbol: optional\n        :type symbol: str\n        :param isIsolated: set to 'TRUE' for isolated margin (default 'FALSE')\n        :type isIsolated: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n            [\n                {\n                    \"clientOrderId\": \"qhcZw71gAkCCTv0t0k8LUK\",\n                    \"cummulativeQuoteQty\": \"0.00000000\",\n                    \"executedQty\": \"0.00000000\",\n                    \"icebergQty\": \"0.00000000\",\n                    \"isWorking\": true,\n                    \"orderId\": 211842552,\n                    \"origQty\": \"0.30000000\",\n                    \"price\": \"0.00475010\",\n                    \"side\": \"SELL\",\n                    \"status\": \"NEW\",\n                    \"stopPrice\": \"0.00000000\",\n                    \"symbol\": \"BNBBTC\",\n                    \"time\": 1562040170089,\n                    \"timeInForce\": \"GTC\",\n                    \"type\": \"LIMIT\",\n                    \"updateTime\": 1562040170089\n                }\n            ]\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"margin/openOrders\", signed=True, data=params\n        )\n\n    def get_all_margin_orders(self, **params):\n        \"\"\"Query all margin accounts orders\n\n        If orderId is set, it will get orders >= that orderId. Otherwise most recent orders are returned.\n\n        For some historical orders cummulativeQuoteQty will be < 0, meaning the data is not available at this time.\n\n        https://developers.binance.com/docs/margin_trading/trade/Query-Margin-Account-All-Orders\n\n        :param symbol: required\n        :type symbol: str\n        :param isIsolated: set to 'TRUE' for isolated margin (default 'FALSE')\n        :type isIsolated: str\n        :param orderId: optional\n        :type orderId: str\n        :param startTime: optional\n        :type startTime: str\n        :param endTime: optional\n        :type endTime: str\n        :param limit: Default 500; max 1000\n        :type limit: int\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n            [\n                {\n                    \"id\": 43123876,\n                    \"price\": \"0.00395740\",\n                    \"qty\": \"4.06000000\",\n                    \"quoteQty\": \"0.01606704\",\n                    \"symbol\": \"BNBBTC\",\n                    \"time\": 1556089977693\n                },\n                {\n                    \"id\": 43123877,\n                    \"price\": \"0.00395740\",\n                    \"qty\": \"0.77000000\",\n                    \"quoteQty\": \"0.00304719\",\n                    \"symbol\": \"BNBBTC\",\n                    \"time\": 1556089977693\n                },\n                {\n                    \"id\": 43253549,\n                    \"price\": \"0.00428930\",\n                    \"qty\": \"23.30000000\",\n                    \"quoteQty\": \"0.09994069\",\n                    \"symbol\": \"BNBBTC\",\n                    \"time\": 1556163963504\n                }\n            ]\n\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"margin/allOrders\", signed=True, data=params\n        )\n\n    def get_margin_trades(self, **params):\n        \"\"\"Query margin accounts trades\n\n        If fromId is set, it will get orders >= that fromId. Otherwise most recent orders are returned.\n\n        https://developers.binance.com/docs/margin_trading/trade/Query-Margin-Account-Trade-List\n\n        :param symbol: required\n        :type symbol: str\n        :param isIsolated: set to 'TRUE' for isolated margin (default 'FALSE')\n        :type isIsolated: str\n        :param fromId: optional\n        :type fromId: str\n        :param startTime: optional\n        :type startTime: str\n        :param endTime: optional\n        :type endTime: str\n        :param limit: Default 500; max 1000\n        :type limit: int\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n            [\n                {\n                    \"commission\": \"0.00006000\",\n                    \"commissionAsset\": \"BTC\",\n                    \"id\": 34,\n                    \"isBestMatch\": true,\n                    \"isBuyer\": false,\n                    \"isMaker\": false,\n                    \"orderId\": 39324,\n                    \"price\": \"0.02000000\",\n                    \"qty\": \"3.00000000\",\n                    \"symbol\": \"BNBBTC\",\n                    \"time\": 1561973357171\n                }, {\n                    \"commission\": \"0.00002950\",\n                    \"commissionAsset\": \"BTC\",\n                    \"id\": 32,\n                    \"isBestMatch\": true,\n                    \"isBuyer\": false,\n                    \"isMaker\": true,\n                    \"orderId\": 39319,\n                    \"price\": \"0.00590000\",\n                    \"qty\": \"5.00000000\",\n                    \"symbol\": \"BNBBTC\",\n                    \"time\": 1561964645345\n                }\n            ]\n\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"margin/myTrades\", signed=True, data=params\n        )\n\n    def get_max_margin_loan(self, **params):\n        \"\"\"Query max borrow amount for an asset\n\n        https://binance-docs.github.io/apidocs/spot/en/#query-max-borrow-user_data\n\n        :param asset: required\n        :type asset: str\n        :param isolatedSymbol: isolated symbol (if querying isolated margin)\n        :type isolatedSymbol: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n            {\n                \"amount\": \"1.69248805\"\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"margin/maxBorrowable\", signed=True, data=params\n        )\n\n    def get_max_margin_transfer(self, **params):\n        \"\"\"Query max transfer-out amount\n\n        https://developers.binance.com/docs/margin_trading/transfer/Query-Max-Transfer-Out-Amount\n\n        :param asset: required\n        :type asset: str\n        :param isolatedSymbol: isolated symbol (if querying isolated margin)\n        :type isolatedSymbol: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n            {\n                \"amount\": \"3.59498107\"\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"margin/maxTransferable\", signed=True, data=params\n        )\n\n    def get_margin_delist_schedule(self, **params):\n        \"\"\"Get tokens or symbols delist schedule for cross margin and isolated margin\n\n        https://developers.binance.com/docs/margin_trading/market-data/Get-Delist-Schedule\n\n        :param recvWindow: optional - the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n            [\n                {\n                    \"delistTime\": 1686161202000,\n                    \"crossMarginAssets\": [\n                        \"BTC\",\n                        \"USDT\"\n                    ],\n                    \"isolatedMarginSymbols\": [\n                        \"ADAUSDT\",\n                        \"BNBUSDT\"\n                    ]\n                },\n                {\n                    \"delistTime\": 1686222232000,\n                    \"crossMarginAssets\": [\n                        \"ADA\"\n                    ],\n                    \"isolatedMarginSymbols\": []\n                }\n            ]\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"/margin/delist-schedule\", signed=True, data=params\n        )\n\n    # Margin OCO\n\n    def create_margin_oco_order(self, **params):\n        \"\"\"Post a new OCO trade for margin account.\n\n        https://developers.binance.com/docs/margin_trading/trade/Margin-Account-New-OCO\n\n\n        :param symbol: required\n        :type symbol: str\n        :param isIsolated: for isolated margin or not, \"TRUE\", \"FALSE\"，default \"FALSE\"\n        :type symbol: str\n        :param listClientOrderId: A unique id for the list order. Automatically generated if not sent.\n        :type listClientOrderId: str\n        :param side: required\n        :type side: str\n        :param quantity: required\n        :type quantity: decimal\n        :param limitClientOrderId: A unique id for the limit order. Automatically generated if not sent.\n        :type limitClientOrderId: str\n        :param price: required\n        :type price: str\n        :param limitIcebergQty: Used to make the LIMIT_MAKER leg an iceberg order.\n        :type limitIcebergQty: decimal\n        :param stopClientOrderId: A unique Id for the stop loss/stop loss limit leg. Automatically generated if not sent.\n        :type stopClientOrderId: str\n        :param stopPrice: required\n        :type stopPrice: str\n        :param stopLimitPrice: If provided, stopLimitTimeInForce is required.\n        :type stopLimitPrice: str\n        :param stopIcebergQty: Used with STOP_LOSS_LIMIT leg to make an iceberg order.\n        :type stopIcebergQty: decimal\n        :param stopLimitTimeInForce: Valid values are GTC/FOK/IOC.\n        :type stopLimitTimeInForce: str\n        :param newOrderRespType: Set the response JSON. ACK, RESULT, or FULL; default: RESULT.\n        :type newOrderRespType: str\n        :param sideEffectType: NO_SIDE_EFFECT, MARGIN_BUY, AUTO_REPAY; default NO_SIDE_EFFECT.\n        :type sideEffectType: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"orderListId\": 0,\n                \"contingencyType\": \"OCO\",\n                \"listStatusType\": \"EXEC_STARTED\",\n                \"listOrderStatus\": \"EXECUTING\",\n                \"listClientOrderId\": \"JYVpp3F0f5CAG15DhtrqLp\",\n                \"transactionTime\": 1563417480525,\n                \"symbol\": \"LTCBTC\",\n                \"marginBuyBorrowAmount\": \"5\",       // will not return if no margin trade happens\n                \"marginBuyBorrowAsset\": \"BTC\",    // will not return if no margin trade happens\n                \"isIsolated\": false,       // if isolated margin\n                \"orders\": [\n                    {\n                        \"symbol\": \"LTCBTC\",\n                        \"orderId\": 2,\n                        \"clientOrderId\": \"Kk7sqHb9J6mJWTMDVW7Vos\"\n                    },\n                    {\n                        \"symbol\": \"LTCBTC\",\n                        \"orderId\": 3,\n                        \"clientOrderId\": \"xTXKaGYd4bluPVp78IVRvl\"\n                    }\n                ],\n                \"orderReports\": [\n                    {\n                        \"symbol\": \"LTCBTC\",\n                        \"orderId\": 2,\n                        \"orderListId\": 0,\n                        \"clientOrderId\": \"Kk7sqHb9J6mJWTMDVW7Vos\",\n                        \"transactTime\": 1563417480525,\n                        \"price\": \"0.000000\",\n                        \"origQty\": \"0.624363\",\n                        \"executedQty\": \"0.000000\",\n                        \"cummulativeQuoteQty\": \"0.000000\",\n                        \"status\": \"NEW\",\n                        \"timeInForce\": \"GTC\",\n                        \"type\": \"STOP_LOSS\",\n                        \"side\": \"BUY\",\n                        \"stopPrice\": \"0.960664\"\n                    },\n                    {\n                        \"symbol\": \"LTCBTC\",\n                        \"orderId\": 3,\n                        \"orderListId\": 0,\n                        \"clientOrderId\": \"xTXKaGYd4bluPVp78IVRvl\",\n                        \"transactTime\": 1563417480525,\n                        \"price\": \"0.036435\",\n                        \"origQty\": \"0.624363\",\n                        \"executedQty\": \"0.000000\",\n                        \"cummulativeQuoteQty\": \"0.000000\",\n                        \"status\": \"NEW\",\n                        \"timeInForce\": \"GTC\",\n                        \"type\": \"LIMIT_MAKER\",\n                        \"side\": \"BUY\"\n                    }\n                ]\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException, BinanceOrderException, BinanceOrderMinAmountException,\n            BinanceOrderMinPriceException, BinanceOrderMinTotalException, BinanceOrderUnknownSymbolException,\n            BinanceOrderInactiveSymbolException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"post\", \"margin/order/oco\", signed=True, data=params\n        )\n\n    def cancel_margin_oco_order(self, **params):\n        \"\"\"Cancel an entire Order List for a margin account.\n\n        https://developers.binance.com/docs/margin_trading/trade/Margin-Account-Cancel-OCO\n\n        :param symbol: required\n        :type symbol: str\n        :param isIsolated: for isolated margin or not, \"TRUE\", \"FALSE\"，default \"FALSE\"\n        :type symbol: str\n        :param orderListId: Either orderListId or listClientOrderId must be provided\n        :type orderListId: int\n        :param listClientOrderId: Either orderListId or listClientOrderId must be provided\n        :type listClientOrderId: str\n        :param newClientOrderId: Used to uniquely identify this cancel. Automatically generated by default.\n        :type newClientOrderId: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"orderListId\": 0,\n                \"contingencyType\": \"OCO\",\n                \"listStatusType\": \"ALL_DONE\",\n                \"listOrderStatus\": \"ALL_DONE\",\n                \"listClientOrderId\": \"C3wyj4WVEktd7u9aVBRXcN\",\n                \"transactionTime\": 1574040868128,\n                \"symbol\": \"LTCBTC\",\n                \"isIsolated\": false,       // if isolated margin\n                \"orders\": [\n                    {\n                        \"symbol\": \"LTCBTC\",\n                        \"orderId\": 2,\n                        \"clientOrderId\": \"pO9ufTiFGg3nw2fOdgeOXa\"\n                    },\n                    {\n                        \"symbol\": \"LTCBTC\",\n                        \"orderId\": 3,\n                        \"clientOrderId\": \"TXOvglzXuaubXAaENpaRCB\"\n                    }\n                ],\n                \"orderReports\": [\n                    {\n                        \"symbol\": \"LTCBTC\",\n                        \"origClientOrderId\": \"pO9ufTiFGg3nw2fOdgeOXa\",\n                        \"orderId\": 2,\n                        \"orderListId\": 0,\n                        \"clientOrderId\": \"unfWT8ig8i0uj6lPuYLez6\",\n                        \"price\": \"1.00000000\",\n                        \"origQty\": \"10.00000000\",\n                        \"executedQty\": \"0.00000000\",\n                        \"cummulativeQuoteQty\": \"0.00000000\",\n                        \"status\": \"CANCELED\",\n                        \"timeInForce\": \"GTC\",\n                        \"type\": \"STOP_LOSS_LIMIT\",\n                        \"side\": \"SELL\",\n                        \"stopPrice\": \"1.00000000\"\n                    },\n                    {\n                        \"symbol\": \"LTCBTC\",\n                        \"origClientOrderId\": \"TXOvglzXuaubXAaENpaRCB\",\n                        \"orderId\": 3,\n                        \"orderListId\": 0,\n                        \"clientOrderId\": \"unfWT8ig8i0uj6lPuYLez6\",\n                        \"price\": \"3.00000000\",\n                        \"origQty\": \"10.00000000\",\n                        \"executedQty\": \"0.00000000\",\n                        \"cummulativeQuoteQty\": \"0.00000000\",\n                        \"status\": \"CANCELED\",\n                        \"timeInForce\": \"GTC\",\n                        \"type\": \"LIMIT_MAKER\",\n                        \"side\": \"SELL\"\n                    }\n                ]\n            }\n\n        \"\"\"\n        return self._request_margin_api(\n            \"delete\", \"margin/orderList\", signed=True, data=params\n        )\n\n    def get_margin_oco_order(self, **params):\n        \"\"\"Retrieves a specific OCO based on provided optional parameters\n\n        https://developers.binance.com/docs/margin_trading/trade/Query-Margin-Account-OCO\n\n        :param isIsolated: for isolated margin or not, \"TRUE\", \"FALSE\"，default \"FALSE\"\n        :type symbol: str\n        :param symbol: mandatory for isolated margin, not supported for cross margin\n        :type symbol: str\n        :param orderListId: Either orderListId or listClientOrderId must be provided\n        :type orderListId: int\n        :param listClientOrderId: Either orderListId or listClientOrderId must be provided\n        :type listClientOrderId: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n            {\n                \"orderListId\": 27,\n                \"contingencyType\": \"OCO\",\n                \"listStatusType\": \"EXEC_STARTED\",\n                \"listOrderStatus\": \"EXECUTING\",\n                \"listClientOrderId\": \"h2USkA5YQpaXHPIrkd96xE\",\n                \"transactionTime\": 1565245656253,\n                \"symbol\": \"LTCBTC\",\n                \"isIsolated\": false,       // if isolated margin\n                \"orders\": [\n                    {\n                        \"symbol\": \"LTCBTC\",\n                        \"orderId\": 4,\n                        \"clientOrderId\": \"qD1gy3kc3Gx0rihm9Y3xwS\"\n                    },\n                    {\n                        \"symbol\": \"LTCBTC\",\n                        \"orderId\": 5,\n                        \"clientOrderId\": \"ARzZ9I00CPM8i3NhmU9Ega\"\n                    }\n                ]\n            }\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"margin/orderList\", signed=True, data=params\n        )\n\n    def get_open_margin_oco_orders(self, **params):\n        \"\"\"Retrieves open OCO trades\n\n        https://developers.binance.com/docs/margin_trading/trade/Query-Margin-Account-Open-OCO\n\n        :param isIsolated: for isolated margin or not, \"TRUE\", \"FALSE\"，default \"FALSE\"\n        :type symbol: str\n        :param symbol: mandatory for isolated margin, not supported for cross margin\n        :type symbol: str\n        :param fromId: If supplied, neither startTime or endTime can be provided\n        :type fromId: int\n        :param startTime: optional\n        :type startTime: int\n        :param endTime: optional\n        :type endTime: int\n        :param limit: optional Default Value: 500; Max Value: 1000\n        :type limit: int\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n            [\n                {\n                    \"orderListId\": 29,\n                    \"contingencyType\": \"OCO\",\n                    \"listStatusType\": \"EXEC_STARTED\",\n                    \"listOrderStatus\": \"EXECUTING\",\n                    \"listClientOrderId\": \"amEEAXryFzFwYF1FeRpUoZ\",\n                    \"transactionTime\": 1565245913483,\n                    \"symbol\": \"LTCBTC\",\n                    \"isIsolated\": true,       // if isolated margin\n                    \"orders\": [\n                        {\n                            \"symbol\": \"LTCBTC\",\n                            \"orderId\": 4,\n                            \"clientOrderId\": \"oD7aesZqjEGlZrbtRpy5zB\"\n                        },\n                        {\n                            \"symbol\": \"LTCBTC\",\n                            \"orderId\": 5,\n                            \"clientOrderId\": \"Jr1h6xirOxgeJOUuYQS7V3\"\n                        }\n                    ]\n                },\n                {\n                    \"orderListId\": 28,\n                    \"contingencyType\": \"OCO\",\n                    \"listStatusType\": \"EXEC_STARTED\",\n                    \"listOrderStatus\": \"EXECUTING\",\n                    \"listClientOrderId\": \"hG7hFNxJV6cZy3Ze4AUT4d\",\n                    \"transactionTime\": 1565245913407,\n                    \"symbol\": \"LTCBTC\",\n                    \"orders\": [\n                        {\n                            \"symbol\": \"LTCBTC\",\n                            \"orderId\": 2,\n                            \"clientOrderId\": \"j6lFOfbmFMRjTYA7rRJ0LP\"\n                        },\n                        {\n                            \"symbol\": \"LTCBTC\",\n                            \"orderId\": 3,\n                            \"clientOrderId\": \"z0KCjOdditiLS5ekAFtK81\"\n                        }\n                    ]\n                }\n            ]\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"margin/openOrderList\", signed=True, data=params\n        )\n\n    # Cross-margin\n\n    def margin_stream_get_listen_key(self):\n        \"\"\"Start a new cross-margin data stream and return the listen key\n        If a stream already exists it should return the same key.\n        If the stream becomes invalid a new key is returned.\n\n        Can be used to keep the stream alive.\n\n        https://developers.binance.com/docs/margin_trading/trade-data-stream/Start-Margin-User-Data-Stream\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"listenKey\": \"pqia91ma19a5s61cv6a81va65sdf19v8a65a1a5s61cv6a81va65sdf19v8a65a1\"\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        warnings.warn(\n            \"POST /sapi/v1/userDataStream is deprecated and will be removed on 2026-02-20. \"\n            \"Use the WebSocket API subscription method instead (create listenToken via POST /sapi/v1/userListenToken, \"\n            \"then subscribe with userDataStream.subscribe.listenToken). \"\n            \"The margin_socket() method now uses WebSocket API by default.\",\n            DeprecationWarning,\n            stacklevel=2\n        )\n        res = self._request_margin_api(\"post\", \"userDataStream\", signed=False, data={})\n        return res[\"listenKey\"]\n\n    def margin_stream_keepalive(self, listenKey):\n        \"\"\"PING a cross-margin data stream to prevent a time out.\n\n        https://developers.binance.com/docs/margin_trading/trade-data-stream/Keepalive-Margin-User-Data-Stream\n\n        :param listenKey: required\n        :type listenKey: str\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {}\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        warnings.warn(\n            \"PUT /sapi/v1/userDataStream is deprecated and will be removed on 2026-02-20. \"\n            \"Use the WebSocket API subscription method instead (create listenToken via POST /sapi/v1/userListenToken, \"\n            \"then subscribe with userDataStream.subscribe.listenToken). \"\n            \"The margin_socket() method now uses WebSocket API by default.\",\n            DeprecationWarning,\n            stacklevel=2\n        )\n        params = {\"listenKey\": listenKey}\n        return self._request_margin_api(\n            \"put\", \"userDataStream\", signed=False, data=params\n        )\n\n    def margin_stream_close(self, listenKey):\n        \"\"\"Close out a cross-margin data stream.\n\n        https://developers.binance.com/docs/margin_trading/trade-data-stream/Close-Margin-User-Data-Stream\n\n        :param listenKey: required\n        :type listenKey: str\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {}\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        warnings.warn(\n            \"DELETE /sapi/v1/userDataStream is deprecated and will be removed on 2026-02-20. \"\n            \"Use the WebSocket API subscription method instead (create listenToken via POST /sapi/v1/userListenToken, \"\n            \"then subscribe with userDataStream.subscribe.listenToken). \"\n            \"The margin_socket() method now uses WebSocket API by default.\",\n            DeprecationWarning,\n            stacklevel=2\n        )\n        params = {\"listenKey\": listenKey}\n        return self._request_margin_api(\n            \"delete\", \"userDataStream\", signed=False, data=params\n        )\n\n    def margin_create_listen_token(self, symbol: Optional[str] = None, is_isolated: bool = False, validity: Optional[int] = None):\n        \"\"\"Create a listenToken for margin account user data stream\n\n        https://developers.binance.com/docs/margin_trading/trade-data-stream/Create-Margin-Account-listenToken\n\n        :param symbol: Trading pair symbol (required when is_isolated=True)\n        :type symbol: str\n        :param is_isolated: Whether it is isolated margin (default: False for cross-margin)\n        :type is_isolated: bool\n        :param validity: Validity in milliseconds (default: 24 hours, max: 24 hours)\n        :type validity: int\n        :returns: API response with token and expirationTime\n\n        .. code-block:: python\n\n            {\n                \"token\": \"6xXxePXwZRjVSHKhzUCCGnmN3fkvMTXru+pYJS8RwijXk9Vcyr3rkwfVOTcP2OkONqciYA\",\n                \"expirationTime\": 1758792204196\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n        \"\"\"\n        params = {}\n        if is_isolated:\n            if not symbol:\n                raise ValueError(\"symbol is required when is_isolated=True\")\n            params[\"symbol\"] = symbol\n            params[\"isIsolated\"] = \"true\"\n        if validity is not None:\n            params[\"validity\"] = validity\n\n        return self._request_margin_api(\n            \"post\", \"userListenToken\", signed=True, data=params\n        )\n\n    # Isolated margin\n\n    def isolated_margin_stream_get_listen_key(self, symbol):\n        \"\"\"Start a new isolated margin data stream and return the listen key\n        If a stream already exists it should return the same key.\n        If the stream becomes invalid a new key is returned.\n\n        Can be used to keep the stream alive.\n\n        https://developers.binance.com/docs/margin_trading/trade-data-stream/Start-Isolated-Margin-User-Data-Stream\n\n        :param symbol: required - symbol for the isolated margin account\n        :type symbol: str\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"listenKey\":  \"T3ee22BIYuWqmvne0HNq2A2WsFlEtLhvWCtItw6ffhhdmjifQ2tRbuKkTHhr\"\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        warnings.warn(\n            \"POST /sapi/v1/userDataStream/isolated is deprecated and will be removed on 2026-02-20. \"\n            \"Use the WebSocket API subscription method instead (create listenToken via POST /sapi/v1/userListenToken \"\n            \"with isIsolated=true, then subscribe with userDataStream.subscribe.listenToken). \"\n            \"The isolated_margin_socket() method now uses WebSocket API by default.\",\n            DeprecationWarning,\n            stacklevel=2\n        )\n        params = {\"symbol\": symbol}\n        res = self._request_margin_api(\n            \"post\", \"userDataStream/isolated\", signed=False, data=params\n        )\n        return res[\"listenKey\"]\n\n    def isolated_margin_stream_keepalive(self, symbol, listenKey):\n        \"\"\"PING an isolated margin data stream to prevent a time out.\n\n        https://developers.binance.com/docs/margin_trading/trade-data-stream/Keepalive-Isolated-Margin-User-Data-Stream\n\n        :param symbol: required - symbol for the isolated margin account\n        :type symbol: str\n        :param listenKey: required\n        :type listenKey: str\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {}\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        warnings.warn(\n            \"PUT /sapi/v1/userDataStream/isolated is deprecated and will be removed on 2026-02-20. \"\n            \"Use the WebSocket API subscription method instead (create listenToken via POST /sapi/v1/userListenToken \"\n            \"with isIsolated=true, then subscribe with userDataStream.subscribe.listenToken). \"\n            \"The isolated_margin_socket() method now uses WebSocket API by default.\",\n            DeprecationWarning,\n            stacklevel=2\n        )\n        params = {\"symbol\": symbol, \"listenKey\": listenKey}\n        return self._request_margin_api(\n            \"put\", \"userDataStream/isolated\", signed=False, data=params\n        )\n\n    def isolated_margin_stream_close(self, symbol, listenKey):\n        \"\"\"Close out an isolated margin data stream.\n\n        https://developers.binance.com/docs/margin_trading/trade-data-stream/Close-Isolated-Margin-User-Data-Stream\n\n        :param symbol: required - symbol for the isolated margin account\n        :type symbol: str\n        :param listenKey: required\n        :type listenKey: str\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {}\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        warnings.warn(\n            \"DELETE /sapi/v1/userDataStream/isolated is deprecated and will be removed on 2026-02-20. \"\n            \"Use the WebSocket API subscription method instead (create listenToken via POST /sapi/v1/userListenToken \"\n            \"with isIsolated=true, then subscribe with userDataStream.subscribe.listenToken). \"\n            \"The isolated_margin_socket() method now uses WebSocket API by default.\",\n            DeprecationWarning,\n            stacklevel=2\n        )\n        params = {\"symbol\": symbol, \"listenKey\": listenKey}\n        return self._request_margin_api(\n            \"delete\", \"userDataStream/isolated\", signed=False, data=params\n        )\n\n    # Simple Earn Endpoints\n\n    def get_simple_earn_flexible_product_list(self, **params):\n        \"\"\"Get available Simple Earn flexible product list\n\n        https://binance-docs.github.io/apidocs/spot/en/#get-simple-earn-flexible-product-list-user_data\n\n        :param asset: optional\n        :type asset: str\n        :param current: optional - Currently querying page. Start from 1. Default:1\n        :type current: int\n        :param size: optional - Default:10, Max:100\n        :type size: int\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n               \"rows\":[\n                   {\n                       \"asset\": \"BTC\",\n                       \"latestAnnualPercentageRate\": \"0.05000000\",\n                       \"tierAnnualPercentageRate\": {\n                       \"0-5BTC\": 0.05,\n                       \"5-10BTC\": 0.03\n                   },\n                       \"airDropPercentageRate\": \"0.05000000\",\n                       \"canPurchase\": true,\n                       \"canRedeem\": true,\n                       \"isSoldOut\": true,\n                       \"hot\": true,\n                       \"minPurchaseAmount\": \"0.01000000\",\n                       \"productId\": \"BTC001\",\n                       \"subscriptionStartTime\": \"1646182276000\",\n                       \"status\": \"PURCHASING\"\n                   }\n               ],\n               \"total\": 1\n           }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"simple-earn/flexible/list\", signed=True, data=params\n        )\n\n    def get_simple_earn_locked_product_list(self, **params):\n        \"\"\"Get available Simple Earn flexible product list\n\n        https://binance-docs.github.io/apidocs/spot/en/#get-simple-earn-locked-product-list-user_data\n\n        :param asset: optional\n        :type asset: str\n        :param current: optional - Currently querying page. Start from 1. Default:1\n        :type current: int\n        :param size: optional - Default:10, Max:100\n        :type size: int\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n               \"rows\": [\n                   {\n                       \"projectId\": \"Axs*90\",\n                       \"detail\": {\n                           \"asset\": \"AXS\",\n                           \"rewardAsset\": \"AXS\",\n                           \"duration\": 90,\n                           \"renewable\": true,\n                           \"isSoldOut\": true,\n                           \"apr\": \"1.2069\",\n                           \"status\": \"CREATED\",\n                           \"subscriptionStartTime\": \"1646182276000\",\n                           \"extraRewardAsset\": \"BNB\",\n                           \"extraRewardAPR\": \"0.23\"\n                       },\n                       \"quota\": {\n                           \"totalPersonalQuota\": \"2\",\n                           \"minimum\": \"0.001\"\n                       }\n                   }\n               ],\n               \"total\": 1\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"simple-earn/locked/list\", signed=True, data=params\n        )\n\n    def subscribe_simple_earn_flexible_product(self, **params):\n        \"\"\"Subscribe to a simple earn flexible product\n\n        https://binance-docs.github.io/apidocs/spot/en/#subscribe-locked-product-trade\n\n        :param productId: required\n        :type productId: str\n        :param amount: required\n        :type amount: str\n        :param autoSubscribe: optional - Default True\n        :type autoSubscribe: bool\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n               \"purchaseId\": 40607,\n               \"success\": true\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"post\", \"simple-earn/flexible/subscribe\", signed=True, data=params\n        )\n\n    def subscribe_simple_earn_locked_product(self, **params):\n        \"\"\"Subscribe to a simple earn locked product\n\n        https://binance-docs.github.io/apidocs/spot/en/#subscribe-locked-product-trade\n\n        :param productId: required\n        :type productId: str\n        :param amount: required\n        :type amount: str\n        :param autoSubscribe: optional - Default True\n        :type autoSubscribe: bool\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n               \"purchaseId\": 40607,\n               \"positionId\": \"12345\",\n               \"success\": true\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"post\", \"simple-earn/locked/subscribe\", signed=True, data=params\n        )\n\n    def redeem_simple_earn_flexible_product(self, **params):\n        \"\"\"Redeem a simple earn flexible product\n\n        https://binance-docs.github.io/apidocs/spot/en/#redeem-flexible-product-trade\n\n        :param productId: required\n        :type productId: str\n        :param amount: optional\n        :type amount: str\n        :param redeemAll: optional - Default False\n        :type redeemAll: bool\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n           {\n               \"redeemId\": 40607,\n               \"success\": true\n           }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"post\", \"simple-earn/flexible/redeem\", signed=True, data=params\n        )\n\n    def redeem_simple_earn_locked_product(self, **params):\n        \"\"\"Redeem a simple earn locked product\n\n        https://binance-docs.github.io/apidocs/spot/en/#redeem-locked-product-trade\n\n        :param productId: required\n        :type productId: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n           {\n               \"redeemId\": 40607,\n               \"success\": true\n           }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"post\", \"simple-earn/locked/redeem\", signed=True, data=params\n        )\n\n    def get_simple_earn_flexible_product_position(self, **params):\n        \"\"\"\n\n        https://binance-docs.github.io/apidocs/spot/en/#get-flexible-product-position-user_data\n\n        :param asset: optional\n        :type asset: str\n        :param current: optional - Currently querying page. Start from 1. Default:1\n        :type current: int\n        :param size: optional - Default:10, Max:100\n        :type size: int\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n           {\n               \"rows\":[\n                   {\n                       \"totalAmount\": \"75.46000000\",\n                       \"tierAnnualPercentageRate\": {\n                       \"0-5BTC\": 0.05,\n                       \"5-10BTC\": 0.03\n                   },\n                       \"latestAnnualPercentageRate\": \"0.02599895\",\n                       \"yesterdayAirdropPercentageRate\": \"0.02599895\",\n                       \"asset\": \"USDT\",\n                       \"airDropAsset\": \"BETH\",\n                       \"canRedeem\": true,\n                       \"collateralAmount\": \"232.23123213\",\n                       \"productId\": \"USDT001\",\n                       \"yesterdayRealTimeRewards\": \"0.10293829\",\n                       \"cumulativeBonusRewards\": \"0.22759183\",\n                       \"cumulativeRealTimeRewards\": \"0.22759183\",\n                       \"cumulativeTotalRewards\": \"0.45459183\",\n                       \"autoSubscribe\": true\n                   }\n               ],\n               \"total\": 1\n           }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"simple-earn/flexible/position\", signed=True, data=params\n        )\n\n    def get_simple_earn_locked_product_position(self, **params):\n        \"\"\"\n\n        https://binance-docs.github.io/apidocs/spot/en/#get-locked-product-position-user_data\n\n        :param asset: optional\n        :type asset: str\n        :param current: optional - Currently querying page. Start from 1. Default:1\n        :type current: int\n        :param size: optional - Default:10, Max:100\n        :type size: int\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n           {\n               \"rows\":[\n                   {\n                       \"positionId\": \"123123\",\n                       \"projectId\": \"Axs*90\",\n                       \"asset\": \"AXS\",\n                       \"amount\": \"122.09202928\",\n                       \"purchaseTime\": \"1646182276000\",\n                       \"duration\": \"60\",\n                       \"accrualDays\": \"4\",\n                       \"rewardAsset\": \"AXS\",\n                       \"APY\": \"0.23\",\n                       \"isRenewable\": true,\n                       \"isAutoRenew\": true,\n                       \"redeemDate\": \"1732182276000\"\n                   }\n               ],\n               \"total\": 1\n           }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"simple-earn/locked/position\", signed=True, data=params\n        )\n\n    def get_simple_earn_account(self, **params):\n        \"\"\"\n\n        https://binance-docs.github.io/apidocs/spot/en/#simple-account-user_data\n\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n           {\n               \"totalAmountInBTC\": \"0.01067982\",\n               \"totalAmountInUSDT\": \"77.13289230\",\n               \"totalFlexibleAmountInBTC\": \"0.00000000\",\n               \"totalFlexibleAmountInUSDT\": \"0.00000000\",\n               \"totalLockedInBTC\": \"0.01067982\",\n               \"totalLockedInUSDT\": \"77.13289230\"\n           }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"simple-earn/account\", signed=True, data=params\n        )\n\n    # Lending Endpoints\n\n    def get_fixed_activity_project_list(self, **params):\n        \"\"\"Get Fixed and Activity Project List\n\n        https://binance-docs.github.io/apidocs/spot/en/#get-fixed-and-activity-project-list-user_data\n\n        :param asset: optional\n        :type asset: str\n        :param type: required - \"ACTIVITY\", \"CUSTOMIZED_FIXED\"\n        :type type: str\n        :param status: optional - \"ALL\", \"SUBSCRIBABLE\", \"UNSUBSCRIBABLE\"; default \"ALL\"\n        :type status: str\n        :param sortBy: optional - \"START_TIME\", \"LOT_SIZE\", \"INTEREST_RATE\", \"DURATION\"; default \"START_TIME\"\n        :type sortBy: str\n        :param current: optional - Currently querying page. Start from 1. Default:1\n        :type current: int\n        :param size: optional - Default:10, Max:100\n        :type size: int\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            [\n                {\n                    \"asset\": \"USDT\",\n                    \"displayPriority\": 1,\n                    \"duration\": 90,\n                    \"interestPerLot\": \"1.35810000\",\n                    \"interestRate\": \"0.05510000\",\n                    \"lotSize\": \"100.00000000\",\n                    \"lotsLowLimit\": 1,\n                    \"lotsPurchased\": 74155,\n                    \"lotsUpLimit\": 80000,\n                    \"maxLotsPerUser\": 2000,\n                    \"needKyc\": False,\n                    \"projectId\": \"CUSDT90DAYSS001\",\n                    \"projectName\": \"USDT\",\n                    \"status\": \"PURCHASING\",\n                    \"type\": \"CUSTOMIZED_FIXED\",\n                    \"withAreaLimitation\": False\n                }\n            ]\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"lending/project/list\", signed=True, data=params\n        )\n\n    def change_fixed_activity_to_daily_position(self, **params):\n        \"\"\"Change Fixed/Activity Position to Daily Position\n\n        https://binance-docs.github.io/apidocs/spot/en/#change-fixed-activity-position-to-daily-position-user_data\n\n        \"\"\"\n        return self._request_margin_api(\n            \"post\", \"lending/positionChanged\", signed=True, data=params\n        )\n\n    # Staking Endpoints\n\n    def get_staking_product_list(self, **params):\n        \"\"\"Get Staking Product List\n\n        https://binance-docs.github.io/apidocs/spot/en/#get-staking-product-list-user_data\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"staking/productList\", signed=True, data=params\n        )\n\n    def purchase_staking_product(self, **params):\n        \"\"\"Purchase Staking Product\n\n        https://binance-docs.github.io/apidocs/spot/en/#purchase-staking-product-user_data\n\n        \"\"\"\n        return self._request_margin_api(\n            \"post\", \"staking/purchase\", signed=True, data=params\n        )\n\n    def redeem_staking_product(self, **params):\n        \"\"\"Redeem Staking Product\n\n        https://binance-docs.github.io/apidocs/spot/en/#redeem-staking-product-user_data\n\n        \"\"\"\n        return self._request_margin_api(\n            \"post\", \"staking/redeem\", signed=True, data=params\n        )\n\n    def get_staking_position(self, **params):\n        \"\"\"Get Staking Product Position\n\n        https://binance-docs.github.io/apidocs/spot/en/#get-staking-product-position-user_data\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"staking/position\", signed=True, data=params\n        )\n\n    def get_staking_purchase_history(self, **params):\n        \"\"\"Get Staking Purchase History\n\n        https://binance-docs.github.io/apidocs/spot/en/#get-staking-history-user_data\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"staking/purchaseRecord\", signed=True, data=params\n        )\n\n    def set_auto_staking(self, **params):\n        \"\"\"Set Auto Staking on Locked Staking or Locked DeFi Staking\n\n        https://binance-docs.github.io/apidocs/spot/en/#set-auto-staking-user_data\n\n        \"\"\"\n        return self._request_margin_api(\n            \"post\", \"staking/setAutoStaking\", signed=True, data=params\n        )\n\n    def get_personal_left_quota(self, **params):\n        \"\"\"Get Personal Left Quota of Staking Product\n\n        https://binance-docs.github.io/apidocs/spot/en/#get-personal-left-quota-of-staking-product-user_data\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"staking/personalLeftQuota\", signed=True, data=params\n        )\n\n    # US Staking Endpoints\n\n    def get_staking_asset_us(self, **params):\n        \"\"\"Get staking information for a supported asset (or assets)\n\n        https://docs.binance.us/#get-staking-asset-information\n\n        :raises BinanceRegionException: If client is not configured for binance.us\n        \"\"\"\n        self._require_tld(\"us\", \"get_staking_asset_us\")\n        return self._request_margin_api(\"get\", \"staking/asset\", True, data=params)\n\n    def stake_asset_us(self, **params):\n        \"\"\"Stake a supported asset.\n\n        https://docs.binance.us/#stake-asset\n\n        :raises BinanceRegionException: If client is not configured for binance.us\n        \"\"\"\n        self._require_tld(\"us\", \"stake_asset_us\")\n        return self._request_margin_api(\"post\", \"staking/stake\", True, data=params)\n\n    def unstake_asset_us(self, **params):\n        \"\"\"Unstake a staked asset\n\n        https://docs.binance.us/#unstake-asset\n\n        :raises BinanceRegionException: If client is not configured for binance.us\n        \"\"\"\n        self._require_tld(\"us\", \"unstake_asset_us\")\n        return self._request_margin_api(\"post\", \"staking/unstake\", True, data=params)\n\n    def get_staking_balance_us(self, **params):\n        \"\"\"Get staking balance\n\n        https://docs.binance.us/#get-staking-balance\n\n        :raises BinanceRegionException: If client is not configured for binance.us\n        \"\"\"\n        self._require_tld(\"us\", \"get_staking_balance_us\")\n        return self._request_margin_api(\n            \"get\", \"staking/stakingBalance\", True, data=params\n        )\n\n    def get_staking_history_us(self, **params):\n        \"\"\"Get staking history\n\n        https://docs.binance.us/#get-staking-history\n\n        :raises BinanceRegionException: If client is not configured for binance.us\n        \"\"\"\n        self._require_tld(\"us\", \"get_staking_history_us\")\n        return self._request_margin_api(\"get\", \"staking/history\", True, data=params)\n\n    def get_staking_rewards_history_us(self, **params):\n        \"\"\"Get staking rewards history for an asset(or assets) within a given time range.\n\n        https://docs.binance.us/#get-staking-rewards-history\n\n        :raises BinanceRegionException: If client is not configured for binance.us\n        \"\"\"\n        self._require_tld(\"us\", \"get_staking_rewards_history_us\")\n        return self._request_margin_api(\n            \"get\", \"staking/stakingRewardsHistory\", True, data=params\n        )\n\n    # Sub Accounts\n\n    def get_sub_account_list(self, **params):\n        \"\"\"Query Sub-account List.\n\n        https://developers.binance.com/docs/sub_account/account-management/Query-Sub-account-List\n\n        :param email: optional - Sub-account email\n        :type email: str\n        :param isFreeze: optional\n        :type isFreeze: str\n        :param page: optional - Default value: 1\n        :type page: int\n        :param limit: optional - Default value: 1, Max value: 200\n        :type limit: int\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"subAccounts\":[\n                    {\n                        \"email\":\"testsub@gmail.com\",\n                        \"isFreeze\":false,\n                        \"createTime\":1544433328000\n                    },\n                    {\n                        \"email\":\"virtual@oxebmvfonoemail.com\",\n                        \"isFreeze\":false,\n                        \"createTime\":1544433328000\n                    }\n                ]\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\"get\", \"sub-account/list\", True, data=params)\n\n    def get_sub_account_transfer_history(self, **params):\n        \"\"\"Query Sub-account Transfer History.\n\n        https://developers.binance.com/docs/sub_account/asset-management/Query-Sub-account-Spot-Asset-Transfer-History\n\n        :param fromEmail: optional\n        :type fromEmail: str\n        :param toEmail: optional\n        :type toEmail: str\n        :param startTime: optional\n        :type startTime: int\n        :param endTime: optional\n        :type endTime: int\n        :param page: optional - Default value: 1\n        :type page: int\n        :param limit: optional - Default value: 500\n        :type limit: int\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            [\n                {\n                    \"from\":\"aaa@test.com\",\n                    \"to\":\"bbb@test.com\",\n                    \"asset\":\"BTC\",\n                    \"qty\":\"10\",\n                    \"status\": \"SUCCESS\",\n                    \"tranId\": 6489943656,\n                    \"time\":1544433328000\n                },\n                {\n                    \"from\":\"bbb@test.com\",\n                    \"to\":\"ccc@test.com\",\n                    \"asset\":\"ETH\",\n                    \"qty\":\"2\",\n                    \"status\": \"SUCCESS\",\n                    \"tranId\": 6489938713,\n                    \"time\":1544433328000\n                }\n            ]\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"sub-account/sub/transfer/history\", True, data=params\n        )\n\n    def get_sub_account_futures_transfer_history(self, **params):\n        \"\"\"Query Sub-account Futures Transfer History.\n\n        https://developers.binance.com/docs/sub_account/asset-management/Query-Sub-account-Futures-Asset-Transfer-History\n\n        :param email: required\n        :type email: str\n        :param futuresType: required\n        :type futuresType: int\n        :param startTime: optional\n        :type startTime: int\n        :param endTime: optional\n        :type endTime: int\n        :param page: optional\n        :type page: int\n        :param limit: optional\n        :type limit: int\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"success\":true,\n                \"futuresType\": 2,\n                \"transfers\":[\n                    {\n                        \"from\":\"aaa@test.com\",\n                        \"to\":\"bbb@test.com\",\n                        \"asset\":\"BTC\",\n                        \"qty\":\"1\",\n                        \"time\":1544433328000\n                    },\n                    {\n                        \"from\":\"bbb@test.com\",\n                        \"to\":\"ccc@test.com\",\n                        \"asset\":\"ETH\",\n                        \"qty\":\"2\",\n                        \"time\":1544433328000\n                    }\n                ]\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"sub-account/futures/internalTransfer\", True, data=params\n        )\n\n    def create_sub_account_futures_transfer(self, **params):\n        \"\"\"Execute sub-account Futures transfer\n\n        https://developers.binance.com/docs/sub_account/asset-management/Sub-account-Futures-Asset-Transfer\n\n        :param fromEmail: required - Sender email\n        :type fromEmail: str\n        :param toEmail: required - Recipient email\n        :type toEmail: str\n        :param futuresType: required\n        :type futuresType: int\n        :param asset: required\n        :type asset: str\n        :param amount: required\n        :type amount: decimal\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n           {\n                \"success\":true,\n                \"txnId\":\"2934662589\"\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"post\", \"sub-account/futures/internalTransfer\", True, data=params\n        )\n\n    def get_sub_account_assets(self, **params):\n        \"\"\"Fetch sub-account assets\n\n        https://developers.binance.com/docs/sub_account/asset-management/Query-Sub-account-Assets-V4\n\n        :param email: required\n        :type email: str\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"balances\":[\n                    {\n                        \"asset\":\"ADA\",\n                        \"free\":10000,\n                        \"locked\":0\n                    },\n                    {\n                        \"asset\":\"BNB\",\n                        \"free\":10003,\n                        \"locked\":0\n                    },\n                    {\n                        \"asset\":\"BTC\",\n                        \"free\":11467.6399,\n                        \"locked\":0\n                    },\n                    {\n                        \"asset\":\"ETH\",\n                        \"free\":10004.995,\n                        \"locked\":0\n                    },\n                    {\n                        \"asset\":\"USDT\",\n                        \"free\":11652.14213,\n                        \"locked\":0\n                    }\n                ]\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"sub-account/assets\", True, data=params, version=4\n        )\n\n    def query_subaccount_spot_summary(self, **params):\n        \"\"\"Query Sub-account Spot Assets Summary (For Master Account)\n\n        https://developers.binance.com/docs/sub_account/asset-management/Query-Sub-account-Spot-Assets-Summary\n\n        :param email: optional - Sub account email\n        :type email: str\n        :param page: optional - default 1\n        :type page: int\n        :param size: optional - default 10, max 20\n        :type size: int\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n           {\n                \"totalCount\":2,\n                \"masterAccountTotalAsset\": \"0.23231201\",\n                \"spotSubUserAssetBtcVoList\":[\n                    {\n                        \"email\":\"sub123@test.com\",\n                        \"totalAsset\":\"9999.00000000\"\n                    },\n                    {\n                        \"email\":\"test456@test.com\",\n                        \"totalAsset\":\"0.00000000\"\n                    }\n                ]\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"sub-account/spotSummary\", True, data=params\n        )\n\n    def get_subaccount_deposit_address(self, **params):\n        \"\"\"Get Sub-account Deposit Address (For Master Account)\n\n        https://developers.binance.com/docs/sub_account/asset-management/Get-Sub-account-Deposit-Address\n\n        :param email: required - Sub account email\n        :type email: str\n        :param coin: required\n        :type coin: str\n        :param network: optional\n        :type network: str\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n           {\n                \"address\":\"TDunhSa7jkTNuKrusUTU1MUHtqXoBPKETV\",\n                \"coin\":\"USDT\",\n                \"tag\":\"\",\n                \"url\":\"https://tronscan.org/#/address/TDunhSa7jkTNuKrusUTU1MUHtqXoBPKETV\"\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"capital/deposit/subAddress\", True, data=params\n        )\n\n    def get_subaccount_deposit_history(self, **params):\n        \"\"\"Get Sub-account Deposit History (For Master Account)\n\n        https://developers.binance.com/docs/sub_account/asset-management/Get-Sub-account-Deposit-History\n\n        :param email: required - Sub account email\n        :type email: str\n        :param coin: optional\n        :type coin: str\n        :param status: optional - (0:pending,6: credited but cannot withdraw, 1:success)\n        :type status: int\n        :param startTime: optional\n        :type startTime: int\n        :param endTime: optional\n        :type endTime: int\n        :param limit: optional\n        :type limit: int\n        :param offset: optional - default:0\n        :type offset: int\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n           [\n                {\n                    \"amount\":\"0.00999800\",\n                    \"coin\":\"PAXG\",\n                    \"network\":\"ETH\",\n                    \"status\":1,\n                    \"address\":\"0x788cabe9236ce061e5a892e1a59395a81fc8d62c\",\n                    \"addressTag\":\"\",\n                    \"txId\":\"0xaad4654a3234aa6118af9b4b335f5ae81c360b2394721c019b5d1e75328b09f3\",\n                    \"insertTime\":1599621997000,\n                    \"transferType\":0,\n                    \"confirmTimes\":\"12/12\"\n                },\n                {\n                    \"amount\":\"0.50000000\",\n                    \"coin\":\"IOTA\",\n                    \"network\":\"IOTA\",\n                    \"status\":1,\n                    \"address\":\"SIZ9VLMHWATXKV99LH99CIGFJFUMLEHGWVZVNNZXRJJVWBPHYWPPBOSDORZ9EQSHCZAMPVAPGFYQAUUV9DROOXJLNW\",\n                    \"addressTag\":\"\",\n                    \"txId\":\"ESBFVQUTPIWQNJSPXFNHNYHSQNTGKRVKPRABQWTAXCDWOAKDKYWPTVG9BGXNVNKTLEJGESAVXIKIZ9999\",\n                    \"insertTime\":1599620082000,\n                    \"transferType\":0,\n                    \"confirmTimes\":\"1/1\"\n                }\n           ]\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"capital/deposit/subHisrec\", True, data=params\n        )\n\n    def get_subaccount_futures_margin_status(self, **params):\n        \"\"\"Get Sub-account's Status on Margin/Futures (For Master Account)\n\n        https://developers.binance.com/docs/sub_account/account-management/Get-Sub-accounts-Status-on-Margin-Or-Futures\n\n        :param email: optional - Sub account email\n        :type email: str\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n           [\n                {\n                    \"email\":\"123@test.com\",      // user email\n                    \"isSubUserEnabled\": true,    // true or false\n                    \"isUserActive\": true,        // true or false\n                    \"insertTime\": 1570791523523  // sub account create time\n                    \"isMarginEnabled\": true,     // true or false for margin\n                    \"isFutureEnabled\": true      // true or false for futures.\n                    \"mobile\": 1570791523523      // user mobile number\n                }\n            ]\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\"get\", \"sub-account/status\", True, data=params)\n\n    def enable_subaccount_margin(self, **params):\n        \"\"\"Enable Margin for Sub-account (For Master Account)\n\n        https://binance-docs.github.io/apidocs/spot/en/#enable-margin-for-sub-account-for-master-account\n\n        :param email: required - Sub account email\n        :type email: str\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n           {\n\n                \"email\":\"123@test.com\",\n\n                \"isMarginEnabled\": true\n\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"post\", \"sub-account/margin/enable\", True, data=params\n        )\n\n    def get_subaccount_margin_details(self, **params):\n        \"\"\"Get Detail on Sub-account's Margin Account (For Master Account)\n\n        https://developers.binance.com/docs/sub_account/asset-management/Get-Detail-on-Sub-accounts-Margin-Account\n\n        :param email: required - Sub account email\n        :type email: str\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                  \"email\":\"123@test.com\",\n                  \"marginLevel\": \"11.64405625\",\n                  \"totalAssetOfBtc\": \"6.82728457\",\n                  \"totalLiabilityOfBtc\": \"0.58633215\",\n                  \"totalNetAssetOfBtc\": \"6.24095242\",\n                  \"marginTradeCoeffVo\":\n                        {\n                            \"forceLiquidationBar\": \"1.10000000\",  // Liquidation margin ratio\n                            \"marginCallBar\": \"1.50000000\",        // Margin call margin ratio\n                            \"normalBar\": \"2.00000000\"             // Initial margin ratio\n                        },\n                  \"marginUserAssetVoList\": [\n                      {\n                          \"asset\": \"BTC\",\n                          \"borrowed\": \"0.00000000\",\n                          \"free\": \"0.00499500\",\n                          \"interest\": \"0.00000000\",\n                          \"locked\": \"0.00000000\",\n                          \"netAsset\": \"0.00499500\"\n                      },\n                      {\n                          \"asset\": \"BNB\",\n                          \"borrowed\": \"201.66666672\",\n                          \"free\": \"2346.50000000\",\n                          \"interest\": \"0.00000000\",\n                          \"locked\": \"0.00000000\",\n                          \"netAsset\": \"2144.83333328\"\n                      },\n                      {\n                          \"asset\": \"ETH\",\n                          \"borrowed\": \"0.00000000\",\n                          \"free\": \"0.00000000\",\n                          \"interest\": \"0.00000000\",\n                          \"locked\": \"0.00000000\",\n                          \"netAsset\": \"0.00000000\"\n                      },\n                      {\n                          \"asset\": \"USDT\",\n                          \"borrowed\": \"0.00000000\",\n                          \"free\": \"0.00000000\",\n                          \"interest\": \"0.00000000\",\n                          \"locked\": \"0.00000000\",\n                          \"netAsset\": \"0.00000000\"\n                      }\n                  ]\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"sub-account/margin/account\", True, data=params\n        )\n\n    def get_subaccount_margin_summary(self, **params):\n        \"\"\"Get Summary of Sub-account's Margin Account (For Master Account)\n\n        https://developers.binance.com/docs/sub_account/asset-management/Get-Summary-of-Sub-accounts-Margin-Account\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"totalAssetOfBtc\": \"4.33333333\",\n                \"totalLiabilityOfBtc\": \"2.11111112\",\n                \"totalNetAssetOfBtc\": \"2.22222221\",\n                \"subAccountList\":[\n                    {\n                        \"email\":\"123@test.com\",\n                        \"totalAssetOfBtc\": \"2.11111111\",\n                        \"totalLiabilityOfBtc\": \"1.11111111\",\n                        \"totalNetAssetOfBtc\": \"1.00000000\"\n                    },\n                    {\n                        \"email\":\"345@test.com\",\n                        \"totalAssetOfBtc\": \"2.22222222\",\n                        \"totalLiabilityOfBtc\": \"1.00000001\",\n                        \"totalNetAssetOfBtc\": \"1.22222221\"\n                    }\n                ]\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"sub-account/margin/accountSummary\", True, data=params\n        )\n\n    def enable_subaccount_futures(self, **params):\n        \"\"\"Enable Futures for Sub-account (For Master Account)\n\n        https://developers.binance.com/docs/sub_account/account-management/Enable-Futures-for-Sub-account\n\n        :param email: required - Sub account email\n        :type email: str\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n\n                \"email\":\"123@test.com\",\n\n                \"isFuturesEnabled\": true  // true or false\n\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"post\", \"sub-account/futures/enable\", True, data=params\n        )\n\n    def get_subaccount_futures_details(self, **params):\n        \"\"\"Get Detail on Sub-account's Futures Account (For Master Account)\n\n        https://developers.binance.com/docs/sub_account/asset-management/Get-Detail-on-Sub-accounts-Futures-Account\n\n        :param email: required - Sub account email\n        :type email: str\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"email\": \"abc@test.com\",\n                \"asset\": \"USDT\",\n                \"assets\":[\n                    {\n                        \"asset\": \"USDT\",\n                        \"initialMargin\": \"0.00000000\",\n                        \"maintenanceMargin\": \"0.00000000\",\n                        \"marginBalance\": \"0.88308000\",\n                        \"maxWithdrawAmount\": \"0.88308000\",\n                        \"openOrderInitialMargin\": \"0.00000000\",\n                        \"positionInitialMargin\": \"0.00000000\",\n                        \"unrealizedProfit\": \"0.00000000\",\n                        \"walletBalance\": \"0.88308000\"\n                     }\n                ],\n                \"canDeposit\": true,\n                \"canTrade\": true,\n                \"canWithdraw\": true,\n                \"feeTier\": 2,\n                \"maxWithdrawAmount\": \"0.88308000\",\n                \"totalInitialMargin\": \"0.00000000\",\n                \"totalMaintenanceMargin\": \"0.00000000\",\n                \"totalMarginBalance\": \"0.88308000\",\n                \"totalOpenOrderInitialMargin\": \"0.00000000\",\n                \"totalPositionInitialMargin\": \"0.00000000\",\n                \"totalUnrealizedProfit\": \"0.00000000\",\n                \"totalWalletBalance\": \"0.88308000\",\n                \"updateTime\": 1576756674610\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"sub-account/futures/account\", True, data=params, version=2\n        )\n\n    def get_subaccount_futures_summary(self, **params):\n        \"\"\"Get Summary of Sub-account's Futures Account (For Master Account)\n\n        https://developers.binance.com/docs/sub_account/asset-management/Get-Summary-of-Sub-accounts-Futures-Account-V2\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"totalInitialMargin\": \"9.83137400\",\n                \"totalMaintenanceMargin\": \"0.41568700\",\n                \"totalMarginBalance\": \"23.03235621\",\n                \"totalOpenOrderInitialMargin\": \"9.00000000\",\n                \"totalPositionInitialMargin\": \"0.83137400\",\n                \"totalUnrealizedProfit\": \"0.03219710\",\n                \"totalWalletBalance\": \"22.15879444\",\n                \"asset\": \"USDT\",\n                \"subAccountList\":[\n                    {\n                        \"email\": \"123@test.com\",\n                        \"totalInitialMargin\": \"9.00000000\",\n                        \"totalMaintenanceMargin\": \"0.00000000\",\n                        \"totalMarginBalance\": \"22.12659734\",\n                        \"totalOpenOrderInitialMargin\": \"9.00000000\",\n                        \"totalPositionInitialMargin\": \"0.00000000\",\n                        \"totalUnrealizedProfit\": \"0.00000000\",\n                        \"totalWalletBalance\": \"22.12659734\",\n                        \"asset\": \"USDT\"\n                    },\n                    {\n                        \"email\": \"345@test.com\",\n                        \"totalInitialMargin\": \"0.83137400\",\n                        \"totalMaintenanceMargin\": \"0.41568700\",\n                        \"totalMarginBalance\": \"0.90575887\",\n                        \"totalOpenOrderInitialMargin\": \"0.00000000\",\n                        \"totalPositionInitialMargin\": \"0.83137400\",\n                        \"totalUnrealizedProfit\": \"0.03219710\",\n                        \"totalWalletBalance\": \"0.87356177\",\n                        \"asset\": \"USDT\"\n                    }\n                ]\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"sub-account/futures/accountSummary\", True, data=params, version=2\n        )\n\n    def get_subaccount_futures_positionrisk(self, **params):\n        \"\"\"Get Futures Position-Risk of Sub-account (For Master Account)\n\n        https://developers.binance.com/docs/sub_account/account-management/Get-Futures-Position-Risk-of-Sub-account-V2\n\n        :param email: required - Sub account email\n        :type email: str\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            [\n                {\n                    \"entryPrice\": \"9975.12000\",\n                    \"leverage\": \"50\",              // current initial leverage\n                    \"maxNotional\": \"1000000\",      // notional value limit of current initial leverage\n                    \"liquidationPrice\": \"7963.54\",\n                    \"markPrice\": \"9973.50770517\",\n                    \"positionAmount\": \"0.010\",\n                    \"symbol\": \"BTCUSDT\",\n                    \"unrealizedProfit\": \"-0.01612295\"\n                }\n            ]\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"sub-account/futures/positionRisk\", True, data=params, version=2\n        )\n\n    def make_subaccount_futures_transfer(self, **params):\n        \"\"\"Futures Transfer for Sub-account (For Master Account)\n\n        https://developers.binance.com/docs/sub_account/asset-management\n\n        :param email: required - Sub account email\n        :type email: str\n        :param asset: required - The asset being transferred, e.g., USDT\n        :type asset: str\n        :param amount: required - The amount to be transferred\n        :type amount: float\n        :param type: required - 1: transfer from subaccount's spot account to its USDT-margined futures account\n                                2: transfer from subaccount's USDT-margined futures account to its spot account\n                                3: transfer from subaccount's spot account to its COIN-margined futures account\n                                4: transfer from subaccount's COIN-margined futures account to its spot account\n        :type type: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"txnId\":\"2966662589\"\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"post\", \"sub-account/futures/transfer\", True, data=params\n        )\n\n    def make_subaccount_margin_transfer(self, **params):\n        \"\"\"Margin Transfer for Sub-account (For Master Account)\n\n        https://developers.binance.com/docs/sub_account/asset-management/Margin-Transfer-for-Sub-account\n\n        :param email: required - Sub account email\n        :type email: str\n        :param asset: required - The asset being transferred, e.g., USDT\n        :type asset: str\n        :param amount: required - The amount to be transferred\n        :type amount: float\n        :param type: required - 1: transfer from subaccount's spot account to margin account\n                                2: transfer from subaccount's margin account to its spot account\n        :type type: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"txnId\":\"2966662589\"\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"post\", \"sub-account/margin/transfer\", True, data=params\n        )\n\n    def make_subaccount_to_subaccount_transfer(self, **params):\n        \"\"\"Transfer to Sub-account of Same Master (For Sub-account)\n\n        https://developers.binance.com/docs/sub_account/asset-management/Transfer-to-Sub-account-of-Same-Master\n\n        :param toEmail: required - Sub account email\n        :type toEmail: str\n        :param asset: required - The asset being transferred, e.g., USDT\n        :type asset: str\n        :param amount: required - The amount to be transferred\n        :type amount: float\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"txnId\":\"2966662589\"\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"post\", \"sub-account/transfer/subToSub\", True, data=params\n        )\n\n    def make_subaccount_to_master_transfer(self, **params):\n        \"\"\"Transfer to Master (For Sub-account)\n\n        https://developers.binance.com/docs/sub_account/asset-management/Transfer-to-Master\n\n        :param asset: required - The asset being transferred, e.g., USDT\n        :type asset: str\n        :param amount: required - The amount to be transferred\n        :type amount: float\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"txnId\":\"2966662589\"\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"post\", \"sub-account/transfer/subToMaster\", True, data=params\n        )\n\n    def get_subaccount_transfer_history(self, **params):\n        \"\"\"Sub-account Transfer History (For Sub-account)\n\n        https://developers.binance.com/docs/sub_account/asset-management/Sub-account-Transfer-History\n\n        :param asset: required - The asset being transferred, e.g., USDT\n        :type asset: str\n        :param type: optional - 1: transfer in, 2: transfer out\n        :type type: int\n        :param startTime: optional\n        :type startTime: int\n        :param endTime: optional\n        :type endTime: int\n        :param limit: optional - Default 500\n        :type limit: int\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            [\n              {\n                \"counterParty\":\"master\",\n                \"email\":\"master@test.com\",\n                \"type\":1,  // 1 for transfer in, 2 for transfer out\n                \"asset\":\"BTC\",\n                \"qty\":\"1\",\n                \"status\":\"SUCCESS\",\n                \"tranId\":11798835829,\n                \"time\":1544433325000\n              },\n              {\n                \"counterParty\":\"subAccount\",\n                \"email\":\"sub2@test.com\",\n                \"type\":2,\n                \"asset\":\"ETH\",\n                \"qty\":\"2\",\n                \"status\":\"SUCCESS\",\n                \"tranId\":11798829519,\n                \"time\":1544433326000\n              }\n            ]\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"sub-account/transfer/subUserHistory\", True, data=params\n        )\n\n    def make_subaccount_universal_transfer(self, **params):\n        \"\"\"Universal Transfer (For Master Account)\n\n        https://developers.binance.com/docs/sub_account/asset-management/Universal-Transfer\n\n        :param fromEmail: optional\n        :type fromEmail: str\n        :param toEmail: optional\n        :type toEmail: str\n        :param fromAccountType: required - \"SPOT\",\"USDT_FUTURE\",\"COIN_FUTURE\"\n        :type fromAccountType: str\n        :param toAccountType: required - \"SPOT\",\"USDT_FUTURE\",\"COIN_FUTURE\"\n        :type toAccountType: str\n        :param asset: required - The asset being transferred, e.g., USDT\n        :type asset: str\n        :param amount: required\n        :type amount: float\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"tranId\":11945860693\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"post\", \"sub-account/universalTransfer\", True, data=params\n        )\n\n    def get_universal_transfer_history(self, **params):\n        \"\"\"Universal Transfer (For Master Account)\n\n        https://developers.binance.com/docs/sub_account/asset-management/Query-Universal-Transfer-History\n\n        :param fromEmail: optional\n        :type fromEmail: str\n        :param toEmail: optional\n        :type toEmail: str\n        :param startTime: optional\n        :type startTime: int\n        :param endTime: optional\n        :type endTime: int\n        :param page: optional\n        :type page: int\n        :param limit: optional\n        :type limit: int\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            [\n              {\n                \"tranId\":11945860693,\n                \"fromEmail\":\"master@test.com\",\n                \"toEmail\":\"subaccount1@test.com\",\n                \"asset\":\"BTC\",\n                \"amount\":\"0.1\",\n                \"fromAccountType\":\"SPOT\",\n                \"toAccountType\":\"COIN_FUTURE\",\n                \"status\":\"SUCCESS\",\n                \"createTimeStamp\":1544433325000\n              },\n              {\n                \"tranId\":11945857955,\n                \"fromEmail\":\"master@test.com\",\n                \"toEmail\":\"subaccount2@test.com\",\n                \"asset\":\"ETH\",\n                \"amount\":\"0.2\",\n                \"fromAccountType\":\"SPOT\",\n                \"toAccountType\":\"USDT_FUTURE\",\n                \"status\":\"SUCCESS\",\n                \"createTimeStamp\":1544433326000\n              }\n            ]\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"sub-account/universalTransfer\", True, data=params\n        )\n\n    # Futures API\n\n    def futures_ping(self):\n        \"\"\"Test connectivity to the Rest API\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api\n\n        \"\"\"\n        return self._request_futures_api(\"get\", \"ping\")\n\n    def futures_time(self):\n        \"\"\"Test connectivity to the Rest API and get the current server time.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Check-Server-Time\n\n        \"\"\"\n        return self._request_futures_api(\"get\", \"time\")\n\n    def futures_exchange_info(self):\n        \"\"\"Current exchange trading rules and symbol information\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Exchange-Information\n\n        \"\"\"\n        return self._request_futures_api(\"get\", \"exchangeInfo\")\n\n    def futures_order_book(self, **params):\n        \"\"\"Get the Order Book for the market\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Order-Book\n\n        \"\"\"\n        return self._request_futures_api(\"get\", \"depth\", data=params)\n\n    def futures_rpi_depth(self, **params):\n        \"\"\"Get RPI Order Book with Retail Price Improvement orders\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/RPI-Order-Book\n\n        :param symbol: required\n        :type symbol: str\n        :param limit: Default 1000; Valid limits:[1000]\n        :type limit: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"lastUpdateId\": 1027024,\n                \"E\": 1589436922972,   // Message output time\n                \"T\": 1589436922959,   // Transaction time\n                \"bids\": [\n                    [\n                        \"4.00000000\",     // PRICE\n                        \"431.00000000\"    // QTY\n                    ]\n                ],\n                \"asks\": [\n                    [\n                        \"4.00000200\",\n                        \"12.00000000\"\n                    ]\n                ]\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_futures_api(\"get\", \"rpiDepth\", data=params)\n\n    def futures_recent_trades(self, **params):\n        \"\"\"Get recent trades (up to last 500).\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Recent-Trades-List\n\n        \"\"\"\n        return self._request_futures_api(\"get\", \"trades\", data=params)\n\n    def futures_historical_trades(self, **params):\n        \"\"\"Get older market historical trades.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Old-Trades-Lookup\n\n        \"\"\"\n        return self._request_futures_api(\"get\", \"historicalTrades\", data=params)\n\n    def futures_aggregate_trades(self, **params):\n        \"\"\"Get compressed, aggregate trades. Trades that fill at the time, from the same order, with the same\n        price will have the quantity aggregated.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Compressed-Aggregate-Trades-List\n\n        \"\"\"\n        return self._request_futures_api(\"get\", \"aggTrades\", data=params)\n\n    def futures_klines(self, **params):\n        \"\"\"Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Kline-Candlestick-Data\n\n        \"\"\"\n        return self._request_futures_api(\"get\", \"klines\", data=params)\n\n    def futures_mark_price_klines(self, **params):\n        \"\"\"Kline/candlestick bars for the mark price of a symbol. Klines are uniquely identified by their open time.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Mark-Price-Kline-Candlestick-Data\n\n        \"\"\"\n        return self._request_futures_api(\"get\", \"markPriceKlines\", data=params)\n\n    def futures_index_price_klines(self, **params):\n        \"\"\"Kline/candlestick bars for the index price of a symbol. Klines are uniquely identified by their open time.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Index-Price-Kline-Candlestick-Data\n\n        \"\"\"\n        return self._request_futures_api(\"get\", \"indexPriceKlines\", data=params)\n\n    def futures_premium_index_klines(self, **params):\n        \"\"\"Premium index kline bars of a symbol.l. Klines are uniquely identified by their open time.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Premium-Index-Kline-Data\n\n        \"\"\"\n        return self._request_futures_api(\"get\", \"premiumIndexKlines\", data=params)\n\n    def futures_continuous_klines(self, **params):\n        \"\"\"Kline/candlestick bars for a specific contract type. Klines are uniquely identified by their open time.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Continuous-Contract-Kline-Candlestick-Data\n\n        \"\"\"\n        return self._request_futures_api(\"get\", \"continuousKlines\", data=params)\n\n    def futures_historical_klines(\n        self, symbol: str, interval :str, start_str, end_str=None, limit=None\n    ):\n        \"\"\"Get historical futures klines from Binance\n\n        :param symbol: Name of symbol pair e.g. BNBBTC\n        :type symbol: str\n        :param interval: Binance Kline interval\n        :type interval: str\n        :param start_str: Start date string in UTC format or timestamp in milliseconds\n        :type start_str: str|int\n        :param end_str: optional - end date string in UTC format or timestamp in milliseconds (default will fetch everything up to now)\n        :type end_str: str|int\n        :param limit: Default None (fetches full range in batches of max 1000 per request). To limit the number of rows, pass an integer.\n        :type limit: int\n\n        :return: list of OHLCV values (Open time, Open, High, Low, Close, Volume, Close time, Quote asset volume, Number of trades, Taker buy base asset volume, Taker buy quote asset volume, Ignore)\n\n        \"\"\"\n        return self._historical_klines(\n            symbol,\n            interval,\n            start_str,\n            end_str=end_str,\n            limit=limit,\n            klines_type=HistoricalKlinesType.FUTURES,\n        )\n\n    def futures_historical_mark_price_klines(\n        self, symbol: str, interval: str, start_str, end_str=None, limit=None\n    ):\n        \"\"\"Get historical futures mark price klines from Binance\n\n        :param symbol: Name of symbol pair e.g. BNBBTC\n        :type symbol: str\n        :param interval: Binance Kline interval\n        :type interval: str\n        :param start_str: Start date string in UTC format or timestamp in milliseconds\n        :type start_str: str|int\n        :param end_str: optional - end date string in UTC format or timestamp in milliseconds (default will fetch everything up to now)\n        :type end_str: str|int\n        :param limit: Default None (fetches full range in batches of max 1000 per request). To limit the number of rows, pass an integer.\n        :type limit: int\n\n        :return: list of OHLCV values (Open time, Open, High, Low, Close, Volume, Close time, Quote asset volume, Number of trades, Taker buy base asset volume, Taker buy quote asset volume, Ignore)\n\n        \"\"\"\n        return self._historical_klines(\n            symbol,\n            interval,\n            start_str,\n            end_str=end_str,\n            limit=limit,\n            klines_type=HistoricalKlinesType.FUTURES_MARK_PRICE,\n        )\n\n    def futures_historical_klines_generator(\n        self, symbol, interval, start_str, end_str=None\n    ):\n        \"\"\"Get historical futures klines generator from Binance\n\n        :param symbol: Name of symbol pair e.g. BNBBTC\n        :type symbol: str\n        :param interval: Binance Kline interval\n        :type interval: str\n        :param start_str: Start date string in UTC format or timestamp in milliseconds\n        :type start_str: str|int\n        :param end_str: optional - end date string in UTC format or timestamp in milliseconds (default will fetch everything up to now)\n        :type end_str: str|int\n\n        :return: generator of OHLCV values\n\n        \"\"\"\n\n        return self._historical_klines_generator(\n            symbol,\n            interval,\n            start_str,\n            end_str=end_str,\n            klines_type=HistoricalKlinesType.FUTURES,\n        )\n\n    def futures_mark_price(self, **params):\n        \"\"\"Get Mark Price and Funding Rate\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Mark-Price\n\n        \"\"\"\n        return self._request_futures_api(\"get\", \"premiumIndex\", data=params)\n\n    def futures_funding_rate(self, **params):\n        \"\"\"Get funding rate history\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Get-Funding-Rate-History\n\n        \"\"\"\n        return self._request_futures_api(\"get\", \"fundingRate\", data=params)\n\n    def futures_top_longshort_account_ratio(self, **params):\n        \"\"\"Get present long to short ratio for top accounts of a specific symbol.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Top-Long-Short-Account-Ratio\n        \"\"\"\n        return self._request_futures_data_api(\n            \"get\", \"topLongShortAccountRatio\", data=params\n        )\n\n    def futures_top_longshort_position_ratio(self, **params):\n        \"\"\"Get present long to short ratio for top positions of a specific symbol.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Top-Trader-Long-Short-Ratio\n        \"\"\"\n        return self._request_futures_data_api(\n            \"get\", \"topLongShortPositionRatio\", data=params\n        )\n\n    def futures_global_longshort_ratio(self, **params):\n        \"\"\"Get present global long to short ratio of a specific symbol.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Long-Short-Ratio\n        \"\"\"\n        return self._request_futures_data_api(\n            \"get\", \"globalLongShortAccountRatio\", data=params\n        )\n\n    def futures_taker_longshort_ratio(self, **params):\n        \"\"\"Get taker buy to sell volume ratio of a specific symbol\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Taker-BuySell-Volume\n        \"\"\"\n        return self._request_futures_data_api(\n            \"get\", \"takerlongshortRatio\", data=params\n        )\n\n    def futures_basis(self, **params):\n        \"\"\"Get future basis of a specific symbol\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Basis\n        \"\"\"\n        return self._request_futures_data_api(\n            \"get\", \"basis\", data=params\n        )\n\n    def futures_ticker(self, **params):\n        \"\"\"24 hour rolling window price change statistics.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/24hr-Ticker-Price-Change-Statistics\n\n        \"\"\"\n        return self._request_futures_api(\"get\", \"ticker/24hr\", data=params)\n\n    def futures_symbol_ticker(self, **params):\n        \"\"\"Latest price for a symbol or symbols.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Symbol-Price-Ticker-v2\n\n        \"\"\"\n        return self._request_futures_api(\"get\", \"ticker/price\", version=2, data=params)\n\n    def futures_orderbook_ticker(self, **params):\n        \"\"\"Best price/qty on the order book for a symbol or symbols.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Symbol-Order-Book-Ticker\n\n        \"\"\"\n        return self._request_futures_api(\"get\", \"ticker/bookTicker\", data=params)\n\n    def futures_delivery_price(self, **params):\n        \"\"\"Get latest price for a symbol or symbols\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Delivery-Price\n\n        \"\"\"\n        return self._request_futures_data_api(\"get\", \"delivery-price\", data=params)\n\n    def futures_index_price_constituents(self, **params):\n        \"\"\"Get index price constituents\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Index-Constituents\n\n        \"\"\"\n        return self._request_futures_api(\"get\", \"constituents\", data=params)\n\n    def futures_insurance_fund_balance_snapshot(self, **params):\n        \"\"\"Get Insurance Fund Balance Snapshot\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Insurance-Fund-Balance\n\n        \"\"\"\n        return self._request_futures_api(\"get\", \"insuranceBalance\", data=params)\n\n    def futures_liquidation_orders(self, **params):\n        \"\"\"Get all liquidation orders\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Users-Force-Orders\n\n        \"\"\"\n        return self._request_futures_api(\"get\", \"forceOrders\", signed=True, data=params)\n\n    def futures_api_trading_status(self, **params):\n        \"\"\"Get quantitative trading rules for order placement, such as Unfilled Ratio (UFR), Good-Til-Canceled Ratio (GCR),\n        Immediate-or-Cancel (IOC) & Fill-or-Kill (FOK) Expire Ratio (IFER), among others.\n        https://www.binance.com/en/support/faq/binance-futures-trading-quantitative-rules-4f462ebe6ff445d4a170be7d9e897272\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Futures-Trading-Quantitative-Rules-Indicators\n\n        :param symbol: optional\n        :type symbol: str\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"indicators\": { // indicator: quantitative rules indicators, value: user's indicators value, triggerValue: trigger indicator value threshold of quantitative rules.\n                    \"BTCUSDT\": [\n                        {\n                            \"isLocked\": true,\n                            \"plannedRecoverTime\": 1545741270000,\n                            \"indicator\": \"UFR\",  // Unfilled Ratio (UFR)\n                            \"value\": 0.05,  // Current value\n                            \"triggerValue\": 0.995  // Trigger value\n                        },\n                        {\n                            \"isLocked\": true,\n                            \"plannedRecoverTime\": 1545741270000,\n                            \"indicator\": \"IFER\",  // IOC/FOK Expiration Ratio (IFER)\n                            \"value\": 0.99,  // Current value\n                            \"triggerValue\": 0.99  // Trigger value\n                        },\n                        {\n                            \"isLocked\": true,\n                            \"plannedRecoverTime\": 1545741270000,\n                            \"indicator\": \"GCR\",  // GTC Cancellation Ratio (GCR)\n                            \"value\": 0.99,  // Current value\n                            \"triggerValue\": 0.99  // Trigger value\n                        },\n                        {\n                            \"isLocked\": true,\n                            \"plannedRecoverTime\": 1545741270000,\n                            \"indicator\": \"DR\",  // Dust Ratio (DR)\n                            \"value\": 0.99,  // Current value\n                            \"triggerValue\": 0.99  // Trigger value\n                        }\n                    ],\n                    \"ETHUSDT\": [\n                        {\n                            \"isLocked\": true,\n                            \"plannedRecoverTime\": 1545741270000,\n                            \"indicator\": \"UFR\",\n                            \"value\": 0.05,\n                            \"triggerValue\": 0.995\n                        },\n                        {\n                            \"isLocked\": true,\n                            \"plannedRecoverTime\": 1545741270000,\n                            \"indicator\": \"IFER\",\n                            \"value\": 0.99,\n                            \"triggerValue\": 0.99\n                        },\n                        {\n                            \"isLocked\": true,\n                            \"plannedRecoverTime\": 1545741270000,\n                            \"indicator\": \"GCR\",\n                            \"value\": 0.99,\n                            \"triggerValue\": 0.99\n                        }\n                        {\n                            \"isLocked\": true,\n                            \"plannedRecoverTime\": 1545741270000,\n                            \"indicator\": \"DR\",\n                            \"value\": 0.99,\n                            \"triggerValue\": 0.99\n                        }\n                    ]\n                },\n                \"updateTime\": 1545741270000\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_futures_api(\n            \"get\", \"apiTradingStatus\", signed=True, data=params\n        )\n\n    def futures_commission_rate(self, **params):\n        \"\"\"Get Futures commission rate\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/User-Commission-Rate\n\n        :param symbol: required\n        :type symbol: str\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"symbol\": \"BTCUSDT\",\n                \"makerCommissionRate\": \"0.0002\",  // 0.02%\n                \"takerCommissionRate\": \"0.0004\"   // 0.04%\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_futures_api(\n            \"get\", \"commissionRate\", signed=True, data=params\n        )\n\n    def futures_adl_quantile_estimate(self, **params):\n        \"\"\"Get Position ADL Quantile Estimate\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Position-ADL-Quantile-Estimation\n\n        \"\"\"\n        return self._request_futures_api(\"get\", \"adlQuantile\", signed=True, data=params)\n\n    def futures_open_interest(self, **params):\n        \"\"\"Get present open interest of a specific symbol.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Open-Interest\n\n        \"\"\"\n        return self._request_futures_api(\"get\", \"openInterest\", data=params)\n\n    def futures_index_info(self, **params):\n        \"\"\"Get index_info\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Composite-Index-Symbol-Information\n\n        \"\"\"\n        return self._request_futures_api(\"get\", \"indexInfo\", data=params)\n\n    def futures_open_interest_hist(self, **params):\n        \"\"\"Get open interest statistics of a specific symbol.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Open-Interest-Statistics\n\n        \"\"\"\n        return self._request_futures_data_api(\"get\", \"openInterestHist\", data=params)\n\n    def futures_leverage_bracket(self, **params):\n        \"\"\"Notional and Leverage Brackets\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Notional-and-Leverage-Brackets\n\n        \"\"\"\n        return self._request_futures_api(\"get\", \"leverageBracket\", True, data=params)\n\n    def futures_account_transfer(self, **params):\n        \"\"\"Execute transfer between spot account and futures account.\n\n        https://binance-docs.github.io/apidocs/futures/en/#new-future-account-transfer\n\n        \"\"\"\n        return self._request_margin_api(\"post\", \"futures/transfer\", True, data=params)\n\n    def transfer_history(self, **params):\n        \"\"\"Get future account transaction history list\n\n        https://binance-docs.github.io/apidocs/futures/en/#get-future-account-transaction-history-list-user_data\n\n        \"\"\"\n        return self._request_margin_api(\"get\", \"futures/transfer\", True, data=params)\n\n    def futures_loan_borrow_history(self, **params):\n        return self._request_margin_api(\n            \"get\", \"futures/loan/borrow/history\", True, data=params\n        )\n\n    def futures_loan_repay_history(self, **params):\n        return self._request_margin_api(\n            \"get\", \"futures/loan/repay/history\", True, data=params\n        )\n\n    def futures_loan_wallet(self, **params):\n        return self._request_margin_api(\n            \"get\", \"futures/loan/wallet\", True, data=params, version=2\n        )\n\n    def futures_cross_collateral_adjust_history(self, **params):\n        return self._request_margin_api(\n            \"get\", \"futures/loan/adjustCollateral/history\", True, data=params\n        )\n\n    def futures_cross_collateral_liquidation_history(self, **params):\n        return self._request_margin_api(\n            \"get\", \"futures/loan/liquidationHistory\", True, data=params\n        )\n\n    def futures_loan_interest_history(self, **params):\n        return self._request_margin_api(\n            \"get\", \"futures/loan/interestHistory\", True, data=params\n        )\n\n    def futures_create_order(self, **params):\n        \"\"\"Send in a new order.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api\n\n        Note: After 2025-12-09, conditional order types (STOP, STOP_MARKET, TAKE_PROFIT,\n        TAKE_PROFIT_MARKET, TRAILING_STOP_MARKET) are automatically routed to the algo\n        order endpoint.\n\n        \"\"\"\n        # Check if this is a conditional order type that needs to use algo endpoint\n        order_type = params.get(\"type\", \"\").upper()\n        conditional_types = [\n            \"STOP\",\n            \"STOP_MARKET\",\n            \"TAKE_PROFIT\",\n            \"TAKE_PROFIT_MARKET\",\n            \"TRAILING_STOP_MARKET\",\n        ]\n\n        if order_type in conditional_types:\n            # Route to algo order endpoint\n            if \"clientAlgoId\" not in params:\n                params[\"clientAlgoId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n            # Remove newClientOrderId if it was added by default\n            params.pop(\"newClientOrderId\", None)\n            params[\"algoType\"] = \"CONDITIONAL\"\n            # Convert stopPrice to triggerPrice for algo orders (camelCase per API docs)\n            if \"stopPrice\" in params and \"triggerPrice\" not in params:\n                params[\"triggerPrice\"] = params.pop(\"stopPrice\")\n            return self._request_futures_api(\"post\", \"algoOrder\", True, data=params)\n        else:\n            # Use regular order endpoint\n            if \"newClientOrderId\" not in params:\n                params[\"newClientOrderId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n            return self._request_futures_api(\"post\", \"order\", True, data=params)\n\n    def futures_limit_order(self, **params):\n        \"\"\"Send in a new futures limit order.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api\n\n        \"\"\"\n        if \"newClientOrderId\" not in params:\n            params[\"newClientOrderId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n        params[\"type\"] = \"LIMIT\"\n        return self._request_futures_api(\"post\", \"order\", True, data=params)\n\n    def futures_market_order(self, **params):\n        \"\"\"Send in a new futures market order.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api\n\n        \"\"\"\n        if \"newClientOrderId\" not in params:\n            params[\"newClientOrderId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n        params[\"type\"] = \"MARKET\"\n        return self._request_futures_api(\"post\", \"order\", True, data=params)\n\n\n    def futures_limit_buy_order(self, **params):\n        \"\"\"Send in a new futures limit buy order.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api\n\n        \"\"\"\n        if \"newClientOrderId\" not in params:\n            params[\"newClientOrderId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n        params[\"side\"] = \"BUY\"\n        params[\"type\"] = \"LIMIT\"\n        return self._request_futures_api(\"post\", \"order\", True, data=params)\n\n    def futures_limit_sell_order(self, **params):\n        \"\"\"Send in a new futures limit sell order.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api\n\n        \"\"\"\n        if \"newClientOrderId\" not in params:\n            params[\"newClientOrderId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n        params[\"side\"] = \"SELL\"\n        params[\"type\"] = \"LIMIT\"\n        return self._request_futures_api(\"post\", \"order\", True, data=params)\n\n    def futures_market_buy_order(self, **params):\n        \"\"\"Send in a new futures market buy order.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api\n\n        \"\"\"\n        if \"newClientOrderId\" not in params:\n            params[\"newClientOrderId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n        params[\"side\"] = \"BUY\"\n        params[\"type\"] = \"MARKET\"\n        return self._request_futures_api(\"post\", \"order\", True, data=params)\n\n    def futures_market_sell_order(self, **params):\n        \"\"\"Send in a new futures market sell order.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api\n\n        \"\"\"\n        if \"newClientOrderId\" not in params:\n            params[\"newClientOrderId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n        params[\"side\"] = \"SELL\"\n        params[\"type\"] = \"MARKET\"\n        return self._request_futures_api(\"post\", \"order\", True, data=params)\n\n    def futures_modify_order(self, **params):\n        \"\"\"Modify an existing order. Currently only LIMIT order modification is supported.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Modify-Order\n\n        \"\"\"\n        return self._request_futures_api(\"put\", \"order\", True, data=params)\n\n    def futures_create_test_order(self, **params):\n        \"\"\"Testing order request, this order will not be submitted to matching engine\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/New-Order-Test\n\n        \"\"\"\n        return self._request_futures_api(\"post\", \"order/test\", True, data=params)\n\n    def futures_place_batch_order(self, **params):\n        \"\"\"Send in new orders.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Place-Multiple-Orders\n\n        To avoid modifying the existing signature generation and parameter order logic,\n        the url encoding is done on the special query param, batchOrders, in the early stage.\n\n        \"\"\"\n        for order in params[\"batchOrders\"]:\n            if \"newClientOrderId\" not in order:\n                order[\"newClientOrderId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n        query_string = urlencode(params)\n        query_string = query_string.replace(\"%27\", \"%22\")\n        params[\"batchOrders\"] = query_string[12:]\n        return self._request_futures_api(\n            \"post\", \"batchOrders\", True, data=params, force_params=True\n        )\n\n    def futures_get_order(self, **params):\n        \"\"\"Check an order's status.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Query-Order\n\n        :param conditional: optional - Set to True to query algo/conditional order\n        :type conditional: bool\n        :param algoId: optional - Algo order ID (for conditional orders)\n        :type algoId: int\n        :param clientAlgoId: optional - Client algo order ID (for conditional orders)\n        :type clientAlgoId: str\n\n        \"\"\"\n        # Check if this is a request for a conditional/algo order\n        is_conditional = params.pop(\"conditional\", False)\n        # Also check if algoId or clientAlgoId is provided\n        if \"algoId\" in params or \"clientAlgoId\" in params:\n            is_conditional = True\n\n        if is_conditional:\n            return self._request_futures_api(\"get\", \"algoOrder\", True, data=params)\n        else:\n            return self._request_futures_api(\"get\", \"order\", True, data=params)\n\n    def futures_get_open_orders(self, **params):\n        \"\"\"Get all open orders on a symbol.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Current-All-Open-Orders\n\n        :param conditional: optional - Set to True to query algo/conditional orders\n        :type conditional: bool\n\n        \"\"\"\n        is_conditional = params.pop(\"conditional\", False)\n\n        if is_conditional:\n            return self._request_futures_api(\"get\", \"openAlgoOrders\", True, data=params)\n        else:\n            return self._request_futures_api(\"get\", \"openOrders\", True, data=params)\n\n    def futures_get_all_orders(self, **params):\n        \"\"\"Get all futures account orders; active, canceled, or filled.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/All-Orders\n\n        :param conditional: optional - Set to True to query algo/conditional orders\n        :type conditional: bool\n\n        \"\"\"\n        is_conditional = params.pop(\"conditional\", False)\n\n        if is_conditional:\n            return self._request_futures_api(\"get\", \"allAlgoOrders\", True, data=params)\n        else:\n            return self._request_futures_api(\"get\", \"allOrders\", True, data=params)\n\n    def futures_cancel_order(self, **params):\n        \"\"\"Cancel an active futures order.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Cancel-Order\n\n        :param conditional: optional - Set to True to cancel algo/conditional order\n        :type conditional: bool\n        :param algoId: optional - Algo order ID (for conditional orders)\n        :type algoId: int\n        :param clientAlgoId: optional - Client algo order ID (for conditional orders)\n        :type clientAlgoId: str\n\n        \"\"\"\n        # Check if this is a request for a conditional/algo order\n        is_conditional = params.pop(\"conditional\", False)\n        # Also check if algoId or clientAlgoId is provided\n        if \"algoId\" in params or \"clientAlgoId\" in params:\n            is_conditional = True\n\n        if is_conditional:\n            return self._request_futures_api(\"delete\", \"algoOrder\", True, data=params)\n        else:\n            return self._request_futures_api(\"delete\", \"order\", True, data=params)\n\n    def futures_cancel_all_open_orders(self, **params):\n        \"\"\"Cancel all open futures orders\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Cancel-All-Open-Orders\n\n        :param conditional: optional - Set to True to cancel algo/conditional orders\n        :type conditional: bool\n\n        \"\"\"\n        is_conditional = params.pop(\"conditional\", False)\n\n        if is_conditional:\n            return self._request_futures_api(\n                \"delete\", \"algoOpenOrders\", True, data=params\n            )\n        else:\n            return self._request_futures_api(\"delete\", \"allOpenOrders\", True, data=params)\n\n    def futures_cancel_orders(self, **params):\n        \"\"\"Cancel multiple futures orders\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Cancel-Multiple-Orders\n\n        \"\"\"\n        if params.get(\"orderidlist\"):\n            params[\"orderidlist\"] = quote(\n                convert_list_to_json_array(params[\"orderidlist\"])\n            )\n        if params.get(\"origclientorderidlist\"):\n            params[\"origclientorderidlist\"] = quote(\n                convert_list_to_json_array(params[\"origclientorderidlist\"])\n            )\n        return self._request_futures_api(\n            \"delete\", \"batchOrders\", True, force_params=True, data=params\n        )\n\n    def futures_countdown_cancel_all(self, **params):\n        \"\"\"Cancel all open orders of the specified symbol at the end of the specified countdown.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Auto-Cancel-All-Open-Orders\n\n        :param symbol: required\n        :type symbol: str\n        :param countdownTime: required\n        :type countdownTime: int\n        :param recvWindow: optional - the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n        {\n            \"symbol\": \"BTCUSDT\",\n            \"countdownTime\": \"100000\"\n        }\n\n        \"\"\"\n        return self._request_futures_api(\n            \"post\", \"countdownCancelAll\", True, data=params\n        )\n\n    # Algo Orders (Conditional Orders)\n\n    def futures_create_algo_order(self, **params):\n        \"\"\"Send in a new algo order (conditional order).\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/New-Algo-Order\n\n        :param algoType: required - Only support CONDITIONAL\n        :type algoType: str\n        :param symbol: required\n        :type symbol: str\n        :param side: required - BUY or SELL\n        :type side: str\n        :param positionSide: optional - Default BOTH for One-way Mode; LONG or SHORT for Hedge Mode\n        :type positionSide: str\n        :param type: required - STOP_MARKET/TAKE_PROFIT_MARKET/STOP/TAKE_PROFIT/TRAILING_STOP_MARKET\n        :type type: str\n        :param timeInForce: optional - IOC or GTC or FOK or GTX, default GTC\n        :type timeInForce: str\n        :param quantity: optional - Cannot be sent with closePosition=true\n        :type quantity: decimal\n        :param price: optional\n        :type price: decimal\n        :param triggerPrice: optional - Used with STOP, STOP_MARKET, TAKE_PROFIT, TAKE_PROFIT_MARKET\n        :type triggerPrice: decimal\n        :param workingType: optional - triggerPrice triggered by: MARK_PRICE, CONTRACT_PRICE. Default CONTRACT_PRICE\n        :type workingType: str\n        :param priceMatch: optional - only available for LIMIT/STOP/TAKE_PROFIT order\n        :type priceMatch: str\n        :param closePosition: optional - true, false; Close-All, used with STOP_MARKET or TAKE_PROFIT_MARKET\n        :type closePosition: str\n        :param priceProtect: optional - \"TRUE\" or \"FALSE\", default \"FALSE\"\n        :type priceProtect: str\n        :param reduceOnly: optional - \"true\" or \"false\", default \"false\"\n        :type reduceOnly: str\n        :param activatePrice: optional - Used with TRAILING_STOP_MARKET orders\n        :type activatePrice: decimal\n        :param callbackRate: optional - Used with TRAILING_STOP_MARKET orders, min 0.1, max 10\n        :type callbackRate: decimal\n        :param clientAlgoId: optional - A unique id among open orders\n        :type clientAlgoId: str\n        :param newOrderRespType: optional - \"ACK\", \"RESULT\", default \"ACK\"\n        :type newOrderRespType: str\n        :param selfTradePreventionMode: optional - EXPIRE_TAKER, EXPIRE_MAKER, EXPIRE_BOTH, default NONE\n        :type selfTradePreventionMode: str\n        :param goodTillDate: optional - order cancel time for timeInForce GTD\n        :type goodTillDate: long\n        :param recvWindow: optional - the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            result = client.futures_create_algo_order(\n                algoType='CONDITIONAL',\n                symbol='BNBUSDT',\n                side='SELL',\n                type='TAKE_PROFIT',\n                quantity='0.01',\n                price='750.000',\n                triggerPrice='750.000',\n                timeInForce='GTC'\n            )\n\n        \"\"\"\n        if \"clientAlgoId\" not in params:\n            params[\"clientAlgoId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n        if \"algoType\" not in params:\n            params[\"algoType\"] = \"CONDITIONAL\"\n        return self._request_futures_api(\"post\", \"algoOrder\", True, data=params)\n\n    def futures_cancel_algo_order(self, **params):\n        \"\"\"Cancel an active algo order.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Cancel-Algo-Order\n\n        :param symbol: required\n        :type symbol: str\n        :param algoId: optional - Either algoId or clientAlgoId must be sent\n        :type algoId: int\n        :param clientAlgoId: optional - Either algoId or clientAlgoId must be sent\n        :type clientAlgoId: str\n        :param recvWindow: optional - the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_futures_api(\"delete\", \"algoOrder\", True, data=params)\n\n    def futures_cancel_all_algo_open_orders(self, **params):\n        \"\"\"Cancel all open algo orders\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Cancel-All-Algo-Open-Orders\n\n        :param symbol: required\n        :type symbol: str\n        :param recvWindow: optional - the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_futures_api(\n            \"delete\", \"algoOpenOrders\", True, data=params\n        )\n\n    def futures_get_algo_order(self, **params):\n        \"\"\"Check an algo order's status.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Query-Algo-Order\n\n        :param symbol: required\n        :type symbol: str\n        :param algoId: optional - Either algoId or clientAlgoId must be sent\n        :type algoId: int\n        :param clientAlgoId: optional - Either algoId or clientAlgoId must be sent\n        :type clientAlgoId: str\n        :param recvWindow: optional - the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_futures_api(\"get\", \"algoOrder\", True, data=params)\n\n    def futures_get_open_algo_orders(self, **params):\n        \"\"\"Get all open algo orders on a symbol.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Current-All-Algo-Open-Orders\n\n        :param symbol: optional\n        :type symbol: str\n        :param recvWindow: optional - the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_futures_api(\"get\", \"openAlgoOrders\", True, data=params)\n\n    def futures_get_all_algo_orders(self, **params):\n        \"\"\"Get all algo account orders; active, canceled, or filled.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Query-All-Algo-Orders\n\n        :param symbol: required\n        :type symbol: str\n        :param startTime: optional\n        :type startTime: int\n        :param endTime: optional\n        :type endTime: int\n        :param limit: optional - Default 100; max 100\n        :type limit: int\n        :param recvWindow: optional - the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_futures_api(\"get\", \"allAlgoOrders\", True, data=params)\n\n    def futures_account_balance(self, **params):\n        \"\"\"Get futures account balance\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Futures-Account-Balance-V3\n\n        \"\"\"\n        return self._request_futures_api(\"get\", \"balance\", True, 3, data=params)\n\n    def futures_account(self, **params):\n        \"\"\"Get current account information.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Account-Information-V2\n\n        \"\"\"\n        return self._request_futures_api(\"get\", \"account\", True, 2, data=params)\n\n    def futures_symbol_adl_risk(self, **params):\n        \"\"\"Query the symbol-level ADL (Auto-Deleveraging) risk rating\n\n        The ADL risk rating measures the likelihood of ADL during liquidation.\n        Rating can be: high, medium, low. Updated every 30 minutes.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Query-ADL-Risk-Rating\n\n        :param symbol: optional - if not provided, returns ADL risk for all symbols\n        :type symbol: str\n\n        :returns: API response\n\n        .. code-block:: python\n\n            # Single symbol\n            {\n                \"symbol\": \"BTCUSDT\",\n                \"adlRisk\": \"low\",\n                \"updateTime\": 1597370495002\n            }\n\n            # All symbols (when symbol not provided)\n            [\n                {\n                    \"symbol\": \"BTCUSDT\",\n                    \"adlRisk\": \"low\",\n                    \"updateTime\": 1597370495002\n                },\n                {\n                    \"symbol\": \"ETHUSDT\",\n                    \"adlRisk\": \"high\",\n                    \"updateTime\": 1597370495004\n                }\n            ]\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_futures_api(\"get\", \"symbolAdlRisk\", True, data=params)\n\n    def futures_change_leverage(self, **params):\n        \"\"\"Change user's initial leverage of specific symbol market\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Change-Initial-Leverage\n\n        \"\"\"\n        return self._request_futures_api(\"post\", \"leverage\", True, data=params)\n\n    def futures_change_margin_type(self, **params):\n        \"\"\"Change the margin type for a symbol\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Change-Margin-Type\n\n        \"\"\"\n        return self._request_futures_api(\"post\", \"marginType\", True, data=params)\n\n    def futures_change_position_margin(self, **params):\n        \"\"\"Change the position margin for a symbol\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Modify-Isolated-Position-Margin\n\n        \"\"\"\n        return self._request_futures_api(\"post\", \"positionMargin\", True, data=params)\n\n    def futures_position_margin_history(self, **params):\n        \"\"\"Get position margin change history\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Get-Position-Margin-Change-History\n\n        \"\"\"\n        return self._request_futures_api(\n            \"get\", \"positionMargin/history\", True, data=params\n        )\n\n    def futures_position_information(self, **params):\n        \"\"\"Get position information\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Position-Information-V3\n\n        \"\"\"\n        return self._request_futures_api(\"get\", \"positionRisk\", True, 3, data=params)\n\n    def futures_account_trades(self, **params):\n        \"\"\"Get trades for the authenticated account and symbol.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Account-Trade-List\n\n        \"\"\"\n        return self._request_futures_api(\"get\", \"userTrades\", True, data=params)\n\n    def futures_income_history(self, **params):\n        \"\"\"Get income history for authenticated account\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Get-Income-History\n\n        \"\"\"\n        return self._request_futures_api(\"get\", \"income\", True, data=params)\n\n    def futures_change_position_mode(self, **params):\n        \"\"\"Change position mode for authenticated account\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Change-Position-Mode\n\n        \"\"\"\n        return self._request_futures_api(\"post\", \"positionSide/dual\", True, data=params)\n\n    def futures_get_position_mode(self, **params):\n        \"\"\"Get position mode for authenticated account\n\n        https://binance-docs.github.io/apidocs/futures/en/#get-current-position-mode-user_data\n\n        \"\"\"\n        return self._request_futures_api(\"get\", \"positionSide/dual\", True, data=params)\n\n    def futures_change_multi_assets_mode(self, multiAssetsMargin: bool):\n        \"\"\"Change user's Multi-Assets mode (Multi-Assets Mode or Single-Asset Mode) on Every symbol\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Change-Multi-Assets-Mode\n\n        \"\"\"\n        params = {\"multiAssetsMargin\": \"true\" if multiAssetsMargin else \"false\"}\n        return self._request_futures_api(\"post\", \"multiAssetsMargin\", True, data=params)\n\n    def futures_get_multi_assets_mode(self):\n        \"\"\"Get user's Multi-Assets mode (Multi-Assets Mode or Single-Asset Mode) on Every symbol\n\n        https://binance-docs.github.io/apidocs/futures/en/#get-current-multi-assets-mode-user_data\n\n        \"\"\"\n        return self._request_futures_api(\"get\", \"multiAssetsMargin\", True, data={})\n\n    def futures_stream_get_listen_key(self):\n        res = self._request_futures_api(\"post\", \"listenKey\", signed=False, data={})\n        return res[\"listenKey\"]\n\n    def futures_stream_keepalive(self, listenKey):\n        params = {\"listenKey\": listenKey}\n        return self._request_futures_api(\"put\", \"listenKey\", signed=False, data=params)\n\n    def futures_stream_close(self, listenKey):\n        params = {\"listenKey\": listenKey}\n        return self._request_futures_api(\n            \"delete\", \"listenKey\", signed=False, data=params\n        )\n\n    # new methods\n    def futures_account_config(self, **params):\n        \"\"\"Get futures account configuration\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Account-Config\n        \"\"\"\n        return self._request_futures_api(\n            \"get\", \"accountConfig\", signed=True, version=1, data=params\n        )\n\n    def futures_symbol_config(self, **params):\n        \"\"\"Get current account symbol configuration\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Symbol-Config\n        \"\"\"\n        return self._request_futures_api(\n            \"get\", \"symbolConfig\", signed=True, version=1, data=params\n        )\n\n    # COIN Futures API\n    def futures_coin_ping(self):\n        \"\"\"Test connectivity to the Rest API\n\n       https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api\n\n        \"\"\"\n        return self._request_futures_coin_api(\"get\", \"ping\")\n\n    def futures_coin_time(self):\n        \"\"\"Test connectivity to the Rest API and get the current server time.\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api/Check-Server-time\n\n        \"\"\"\n        return self._request_futures_coin_api(\"get\", \"time\")\n\n    def futures_coin_exchange_info(self):\n        \"\"\"Current exchange trading rules and symbol information\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api/Exchange-Information\n\n        \"\"\"\n        return self._request_futures_coin_api(\"get\", \"exchangeInfo\")\n\n    def futures_coin_order_book(self, **params):\n        \"\"\"Get the Order Book for the market\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api/Order-Book\n\n        \"\"\"\n        return self._request_futures_coin_api(\"get\", \"depth\", data=params)\n\n    def futures_coin_recent_trades(self, **params):\n        \"\"\"Get recent trades (up to last 500).\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api/Recent-Trades-List\n\n        \"\"\"\n        return self._request_futures_coin_api(\"get\", \"trades\", data=params)\n\n    def futures_coin_historical_trades(self, **params):\n        \"\"\"Get older market historical trades.\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api/Old-Trades-Lookup\n\n        \"\"\"\n        return self._request_futures_coin_api(\"get\", \"historicalTrades\", data=params)\n\n    def futures_coin_aggregate_trades(self, **params):\n        \"\"\"Get compressed, aggregate trades. Trades that fill at the time, from the same order, with the same\n        price will have the quantity aggregated.\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api/Compressed-Aggregate-Trades-List\n\n        \"\"\"\n        return self._request_futures_coin_api(\"get\", \"aggTrades\", data=params)\n\n    def futures_coin_klines(self, **params):\n        \"\"\"Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time.\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api/Kline-Candlestick-Data\n\n        \"\"\"\n        return self._request_futures_coin_api(\"get\", \"klines\", data=params)\n\n    def futures_coin_continous_klines(self, **params):\n        \"\"\"Kline/candlestick bars for a specific contract type. Klines are uniquely identified by their open time.\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api/Continuous-Contract-Kline-Candlestick-Data\n\n        \"\"\"\n        return self._request_futures_coin_api(\"get\", \"continuousKlines\", data=params)\n\n    def futures_coin_index_price_klines(self, **params):\n        \"\"\"Kline/candlestick bars for the index price of a pair..\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api/Index-Price-Kline-Candlestick-Data\n\n        \"\"\"\n        return self._request_futures_coin_api(\"get\", \"indexPriceKlines\", data=params)\n\n    def futures_coin_premium_index_klines(self, **params):\n        \"\"\"Kline/candlestick bars for the index price of a pair..\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api/Premium-Index-Kline-Data\n\n        \"\"\"\n        return self._request_futures_coin_api(\"get\", \"premiumIndexKlines\", data=params)\n\n    def futures_coin_mark_price_klines(self, **params):\n        \"\"\"Kline/candlestick bars for the index price of a pair..\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api/Mark-Price-Kline-Candlestick-Data\n\n        \"\"\"\n        return self._request_futures_coin_api(\"get\", \"markPriceKlines\", data=params)\n\n    def futures_coin_mark_price(self, **params):\n        \"\"\"Get Mark Price and Funding Rate\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api/Index-Price-and-Mark-Price\n\n        \"\"\"\n        return self._request_futures_coin_api(\"get\", \"premiumIndex\", data=params)\n\n    def futures_coin_funding_rate(self, **params):\n        \"\"\"Get funding rate history\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api/Get-Funding-Rate-History-of-Perpetual-Futures\n\n        \"\"\"\n        return self._request_futures_coin_api(\"get\", \"fundingRate\", data=params)\n\n    def futures_coin_ticker(self, **params):\n        \"\"\"24 hour rolling window price change statistics.\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api/24hr-Ticker-Price-Change-Statistics\n\n        \"\"\"\n        return self._request_futures_coin_api(\"get\", \"ticker/24hr\", data=params)\n\n    def futures_coin_symbol_ticker(self, **params):\n        \"\"\"Latest price for a symbol or symbols.\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api/Symbol-Price-Ticker\n\n        \"\"\"\n        return self._request_futures_coin_api(\"get\", \"ticker/price\", data=params)\n\n    def futures_coin_orderbook_ticker(self, **params):\n        \"\"\"Best price/qty on the order book for a symbol or symbols.\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api/Symbol-Order-Book-Ticker\n\n        \"\"\"\n        return self._request_futures_coin_api(\"get\", \"ticker/bookTicker\", data=params)\n\n    def futures_coin_top_longshort_position_ratio(self, **params):\n        \"\"\"Get present long to short ratio for top positions of a specific symbol.\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api/Top-Trader-Long-Short-Ratio\n        \"\"\"\n        return self._request_futures_coin_data_api(\"get\", \"topLongShortPositionRatio\", data=params)\n\n    def futures_coin_top_longshort_account_ratio(self, **params):\n        \"\"\"Get present long to short ratio for top positions of a specific symbol.\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api/Top-Long-Short-Account-Ratio\n        \"\"\"\n        return self._request_futures_coin_data_api(\"get\", \"topLongShortAccountRatio\", data=params)\n\n    def futures_coin_global_longshort_ratio(self, **params):\n        \"\"\"Get present long to short ratio for top positions of a specific symbol.\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api/Long-Short-Ratio\n        \"\"\"\n        return self._request_futures_coin_data_api(\"get\", \"globalLongShortAccountRatio\", data=params)\n\n    def futures_coin_taker_buy_sell_volume(self, **params):\n        \"\"\"Get present long to short ratio for top positions of a specific symbol.\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api/Taker-Buy-Sell-Volume\n        \"\"\"\n        return self._request_futures_coin_data_api(\"get\", \"takerBuySellVol\", data=params)\n\n    def futures_coin_basis(self, **params):\n        \"\"\"Get future basis of a specific symbol\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api/Basis\n        \"\"\"\n        return self._request_futures_coin_data_api(\"get\", \"basis\", data=params)\n\n    def futures_coin_index_price_constituents(self, **params):\n        \"\"\"Get index price constituents\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api/Index-Constituents\n\n        \"\"\"\n        return self._request_futures_coin_api(\"get\", \"constituents\", data=params)\n\n    def futures_coin_liquidation_orders(self, **params):\n        \"\"\"Get all liquidation orders\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/rest-api/Users-Force-Orders\n\n        \"\"\"\n        return self._request_futures_coin_api(\n            \"get\", \"forceOrders\", signed=True, data=params\n        )\n\n    def futures_coin_open_interest(self, **params):\n        \"\"\"Get present open interest of a specific symbol.\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api/Open-Interest\n\n        \"\"\"\n        return self._request_futures_coin_api(\"get\", \"openInterest\", data=params)\n\n    def futures_coin_open_interest_hist(self, **params):\n        \"\"\"Get open interest statistics of a specific symbol.\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api/Open-Interest-Statistics\n\n        \"\"\"\n        return self._request_futures_coin_data_api(\n            \"get\", \"openInterestHist\", data=params\n        )\n\n    def futures_coin_leverage_bracket(self, **params):\n        \"\"\"Notional and Leverage Brackets\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/account/rest-api/Notional-Bracket-for-Symbol\n\n        \"\"\"\n        return self._request_futures_coin_api(\n            \"get\", \"leverageBracket\", version=2, signed=True, data=params\n        )\n\n    def new_transfer_history(self, **params):\n        \"\"\"Get future account transaction history list\n\n        https://developers.binance.com/docs/wallet/asset/query-user-universal-transfer\n\n        \"\"\"\n        return self._request_margin_api(\"get\", \"asset/transfer\", True, data=params)\n\n    def funding_wallet(self, **params):\n        \"\"\" Query Funding Wallet\n\n        https://developers.binance.com/docs/wallet/asset/funding-wallet\n\n        \"\"\"\n        return self._request_margin_api(\n            \"post\", \"asset/get-funding-asset\", True, data=params\n        )\n\n    def get_user_asset(self, **params):\n        \"\"\" Get user assets, just for positive data\n\n        https://developers.binance.com/docs/wallet/asset/user-assets\n\n        \"\"\"\n        return self._request_margin_api(\n            \"post\", \"asset/getUserAsset\", True, data=params, version=3\n        )\n\n    def universal_transfer(self, **params):\n        \"\"\"Unviversal transfer api accross different binance account types\n\n        https://developers.binance.com/docs/wallet/asset/user-universal-transfer\n        \"\"\"\n        return self._request_margin_api(\n            \"post\", \"asset/transfer\", signed=True, data=params\n        )\n\n    def futures_coin_create_order(self, **params):\n        \"\"\"Send in a new order.\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/rest-api\n\n        \"\"\"\n        if \"newClientOrderId\" not in params:\n            params[\"newClientOrderId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n        return self._request_futures_coin_api(\"post\", \"order\", True, data=params)\n\n    def futures_coin_place_batch_order(self, **params):\n        \"\"\"Send in new orders.\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/rest-api/Place-Multiple-Orders\n\n        To avoid modifying the existing signature generation and parameter order logic,\n        the url encoding is done on the special query param, batchOrders, in the early stage.\n\n        \"\"\"\n        for order in params[\"batchOrders\"]:\n            if \"newClientOrderId\" not in order:\n                order[\"newClientOrderId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n        query_string = urlencode(params)\n        query_string = query_string.replace(\"%27\", \"%22\")\n        params[\"batchOrders\"] = query_string[12:]\n\n        return self._request_futures_coin_api(\"post\", \"batchOrders\", True, data=params)\n\n    def futures_coin_modify_order(self, **params):\n        \"\"\"Modify an existing order. Currently only LIMIT order modification is supported.\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/rest-api/Modify-Order\n\n        \"\"\"\n        return self._request_futures_coin_api(\"put\", \"order\", True, data=params)\n\n    def futures_coin_get_order(self, **params):\n        \"\"\"Check an order's status.\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/rest-api/Query-Order\n\n        \"\"\"\n        return self._request_futures_coin_api(\"get\", \"order\", True, data=params)\n\n    def futures_coin_get_open_orders(self, **params):\n        \"\"\"Get all open orders on a symbol.\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/rest-api/Current-All-Open-Orders\n\n        \"\"\"\n        return self._request_futures_coin_api(\"get\", \"openOrders\", True, data=params)\n\n    def futures_coin_get_all_orders(self, **params):\n        \"\"\"Get all futures account orders; active, canceled, or filled.\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/rest-api/All-Orders\n\n        \"\"\"\n        return self._request_futures_coin_api(\n            \"get\", \"allOrders\", signed=True, data=params\n        )\n\n    def futures_coin_cancel_order(self, **params):\n        \"\"\"Cancel an active futures order.\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/rest-api/Cancel-Order\n\n        \"\"\"\n        return self._request_futures_coin_api(\n            \"delete\", \"order\", signed=True, data=params\n        )\n\n    def futures_coin_cancel_all_open_orders(self, **params):\n        \"\"\"Cancel all open futures orders\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/rest-api/Cancel-All-Open-Orders\n\n        \"\"\"\n        return self._request_futures_coin_api(\n            \"delete\", \"allOpenOrders\", signed=True, force_params=True, data=params\n        )\n\n    def futures_coin_cancel_orders(self, **params):\n        \"\"\"Cancel multiple futures orders\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/rest-api/Cancel-Multiple-Orders\n\n        \"\"\"\n        if params.get(\"orderidlist\"):\n            params[\"orderidlist\"] = quote(\n                convert_list_to_json_array(params[\"orderidlist\"])\n            )\n        if params.get(\"origclientOrderidlist\"):\n            params[\"origclientorderidlist\"] = quote(\n                convert_list_to_json_array(params[\"origclientorderidlist\"])\n            )\n        return self._request_futures_coin_api(\n            \"delete\", \"batchOrders\", True, data=params\n        )\n\n    def futures_coin_countdown_cancel_all(self, **params):\n        \"\"\"Cancel all open orders of the specified symbol at the end of the specified countdown.\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/rest-api/Auto-Cancel-All-Open-Orders\n\n        :param symbol: required\n        :type symbol: str\n        :param countdownTime: required\n        :type countdownTime: int\n        :param recvWindow: optional - the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n        {\n            \"symbol\": \"BTCUSDT\",\n            \"countdownTime\": \"100000\"\n        }\n\n        \"\"\"\n        return self._request_futures_coin_api(\n            \"post\", \"countdownCancelAll\", True, data=params\n        )\n\n    def futures_coin_get_open_order(self, **params):\n        \"\"\"Get current open order.\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/rest-api/Query-Current-Open-Order\n\n        \"\"\"\n        return self._request_futures_coin_api(\n            \"get\", \"openOrder\", signed=True, data=params\n        )\n\n    def futures_coin_account_balance(self, **params):\n        \"\"\"Get futures account balance\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/account/rest-api/Futures-Account-Balance\n\n        \"\"\"\n        return self._request_futures_coin_api(\n            \"get\", \"balance\", signed=True, data=params\n        )\n\n    def futures_coin_account(self, **params):\n        \"\"\"Get current account information.\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/account/rest-api/Account-Information\n\n        \"\"\"\n        return self._request_futures_coin_api(\n            \"get\", \"account\", signed=True, data=params\n        )\n\n    def futures_coin_change_leverage(self, **params):\n        \"\"\"Change user's initial leverage of specific symbol market\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/rest-api/Change-Initial-Leverage\n\n        \"\"\"\n        return self._request_futures_coin_api(\n            \"post\", \"leverage\", signed=True, data=params\n        )\n\n    def futures_coin_change_margin_type(self, **params):\n        \"\"\"Change the margin type for a symbol\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/rest-api/Change-Margin-Type\n\n        \"\"\"\n        return self._request_futures_coin_api(\n            \"post\", \"marginType\", signed=True, data=params\n        )\n\n    def futures_coin_change_position_margin(self, **params):\n        \"\"\"Change the position margin for a symbol\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/rest-api/Modify-Isolated-Position-Margin\n\n        \"\"\"\n        return self._request_futures_coin_api(\n            \"post\", \"positionMargin\", True, data=params\n        )\n\n    def futures_coin_position_margin_history(self, **params):\n        \"\"\"Get position margin change history\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/rest-api/Get-Position-Margin-Change-History\n\n        \"\"\"\n        return self._request_futures_coin_api(\n            \"get\", \"positionMargin/history\", True, data=params\n        )\n\n    def futures_coin_position_information(self, **params):\n        \"\"\"Get position information\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/rest-api/Position-Information\n\n        \"\"\"\n        return self._request_futures_coin_api(\"get\", \"positionRisk\", True, data=params)\n\n    def futures_coin_account_trades(self, **params):\n        \"\"\"Get trades for the authenticated account and symbol.\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/rest-api/Account-Trade-List\n\n        \"\"\"\n        return self._request_futures_coin_api(\"get\", \"userTrades\", True, data=params)\n\n    def futures_coin_income_history(self, **params):\n        \"\"\"Get income history for authenticated account\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/account/rest-api/Get-Income-History\n\n        \"\"\"\n        return self._request_futures_coin_api(\"get\", \"income\", True, data=params)\n\n    def futures_coin_change_position_mode(self, **params):\n        \"\"\"Change user's position mode (Hedge Mode or One-way Mode ) on EVERY symbol\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/rest-api/Change-Position-Mode\n\n        \"\"\"\n        return self._request_futures_coin_api(\n            \"post\", \"positionSide/dual\", True, data=params\n        )\n\n    def futures_coin_get_position_mode(self, **params):\n        \"\"\"Get user's position mode (Hedge Mode or One-way Mode ) on EVERY symbol\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/account/rest-api/Get-Current-Position-Mode\n\n        \"\"\"\n        return self._request_futures_coin_api(\n            \"get\", \"positionSide/dual\", True, data=params\n        )\n\n    def futures_coin_stream_get_listen_key(self):\n        res = self._request_futures_coin_api(\"post\", \"listenKey\", signed=False, data={})\n        return res[\"listenKey\"]\n\n    def futures_coin_stream_keepalive(self, listenKey):\n        params = {\"listenKey\": listenKey}\n        return self._request_futures_coin_api(\n            \"put\", \"listenKey\", signed=False, data=params\n        )\n\n    def futures_coin_stream_close(self, listenKey):\n        params = {\"listenKey\": listenKey}\n        return self._request_futures_coin_api(\n            \"delete\", \"listenKey\", signed=False, data=params\n        )\n\n    def futures_coin_account_order_history_download(self, **params):\n        \"\"\"Get Download Id For Futures Order History\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/account/rest-api/Get-Download-Id-For-Futures-Order-History\n\n        :param startTime: required - Start timestamp in ms\n        :type startTime: int\n        :param endTime: required - End timestamp in ms\n        :type endTime: int\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"avgCostTimestampOfLast30d\": 7241837,  # Average time taken for data download in the past 30 days\n                \"downloadId\": \"546975389218332672\"\n            }\n\n        Note:\n            - Request Limitation is 10 times per month, shared by front end download page and rest api\n            - The time between startTime and endTime can not be longer than 1 year\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_futures_coin_api(\n            \"get\", \"order/asyn\", signed=True, data=params\n        )\n\n    def futures_coin_accout_order_history_download_link(self, **params):\n        \"\"\"Get futures order history download link by Id\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/account/rest-api/Get-Futures-Order-History-Download-Link-by-Id\n\n        :param downloadId: required - Download ID obtained from futures_coin_download_id\n        :type downloadId: str\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"downloadId\": \"545923594199212032\",\n                \"status\": \"completed\",     # Enum：completed，processing\n                \"url\": \"www.binance.com\",  # The link is mapped to download id\n                \"notified\": true,          # ignore\n                \"expirationTimestamp\": 1645009771000,  # The link would expire after this timestamp\n                \"isExpired\": null\n            }\n\n            # OR (Response when server is processing)\n            {\n                \"downloadId\": \"545923594199212032\",\n                \"status\": \"processing\",\n                \"url\": \"\",\n                \"notified\": false,\n                \"expirationTimestamp\": -1,\n                \"isExpired\": null\n            }\n\n        Note:\n            - Download link expiration: 24h\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_futures_coin_api(\"get\", \"order/asyn/id\", True, data=params)\n\n    def futures_coin_account_trade_history_download(self, **params):\n        \"\"\"Get Download Id For Futures Trade History (USER_DATA)\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/account/rest-api/Get-Download-Id-For-Futures-Trade-History\n\n        :param startTime: required - Start timestamp in ms\n        :type startTime: int\n        :param endTime: required - End timestamp in ms\n        :type endTime: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"avgCostTimestampOfLast30d\": 7241837,  # Average time taken for data download in the past 30 days\n                \"downloadId\": \"546975389218332672\"\n            }\n\n        Note:\n            - Request Limitation is 5 times per month, shared by front end download page and rest api\n            - The time between startTime and endTime can not be longer than 1 year\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_futures_coin_api(\"get\", \"trade/asyn\", True, data=params)\n\n    def futures_coin_account_trade_history_download_link(self, **params):\n        \"\"\"Get futures trade download link by Id\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/account/rest-api/Get-Futures-Trade-Download-Link-by-Id\n\n        :param downloadId: required - Download ID obtained from futures_coin_trade_download_id\n        :type downloadId: str\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"downloadId\": \"545923594199212032\",\n                \"status\": \"completed\",     # Enum：completed，processing\n                \"url\": \"www.binance.com\",  # The link is mapped to download id\n                \"notified\": true,          # ignore\n                \"expirationTimestamp\": 1645009771000,  # The link would expire after this timestamp\n                \"isExpired\": null\n            }\n\n            # OR (Response when server is processing)\n            {\n                \"downloadId\": \"545923594199212032\",\n                \"status\": \"processing\",\n                \"url\": \"\",\n                \"notified\": false,\n                \"expirationTimestamp\": -1,\n                \"isExpired\": null\n            }\n\n        Note:\n            - Download link expiration: 24h\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_futures_coin_api(\"get\", \"trade/asyn/id\", True, data=params)\n\n    def get_all_coins_info(self, **params):\n        \"\"\"Get information of coins (available for deposit and withdraw) for user.\n\n        https://developers.binance.com/docs/wallet/capital\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"coin\": \"BTC\",\n                \"depositAllEnable\": true,\n                \"withdrawAllEnable\": true,\n                \"name\": \"Bitcoin\",\n                \"free\": \"0\",\n                \"locked\": \"0\",\n                \"freeze\": \"0\",\n                \"withdrawing\": \"0\",\n                \"ipoing\": \"0\",\n                \"ipoable\": \"0\",\n                \"storage\": \"0\",\n                \"isLegalMoney\": false,\n                \"trading\": true,\n                \"networkList\": [\n                    {\n                        \"network\": \"BNB\",\n                        \"coin\": \"BTC\",\n                        \"withdrawIntegerMultiple\": \"0.00000001\",\n                        \"isDefault\": false,\n                        \"depositEnable\": true,\n                        \"withdrawEnable\": true,\n                        \"depositDesc\": \"\",\n                        \"withdrawDesc\": \"\",\n                        \"specialTips\": \"Both a MEMO and an Address are required to successfully deposit your BEP2-BTCB tokens to Binance.\",\n                        \"name\": \"BEP2\",\n                        \"resetAddressStatus\": false,\n                        \"addressRegex\": \"^(bnb1)[0-9a-z]{38}$\",\n                        \"memoRegex\": \"^[0-9A-Za-z-_]{1,120}$\",\n                        \"withdrawFee\": \"0.0000026\",\n                        \"withdrawMin\": \"0.0000052\",\n                        \"withdrawMax\": \"0\",\n                        \"minConfirm\": 1,\n                        \"unLockConfirm\": 0\n                    },\n                    {\n                        \"network\": \"BTC\",\n                        \"coin\": \"BTC\",\n                        \"withdrawIntegerMultiple\": \"0.00000001\",\n                        \"isDefault\": true,\n                        \"depositEnable\": true,\n                        \"withdrawEnable\": true,\n                        \"depositDesc\": \"\",\n                        \"withdrawDesc\": \"\",\n                        \"specialTips\": \"\",\n                        \"name\": \"BTC\",\n                        \"resetAddressStatus\": false,\n                        \"addressRegex\": \"^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$|^(bc1)[0-9A-Za-z]{39,59}$\",\n                        \"memoRegex\": \"\",\n                        \"withdrawFee\": \"0.0005\",\n                        \"withdrawMin\": \"0.001\",\n                        \"withdrawMax\": \"0\",\n                        \"minConfirm\": 1,\n                        \"unLockConfirm\": 2\n                    }\n                ]\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"capital/config/getall\", True, data=params\n        )\n\n    def get_account_snapshot(self, **params):\n        \"\"\"Get daily account snapshot of specific type.\n\n        https://developers.binance.com/docs/wallet/account/daily-account-snapshoot\n\n        :param type: required. Valid values are SPOT/MARGIN/FUTURES.\n        :type type: string\n        :param startTime: optional\n        :type startTime: int\n        :param endTime: optional\n        :type endTime: int\n        :param limit: optional\n        :type limit: int\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n               \"code\":200, // 200 for success; others are error codes\n               \"msg\":\"\", // error message\n               \"snapshotVos\":[\n                  {\n                     \"data\":{\n                        \"balances\":[\n                           {\n                              \"asset\":\"BTC\",\n                              \"free\":\"0.09905021\",\n                              \"locked\":\"0.00000000\"\n                           },\n                           {\n                              \"asset\":\"USDT\",\n                              \"free\":\"1.89109409\",\n                              \"locked\":\"0.00000000\"\n                           }\n                        ],\n                        \"totalAssetOfBtc\":\"0.09942700\"\n                     },\n                     \"type\":\"spot\",\n                     \"updateTime\":1576281599000\n                  }\n               ]\n            }\n\n        OR\n\n        .. code-block:: python\n\n            {\n               \"code\":200, // 200 for success; others are error codes\n               \"msg\":\"\", // error message\n               \"snapshotVos\":[\n                  {\n                     \"data\":{\n                        \"marginLevel\":\"2748.02909813\",\n                        \"totalAssetOfBtc\":\"0.00274803\",\n                        \"totalLiabilityOfBtc\":\"0.00000100\",\n                        \"totalNetAssetOfBtc\":\"0.00274750\",\n                        \"userAssets\":[\n                           {\n                              \"asset\":\"XRP\",\n                              \"borrowed\":\"0.00000000\",\n                              \"free\":\"1.00000000\",\n                              \"interest\":\"0.00000000\",\n                              \"locked\":\"0.00000000\",\n                              \"netAsset\":\"1.00000000\"\n                           }\n                        ]\n                     },\n                     \"type\":\"margin\",\n                     \"updateTime\":1576281599000\n                  }\n               ]\n            }\n\n        OR\n\n        .. code-block:: python\n\n            {\n               \"code\":200, // 200 for success; others are error codes\n               \"msg\":\"\", // error message\n               \"snapshotVos\":[\n                  {\n                     \"data\":{\n                        \"assets\":[\n                           {\n                              \"asset\":\"USDT\",\n                              \"marginBalance\":\"118.99782335\",\n                              \"walletBalance\":\"120.23811389\"\n                           }\n                        ],\n                        \"position\":[\n                           {\n                              \"entryPrice\":\"7130.41000000\",\n                              \"markPrice\":\"7257.66239673\",\n                              \"positionAmt\":\"0.01000000\",\n                              \"symbol\":\"BTCUSDT\",\n                              \"unRealizedProfit\":\"1.24029054\"\n                           }\n                        ]\n                     },\n                     \"type\":\"futures\",\n                     \"updateTime\":1576281599000\n                  }\n               ]\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\"get\", \"accountSnapshot\", True, data=params)\n\n    def disable_fast_withdraw_switch(self, **params):\n        \"\"\"Disable Fast Withdraw Switch\n\n        https://binance-docs.github.io/apidocs/spot/en/#disable-fast-withdraw-switch-user_data\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"post\", \"disableFastWithdrawSwitch\", True, data=params\n        )\n\n    def enable_fast_withdraw_switch(self, **params):\n        \"\"\"Enable Fast Withdraw Switch\n\n        https://binance-docs.github.io/apidocs/spot/en/#enable-fast-withdraw-switch-user_data\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        \"\"\"\n        return self._request_margin_api(\n            \"post\", \"enableFastWithdrawSwitch\", True, data=params\n        )\n\n    \"\"\"\n    ====================================================================================================================\n    Options API\n    ====================================================================================================================\n    \"\"\"\n    # Quoting interface endpoints\n\n    def options_ping(self):\n        \"\"\"Test connectivity\n\n        https://developers.binance.com/docs/derivatives/option/market-data/Test-Connectivity\n\n        \"\"\"\n        return self._request_options_api(\"get\", \"ping\")\n\n    def options_time(self):\n        \"\"\"Get server time\n\n        https://developers.binance.com/docs/derivatives/option/market-data\n\n        \"\"\"\n        return self._request_options_api(\"get\", \"time\")\n\n    def options_info(self):\n        \"\"\"Get current trading pair info\n\n        https://binance-docs.github.io/apidocs/voptions/en/#get-current-trading-pair-info\n\n        \"\"\"\n        return self._request_options_api(\"get\", \"optionInfo\")\n\n    def options_exchange_info(self):\n        \"\"\"Get current limit info and trading pair info\n\n        https://developers.binance.com/docs/derivatives/option/market-data/Exchange-Information\n\n        \"\"\"\n        return self._request_options_api(\"get\", \"exchangeInfo\")\n\n    def options_index_price(self, **params):\n        \"\"\"Get the spot index price\n\n        https://developers.binance.com/docs/derivatives/option/market-data/Symbol-Price-Ticker\n\n        :param underlying: required - Spot pair（Option contract underlying asset）- BTCUSDT\n        :type underlying: str\n\n        \"\"\"\n        return self._request_options_api(\"get\", \"index\", data=params)\n\n    def options_price(self, **params):\n        \"\"\"Get the latest price\n\n        https://developers.binance.com/docs/derivatives/option/market-data/24hr-Ticker-Price-Change-Statistics\n\n        :param symbol: optional - Option trading pair - BTC-200730-9000-C\n        :type symbol: str\n\n        \"\"\"\n        return self._request_options_api(\"get\", \"ticker\", data=params)\n\n    def options_mark_price(self, **params):\n        \"\"\"Get the latest mark price\n\n        https://developers.binance.com/docs/derivatives/option/market-data/Option-Mark-Price\n\n        :param symbol: optional - Option trading pair - BTC-200730-9000-C\n        :type symbol: str\n\n        \"\"\"\n        return self._request_options_api(\"get\", \"mark\", data=params)\n\n    def options_order_book(self, **params):\n        \"\"\"Depth information\n\n        https://developers.binance.com/docs/derivatives/option/market-data/Order-Book\n\n        :param symbol: required - Option trading pair - BTC-200730-9000-C\n        :type symbol: str\n        :param limit: optional - Default:100 Max:1000.Optional value:[10, 20, 50, 100, 500, 1000] - 100\n        :type limit: int\n\n        \"\"\"\n        return self._request_options_api(\"get\", \"depth\", data=params)\n\n    def options_klines(self, **params):\n        \"\"\"Candle data\n\n        https://developers.binance.com/docs/derivatives/option/market-data/Kline-Candlestick-Data\n\n        :param symbol: required - Option trading pair - BTC-200730-9000-C\n        :type symbol: str\n        :param interval: required - Time interval - 5m\n        :type interval: str\n        :param startTime: optional - Start Time - 1592317127349\n        :type startTime: int\n        :param endTime: optional - End Time - 1592317127349\n        :type endTime: int\n        :param limit: optional - Number of records Default:500 Max:1500 - 500\n        :type limit: int\n\n        \"\"\"\n        return self._request_options_api(\"get\", \"klines\", data=params)\n\n    def options_recent_trades(self, **params):\n        \"\"\"Recently completed Option trades\n\n        https://developers.binance.com/docs/derivatives/option/market-data/Recent-Trades-List\n\n        :param symbol: required - Option trading pair - BTC-200730-9000-C\n        :type symbol: str\n        :param limit: optional - Number of records Default:100 Max:500 - 100\n        :type limit: int\n\n        \"\"\"\n        return self._request_options_api(\"get\", \"trades\", data=params)\n\n    def options_historical_trades(self, **params):\n        \"\"\"Query trade history\n\n        https://developers.binance.com/docs/derivatives/option/market-data/Old-Trades-Lookup\n\n        :param symbol: required - Option trading pair - BTC-200730-9000-C\n        :type symbol: str\n        :param fromId: optional - The deal ID from which to return. The latest deal record is returned by default - 1592317127349\n        :type fromId: int\n        :param limit: optional - Number of records Default:100 Max:500 - 100\n        :type limit: int\n\n        \"\"\"\n        return self._request_options_api(\"get\", \"historicalTrades\", data=params)\n\n    # Account and trading interface endpoints\n\n    def options_account_info(self, **params):\n        \"\"\"Account asset info (USER_DATA)\n\n        https://developers.binance.com/docs/derivatives/option/account\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        \"\"\"\n        return self._request_options_api(\"get\", \"account\", signed=True, data=params)\n\n    def options_get_bill(self, **params):\n        \"\"\"Get account funding flows\n\n        https://developers.binance.com/docs/derivatives/option/account/Account-Funding-Flow\n\n        :param currency: required\n        :type currency: str\n        :param recordId: optional\n        :type recordId: int\n        :param startTime: optional\n        :type startTime: int\n        :param endTime: optional\n        :type endTime: int\n        :param limit: optional\n        :type limit: int\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n        \"\"\"\n        return self._request_options_api(\"get\", \"bill\", signed=True, data=params)\n\n    def options_funds_transfer(self, **params):\n        \"\"\"Funds transfer (USER_DATA)\n\n        https://binance-docs.github.io/apidocs/voptions/en/#funds-transfer-user_data\n\n        :param currency: required - Asset type - USDT\n        :type currency: str\n        :param type: required - IN: Transfer from spot account to option account OUT: Transfer from option account to spot account - IN\n        :type type: str (ENUM)\n        :param amount: required - Amount - 10000\n        :type amount: float\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        \"\"\"\n        return self._request_options_api(\"post\", \"transfer\", signed=True, data=params)\n\n    def options_positions(self, **params):\n        \"\"\"Option holdings info (USER_DATA)\n\n        https://developers.binance.com/docs/derivatives/option/trade/Option-Position-Information\n\n        :param symbol: optional - Option trading pair - BTC-200730-9000-C\n        :type symbol: str\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        \"\"\"\n        return self._request_options_api(\"get\", \"position\", signed=True, data=params)\n\n    def options_exercise_record(self, **params):\n        \"\"\"\n        Get account exercise records.\n\n        https://developers.binance.com/docs/derivatives/option/trade/User-Exercise-Record\n\n        :param symbol: optional\n        :type symbol: str\n        :param startTime: optional\n        :type startTime: int\n        :param endTime: optional\n        :type endTime: int\n        :param limit: optional\n        :type limit: int\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n        \"\"\"\n        return self._request_options_api(\"get\", \"exerciseRecord\", signed=True, data=params)\n\n    def options_bill(self, **params):\n        \"\"\"Account funding flow (USER_DATA)\n\n        https://binance-docs.github.io/apidocs/voptions/en/#account-funding-flow-user_data\n\n        :param currency: required - Asset type - USDT\n        :type currency: str\n        :param recordId: optional - Return the recordId and subsequent data, the latest data is returned by default - 100000\n        :type recordId: int\n        :param startTime: optional - Start Time - 1593511200000\n        :type startTime: int\n        :param endTime: optional - End Time - 1593511200000\n        :type endTime: int\n        :param limit: optional - Number of result sets returned Default:100 Max:1000 - 100\n        :type limit: int\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        \"\"\"\n        return self._request_options_api(\"post\", \"bill\", signed=True, data=params)\n\n    def options_place_order(self, **params):\n        \"\"\"Option order (TRADE)\n\n        https://developers.binance.com/docs/derivatives/option/trade\n\n        :param symbol: required - Option trading pair - BTC-200730-9000-C\n        :type symbol: str\n        :param side: required - Buy/sell direction: SELL, BUY - BUY\n        :type side: str (ENUM)\n        :param type: required - Order Type: LIMIT, MARKET - LIMIT\n        :type type: str (ENUM)\n        :param quantity: required - Order Quantity - 3\n        :type quantity: float\n        :param price: optional - Order Price - 1000\n        :type price: float\n        :param timeInForce: optional - Time in force method（Default GTC) - GTC\n        :type timeInForce: str (ENUM)\n        :param reduceOnly: optional - Reduce Only (Default false) - false\n        :type reduceOnly: bool\n        :param postOnly: optional - Post Only (Default false) - false\n        :type postOnly: bool\n        :param newOrderRespType: optional - \"ACK\", \"RESULT\", Default \"ACK\" - ACK\n        :type newOrderRespType: str (ENUM)\n        :param clientOrderId: optional - User-defined order ID cannot be repeated in pending orders - 10000\n        :type clientOrderId: str\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        \"\"\"\n        if \"clientOrderId\" not in params:\n            params[\"clientOrderId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n        return self._request_options_api(\"post\", \"order\", signed=True, data=params)\n\n    def options_place_batch_order(self, **params):\n        \"\"\"Place Multiple Option orders (TRADE)\n\n        https://developers.binance.com/docs/derivatives/option/trade/Place-Multiple-Orders\n\n        :param orders: required - order list. Max 5 orders - [{\"symbol\":\"BTC-210115-35000-C\",\"price\":\"100\",\"quantity\":\"0.0001\",\"side\":\"BUY\",\"type\":\"LIMIT\"}]\n        :type orders: list\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        \"\"\"\n        for order in params[\"batchOrders\"]:\n            if \"newClientOrderId\" not in order:\n                order[\"newClientOrderId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n        return self._request_options_api(\n            \"post\", \"batchOrders\", signed=True, data=params\n        )\n\n    def options_cancel_order(self, **params):\n        \"\"\"Cancel Option order (TRADE)\n\n        https://developers.binance.com/docs/derivatives/option/trade/Cancel-Option-Order\n\n        :param symbol: required - Option trading pair - BTC-200730-9000-C\n        :type symbol: str\n        :param orderId: optional - Order ID - 4611875134427365377\n        :type orderId: str\n        :param clientOrderId: optional - User-defined order ID - 10000\n        :type clientOrderId: str\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        \"\"\"\n        return self._request_options_api(\"delete\", \"order\", signed=True, data=params)\n\n    def options_cancel_batch_order(self, **params):\n        \"\"\"Cancel Multiple Option orders (TRADE)\n\n        https://developers.binance.com/docs/derivatives/option/trade/Cancel-Multiple-Option-Orders\n\n        :param symbol: required - Option trading pair - BTC-200730-9000-C\n        :type symbol: str\n        :param orderIds: optional - Order ID - [4611875134427365377,4611875134427365378]\n        :type orderId: list\n        :param clientOrderIds: optional - User-defined order ID - [\"my_id_1\",\"my_id_2\"]\n        :type clientOrderIds: list\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        \"\"\"\n        return self._request_options_api(\n            \"delete\", \"batchOrders\", signed=True, data=params\n        )\n\n    def options_cancel_all_orders(self, **params):\n        \"\"\"Cancel all Option orders (TRADE)\n\n        https://developers.binance.com/docs/derivatives/option/trade/Cancel-all-Option-orders-on-specific-symbol\n\n        :param symbol: required - Option trading pair - BTC-200730-9000-C\n        :type symbol: str\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        \"\"\"\n        return self._request_options_api(\n            \"delete\", \"allOpenOrders\", signed=True, data=params\n        )\n\n    def options_query_order(self, **params):\n        \"\"\"Query Option order (TRADE)\n\n        https://developers.binance.com/docs/derivatives/option/trade/Query-Single-Order\n\n        :param symbol: required - Option trading pair - BTC-200730-9000-C\n        :type symbol: str\n        :param orderId: optional - Order ID - 4611875134427365377\n        :type orderId: str\n        :param clientOrderId: optional - User-defined order ID - 10000\n        :type clientOrderId: str\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        \"\"\"\n        return self._request_options_api(\"get\", \"order\", signed=True, data=params)\n\n    def options_query_pending_orders(self, **params):\n        \"\"\"Query current pending Option orders (TRADE)\n\n        https://developers.binance.com/docs/derivatives/option/trade/Query-Current-Open-Option-Orders\n\n        :param symbol: required - Option trading pair - BTC-200730-9000-C\n        :type symbol: str\n        :param orderId: optional - Returns the orderId and subsequent orders, the most recent order is returned by default - 100000\n        :type orderId: str\n        :param startTime: optional - Start Time - 1593511200000\n        :type startTime: int\n        :param endTime: optional - End Time - 1593511200000\n        :type endTime: int\n        :param limit: optional - Number of result sets returned Default:100 Max:1000 - 100\n        :type limit: int\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        \"\"\"\n        return self._request_options_api(\"get\", \"openOrders\", signed=True, data=params)\n\n    def options_query_order_history(self, **params):\n        \"\"\"Query Option order history (TRADE)\n\n        https://developers.binance.com/docs/derivatives/option/trade/Query-Option-Order-History\n\n        :param symbol: required - Option trading pair - BTC-200730-9000-C\n        :type symbol: str\n        :param orderId: optional - Returns the orderId and subsequent orders, the most recent order is returned by default - 100000\n        :type orderId: str\n        :param startTime: optional - Start Time - 1593511200000\n        :type startTime: int\n        :param endTime: optional - End Time - 1593511200000\n        :type endTime: int\n        :param limit: optional - Number of result sets returned Default:100 Max:1000 - 100\n        :type limit: int\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        \"\"\"\n        return self._request_options_api(\n            \"get\", \"historyOrders\", signed=True, data=params\n        )\n\n    def options_user_trades(self, **params):\n        \"\"\"Option Trade List (USER_DATA)\n\n        https://developers.binance.com/docs/derivatives/option/trade/Account-Trade-List\n\n        :param symbol: required - Option trading pair - BTC-200730-9000-C\n        :type symbol: str\n        :param fromId: optional - Trade id to fetch from. Default gets most recent trades. - 4611875134427365376\n        :type fromId: int\n        :param startTime: optional - Start Time - 1593511200000\n        :type startTime: int\n        :param endTime: optional - End Time - 1593511200000\n        :type endTime: int\n        :param limit: optional - Number of result sets returned Default:100 Max:1000 - 100\n        :type limit: int\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        \"\"\"\n        return self._request_options_api(\"get\", \"userTrades\", signed=True, data=params)\n\n    ####################################################\n    # Options - Market Maker Block Trade\n    ####################################################\n\n    def options_create_block_trade_order(self, **params):\n        \"\"\"New Block Trade Order (TRADE)\n\n        https://developers.binance.com/docs/derivatives/option/market-maker-block-trade\n\n        :param liquidity: required - Taker or Maker\n        :type liquidity: str\n        :param symbol: required - Option trading pair, e.g BTC-200730-9000-C\n        :type symbol: str\n        :param side: required - BUY or SELL\n        :type side: str\n        :param price: required - Order Price\n        :type price: float\n        :param quantity: required - Order Quantity\n        :type quantity: float\n        :param recvWindow: optional - The value cannot be greater than 60000\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n            {\n                \"blockTradeSettlementKey\": \"3668822b8-1baa-6a2f-adb8-d3de6289b361\",\n                \"expireTime\": 1730171888109,\n                \"liquidity\": \"TAKER\",\n                \"status\": \"RECEIVED\",\n                \"legs\": [\n                    {\n                        \"symbol\": \"BNB-241101-700-C\",\n                        \"side\": \"BUY\",\n                        \"quantity\": \"1.2\",\n                        \"price\": \"2.8\"\n                    }\n                ]\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n        \"\"\"\n        return self._request_options_api(\n            \"post\", \"block/order/create\", signed=True, data=params\n        )\n\n    def options_cancel_block_trade_order(self, **params):\n        \"\"\"Cancel Block Trade Order (TRADE)\n\n        https://developers.binance.com/docs/derivatives/option/market-maker-block-trade/Cancel-Block-Trade-Order\n\n        :param blockOrderMatchingKey: required - Block Order Matching Key\n        :type blockOrderMatchingKey: str\n        :param recvWindow: optional - The value cannot be greater than 60000\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n            {}\n\n        :raises: BinanceRequestException, BinanceAPIException\n        \"\"\"\n        return self._request_options_api(\n            \"delete\", \"block/order/create\", signed=True, data=params\n        )\n\n    def options_extend_block_trade_order(self, **params):\n        \"\"\"Extend Block Trade Order (TRADE)\n\n        Extends a block trade expire time by 30 mins from the current time.\n\n        https://developers.binance.com/docs/derivatives/option/market-maker-block-trade/Extend-Block-Trade-Order\n\n        :param blockOrderMatchingKey: required - Block Order Matching Key\n        :type blockOrderMatchingKey: str\n        :param recvWindow: optional - The value cannot be greater than 60000\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n            {\n                \"blockTradeSettlementKey\": \"3668822b8-1baa-6a2f-adb8-d3de6289b361\",\n                \"expireTime\": 1730172007000,\n                \"liquidity\": \"TAKER\",\n                \"status\": \"RECEIVED\",\n                \"createTime\": 1730170088111,\n                \"legs\": [\n                    {\n                        \"symbol\": \"BNB-241101-700-C\",\n                        \"side\": \"BUY\",\n                        \"quantity\": \"1.2\",\n                        \"price\": \"2.8\"\n                    }\n                ]\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n        \"\"\"\n        return self._request_options_api(\n            \"put\", \"block/order/create\", signed=True, data=params\n        )\n\n    def options_get_block_trade_orders(self, **params):\n        \"\"\"Query Block Trade Order (TRADE)\n\n        Check block trade order status.\n\n        https://developers.binance.com/docs/derivatives/option/market-maker-block-trade/Query-Block-Trade-Order\n\n        :param blockOrderMatchingKey: optional - Returns specific block trade for this key\n        :type blockOrderMatchingKey: str\n        :param endTime: optional\n        :type endTime: int\n        :param startTime: optional\n        :type startTime: int\n        :param underlying: optional\n        :type underlying: str\n        :param recvWindow: optional - The value cannot be greater than 60000\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n            [\n                {\n                    \"blockTradeSettlementKey\": \"7d046e6e-a429-4335-ab9d-6a681febcde5\",\n                    \"expireTime\": 1730172115801,\n                    \"liquidity\": \"TAKER\",\n                    \"status\": \"RECEIVED\",\n                    \"createTime\": 1730170315803,\n                    \"legs\": [\n                        {\n                            \"symbol\": \"BNB-241101-700-C\",\n                            \"side\": \"BUY\",\n                            \"quantity\": \"1.2\",\n                            \"price\": \"2.8\"\n                        }\n                    ]\n                }\n            ]\n\n        :raises: BinanceRequestException, BinanceAPIException\n        \"\"\"\n        return self._request_options_api(\n            \"get\", \"block/order/orders\", signed=True, data=params\n        )\n\n    def options_accept_block_trade_order(self, **params):\n        \"\"\"Accept Block Trade Order (TRADE)\n\n        Accept a block trade order.\n\n        https://developers.binance.com/docs/derivatives/option/market-maker-block-trade/Accept-Block-Trade-Order\n\n        :param blockOrderMatchingKey: required - Block Order Matching Key\n        :type blockOrderMatchingKey: str\n        :param recvWindow: optional - The value cannot be greater than 60000\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n            {\n                \"blockTradeSettlementKey\": \"7d046e6e-a429-4335-ab9d-6a681febcde5\",\n                \"expireTime\": 1730172115801,\n                \"liquidity\": \"MAKER\",\n                \"status\": \"ACCEPTED\",\n                \"createTime\": 1730170315803,\n                \"legs\": [\n                    {\n                        \"symbol\": \"BNB-241101-700-C\",\n                        \"side\": \"SELL\",\n                        \"quantity\": \"1.2\",\n                        \"price\": \"2.8\"\n                    }\n                ]\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n        \"\"\"\n        return self._request_options_api(\n            \"post\", \"block/order/execute\", signed=True, data=params\n        )\n\n    def options_get_block_trade_order(self, **params):\n        \"\"\"Query Block Trade Details (USER_DATA)\n\n        Query block trade details; returns block trade details from counterparty's perspective.\n\n        https://developers.binance.com/docs/derivatives/option/market-maker-block-trade/Query-Block-Trade-Detail\n\n        :param blockOrderMatchingKey: required - Block Order Matching Key\n        :type blockOrderMatchingKey: str\n        :param recvWindow: optional - The value cannot be greater than 60000\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n            {\n                \"blockTradeSettlementKey\": \"12b96c28-ba05-8906-c89t-703215cfb2e6\",\n                \"expireTime\": 1730171860460,\n                \"liquidity\": \"MAKER\",\n                \"status\": \"RECEIVED\",\n                \"createTime\": 1730170060462,\n                \"legs\": [\n                    {\n                        \"symbol\": \"BNB-241101-700-C\",\n                        \"side\": \"SELL\",\n                        \"quantity\": \"1.66\",\n                        \"price\": \"20\"\n                    }\n                ]\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n        \"\"\"\n        return self._request_options_api(\n            \"get\", \"block/order/execute\", signed=True, data=params\n        )\n\n    def options_account_get_block_trades(self, **params):\n        \"\"\"Account Block Trade List (USER_DATA)\n\n        Gets block trades for a specific account.\n\n        https://developers.binance.com/docs/derivatives/option/market-maker-block-trade/Account-Block-Trade-List\n\n        :param endTime: optional\n        :type endTime: int\n        :param startTime: optional\n        :type startTime: int\n        :param underlying: optional\n        :type underlying: str\n        :param recvWindow: optional - The value cannot be greater than 60000\n        :type recvWindow: int\n\n        :returns: API response\n\n        .. code-block:: python\n            [\n                {\n                    \"parentOrderId\": \"4675011431944499201\",\n                    \"crossType\": \"USER_BLOCK\",\n                    \"legs\": [\n                        {\n                            \"createTime\": 1730170445600,\n                            \"updateTime\": 1730170445600,\n                            \"symbol\": \"BNB-241101-700-C\",\n                            \"orderId\": \"4675011431944499203\",\n                            \"orderPrice\": 2.8,\n                            \"orderQuantity\": 1.2,\n                            \"orderStatus\": \"FILLED\",\n                            \"executedQty\": 1.2,\n                            \"executedAmount\": 3.36,\n                            \"fee\": 0.336,\n                            \"orderType\": \"PREV_QUOTED\",\n                            \"orderSide\": \"BUY\",\n                            \"id\": \"1125899906900937837\",\n                            \"tradeId\": 1,\n                            \"tradePrice\": 2.8,\n                            \"tradeQty\": 1.2,\n                            \"tradeTime\": 1730170445600,\n                            \"liquidity\": \"TAKER\",\n                            \"commission\": 0.336\n                        }\n                    ],\n                    \"blockTradeSettlementKey\": \"7d085e6e-a229-2335-ab9d-6a581febcd25\"\n                }\n            ]\n\n        :raises: BinanceRequestException, BinanceAPIException\n        \"\"\"\n        return self._request_options_api(\n            \"get\", \"block/user-trades\", signed=True, data=params\n        )\n\n    # Fiat Endpoints\n\n    def get_fiat_deposit_withdraw_history(self, **params):\n        \"\"\"Get Fiat Deposit/Withdraw History\n\n        https://binance-docs.github.io/apidocs/spot/en/#get-fiat-deposit-withdraw-history-user_data\n\n        :param transactionType: required - 0-deposit,1-withdraw\n        :type transactionType: str\n        :param beginTime: optional\n        :type beginTime: int\n        :param endTime: optional\n        :type endTime: int\n        :param page: optional - default 1\n        :type page: int\n        :param rows: optional - default 100, max 500\n        :type rows: int\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        \"\"\"\n        return self._request_margin_api(\"get\", \"fiat/orders\", signed=True, data=params)\n\n    def get_fiat_payments_history(self, **params):\n        \"\"\"Get Fiat Payments History\n\n        https://binance-docs.github.io/apidocs/spot/en/#get-fiat-payments-history-user_data\n\n        :param transactionType: required - 0-buy,1-sell\n        :type transactionType: str\n        :param beginTime: optional\n        :type beginTime: int\n        :param endTime: optional\n        :type endTime: int\n        :param page: optional - default 1\n        :type page: int\n        :param rows: optional - default 100, max 500\n        :type rows: int\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"fiat/payments\", signed=True, data=params\n        )\n\n    # C2C Endpoints\n\n    def get_c2c_trade_history(self, **params):\n        \"\"\"Get C2C Trade History\n\n        https://binance-docs.github.io/apidocs/spot/en/#get-c2c-trade-history-user_data\n\n        :param tradeType: required - BUY, SELL\n        :type tradeType: str\n        :param startTimestamp: optional\n        :type startTime: int\n        :param endTimestamp: optional\n        :type endTimestamp: int\n        :param page: optional - default 1\n        :type page: int\n        :param rows: optional - default 100, max 100\n        :type rows: int\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n            {\n                \"code\": \"000000\",\n                \"message\": \"success\",\n                \"data\": [\n                    {\n                        \"orderNumber\":\"20219644646554779648\",\n                        \"advNo\": \"11218246497340923904\",\n                        \"tradeType\": \"SELL\",\n                        \"asset\": \"BUSD\",\n                        \"fiat\": \"CNY\",\n                        \"fiatSymbol\": \"￥\",\n                        \"amount\": \"5000.00000000\",  // Quantity (in Crypto)\n                        \"totalPrice\": \"33400.00000000\",\n                        \"unitPrice\": \"6.68\", // Unit Price (in Fiat)\n                        \"orderStatus\": \"COMPLETED\",  // PENDING, TRADING, BUYER_PAYED, DISTRIBUTING, COMPLETED, IN_APPEAL, CANCELLED, CANCELLED_BY_SYSTEM\n                        \"createTime\": 1619361369000,\n                        \"commission\": \"0\",   // Transaction Fee (in Crypto)\n                        \"counterPartNickName\": \"ab***\",\n                        \"advertisementRole\": \"TAKER\"\n                    }\n                ],\n                \"total\": 1,\n                \"success\": true\n            }\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"c2c/orderMatch/listUserOrderHistory\", signed=True, data=params\n        )\n\n    # Pay Endpoints\n\n    def get_pay_trade_history(self, **params):\n        \"\"\"Get C2C Trade History\n\n        https://binance-docs.github.io/apidocs/spot/en/#pay-endpoints\n\n        :param startTime: optional\n        :type startTime: int\n        :param endTime: optional\n        :type endTime: int\n        :param limit: optional - default 100, max 100\n        :type limit: int\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"pay/transactions\", signed=True, data=params\n        )\n\n    # Convert Endpoints\n\n    def get_convert_trade_history(self, **params):\n        \"\"\"Get C2C Trade History\n\n        https://developers.binance.com/docs/convert/trade/Get-Convert-Trade-History\n\n        :param startTime: required - Start Time - 1593511200000\n        :type startTime: int\n        :param endTime: required - End Time - 1593511200000\n        :type endTime: int\n        :param limit: optional - default 100, max 100\n        :type limit: int\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"convert/tradeFlow\", signed=True, data=params\n        )\n\n    def convert_request_quote(self, **params):\n        \"\"\"Request a quote for the requested token pairs\n\n        https://developers.binance.com/docs/convert/trade\n\n        :param fromAsset: required - Asset to convert from - BUSD\n        :type fromAsset: str\n        :param toAsset: required - Asset to convert to - BTC\n        :type toAsset: str\n        :param fromAmount: EITHER - When specified, it is the amount you will be debited after the conversion\n        :type fromAmount: decimal\n        :param toAmount: EITHER - When specified, it is the amount you will be credited after the conversion\n        :type toAmount: decimal\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_margin_api(\n            \"post\", \"convert/getQuote\", signed=True, data=params\n        )\n\n    def convert_accept_quote(self, **params):\n        \"\"\"Accept the offered quote by quote ID.\n\n        https://developers.binance.com/docs/convert/trade/Accept-Quote\n\n        :param quoteId: required - 457235734584567\n        :type quoteId: str\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_margin_api(\n            \"post\", \"convert/acceptQuote\", signed=True, data=params\n        )\n\n    \"\"\"\n    ====================================================================================================================\n    PortfolioMargin API\n    ====================================================================================================================\n    \"\"\"\n\n    def papi_get_balance(self, **params):\n        \"\"\"Query account balance.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account\n\n        :param asset: required\n        :type asset: str\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\"get\", \"balance\", signed=True, data=params)\n\n    def papi_get_rate_limit(self, **params):\n        \"\"\"Query User Rate Limit\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account/Query-User-Rate-Limit\n\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\"get\", \"rateLimit/order\", signed=True, data=params)\n\n    def papi_stream_get_listen_key(self):\n        \"\"\"Start a new user data stream for Portfolio Margin account.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/user-data-streams/Start-User-Data-Stream\n\n        :returns: API response\n\n            {\n                \"listenKey\": \"pM_XXXXXXX\"\n            }\n\n        The stream will close after 60 minutes unless a keepalive is sent.\n        If the account has an active listenKey, that listenKey will be returned and its validity will be extended for 60 minutes.\n\n        Weight: 1\n\n        \"\"\"\n        res = self._request_papi_api(\"post\", \"listenKey\", signed=False, data={})\n        return res[\"listenKey\"]\n\n    def papi_stream_keepalive(self, listenKey):\n        \"\"\"Keepalive a user data stream to prevent a time out.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/user-data-streams/Keepalive-User-Data-Stream\n\n        :returns: API response\n\n            {}\n\n        User data streams will close after 60 minutes. It's recommended to send a ping about every 60 minutes.\n\n        Weight: 1\n\n        \"\"\"\n        params = {\"listenKey\": listenKey}\n        return self._request_papi_api(\"put\", \"listenKey\", signed=False, data=params)\n\n    def papi_stream_close(self, listenKey):\n        \"\"\"Close out a user data stream.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/user-data-streams/Close-User-Data-Stream\n\n        :returns: API response\n\n            {}\n\n        Weight: 1\n\n        \"\"\"\n        params = {\"listenKey\": listenKey}\n        return self._request_papi_api(\"delete\", \"listenKey\", signed=False, data=params)\n\n    def papi_get_account(self, **params):\n        \"\"\"Query account information.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account/Account-Information\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\"get\", \"account\", signed=True, data=params)\n\n    def papi_get_margin_max_borrowable(self, **params):\n        \"\"\"Query margin max borrow.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account/Margin-Max-Borrow\n\n        :param asset: required\n        :type asset: str\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"get\", \"margin/maxBorrowable\", signed=True, data=params\n        )\n\n    def papi_get_margin_max_withdraw(self, **params):\n        \"\"\"Query margin max borrow.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account/Query-Margin-Max-Withdraw\n\n        :param asset: required\n        :type asset: str\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"get\", \"margin/maxWithdraw\", signed=True, data=params\n        )\n\n    def papi_get_um_position_risk(self, **params):\n        \"\"\"Query margin max borrow.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account/Query-UM-Position-Information\n\n        :param symbol: required\n        :type symbol: str\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"get\", \"um/positionRisk\", signed=True, data=params\n        )\n\n    def papi_get_cm_position_risk(self, **params):\n        \"\"\"Query margin max borrow.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account/Query-CM-Position-Information\n\n        :param asset: required\n        :type asset: str\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"get\", \"cm/positionRisk\", signed=True, data=params\n        )\n\n    def papi_set_um_leverage(self, **params):\n        \"\"\"Query margin max borrow.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account/Change-UM-Initial-Leverage\n\n        :param asset: required\n        :type asset: str\n\n        :param leverage: required\n        :type leverage: int\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\"post\", \"um/leverage\", signed=True, data=params)\n\n    def papi_set_cm_leverage(self, **params):\n        \"\"\"Query margin max borrow.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account/Change-CM-Initial-Leverage\n\n        :param asset: required\n        :type asset: str\n\n        :param leverage: required\n        :type leverage: int\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\"post\", \"cm/leverage\", signed=True, data=params)\n\n    def papi_change_um_position_side_dual(self, **params):\n        \"\"\"Change user's position mode (Hedge Mode or One-way Mode ) on EVERY symbol in UM.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account/Change-UM-Position-Mode\n\n        :param dualSidePosition: required\n        :type dualSidePosition: str\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"post\", \"um/positionSide/dual\", signed=True, data=params\n        )\n\n    def papi_change_cm_position_side_dual(self, **params):\n        \"\"\"Change user's position mode (Hedge Mode or One-way Mode ) on EVERY symbol in CM.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account/Change-CM-Position-Mode\n\n        :param dualSidePosition: required\n        :type dualSidePosition: str\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"post\", \"cm/positionSide/dual\", signed=True, data=params\n        )\n\n    def papi_get_um_position_side_dual(self, **params):\n        \"\"\"Get user's position mode (Hedge Mode or One-way Mode ) on EVERY symbol in UM.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account/Get-UM-Current-Position-Mode\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"get\", \"um/positionSide/dual\", signed=True, data=params\n        )\n\n    def papi_get_cm_position_side_dual(self, **params):\n        \"\"\"Get user's position mode (Hedge Mode or One-way Mode ) on EVERY symbol in CM.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account/Get-CM-Current-Position-Mode\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"get\", \"cm/positionSide/dual\", signed=True, data=params\n        )\n\n    def papi_get_um_leverage_bracket(self, **params):\n        \"\"\"Query UM notional and leverage brackets.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account/UM-Notional-and-Leverage-Brackets\n\n        :param symbol: optional\n        :type symbol: str\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"get\", \"um/leverageBracket\", signed=True, data=params\n        )\n\n    def papi_get_cm_leverage_bracket(self, **params):\n        \"\"\"Query CM notional and leverage brackets.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account/CM-Notional-and-Leverage-Brackets\n\n        :param symbol: optional\n        :type symbol: str\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"get\", \"cm/leverageBracket\", signed=True, data=params\n        )\n\n    def papi_get_um_api_trading_status(self, **params):\n        \"\"\"Portfolio Margin UM Trading Quantitative Rules Indicators.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account/Portfolio-Margin-UM-Trading-Quantitative-Rules-Indicators\n\n        :param symbol: optional\n        :type symbol: str\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"get\", \"um/apiTradingStatus\", signed=True, data=params\n        )\n\n    def papi_get_um_comission_rate(self, **params):\n        \"\"\"Get User Commission Rate for UM.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account/Get-User-Commission-Rate-for-UM\n\n        :param symbol: required\n        :type symbol: str\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"get\", \"um/commissionRate\", signed=True, data=params\n        )\n\n    def papi_get_cm_comission_rate(self, **params):\n        \"\"\"Get User Commission Rate for CM.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account/Get-User-Commission-Rate-for-CM\n\n        :param symbol: required\n        :type symbol: str\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"get\", \"cm/commissionRate\", signed=True, data=params\n        )\n\n    def papi_get_margin_margin_loan(self, **params):\n        \"\"\"Query margin loan record.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account/Query-Margin-Loan-Record\n\n        :param asset: required\n        :type asset: str\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"get\", \"margin/marginLoan\", signed=True, data=params\n        )\n\n    def papi_get_margin_repay_loan(self, **params):\n        \"\"\"Query margin repay record.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account/Query-Margin-repay-Record\n\n        :param asset: required\n        :type asset: str\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"get\", \"margin/repayLoan\", signed=True, data=params\n        )\n\n    def papi_get_repay_futures_switch(self, **params):\n        \"\"\"Query Auto-repay-futures Status.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account/Get-Auto-repay-futures-Status\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"get\", \"repay-futures-switch\", signed=True, data=params\n        )\n\n    def papi_repay_futures_switch(self, **params):\n        \"\"\"Change Auto-repay-futures Status.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account/Change-Auto-repay-futures-Status\n\n        :param autoRepay: required\n        :type autoRepay: str\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"post\", \"repay-futures-switch\", signed=True, data=params\n        )\n\n    def papi_get_margin_interest_history(self, **params):\n        \"\"\"Get Margin Borrow/Loan Interest History.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account/Get-Margin-BorrowLoan-Interest-History\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"get\", \"margin/marginInterestHistory\", signed=True, data=params\n        )\n\n    def papi_repay_futures_negative_balance(self, **params):\n        \"\"\"Repay futures Negative Balance.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account/Repay-futures-Negative-Balance\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"post\", \"repay-futures-negative-balance\", signed=True, data=params\n        )\n\n    def papi_get_portfolio_interest_history(self, **params):\n        \"\"\"Query interest history of negative balance for portfolio margin.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account/Query-Portfolio-Margin-Negative-Balance-Interest-History\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"get\", \"portfolio/interest-history\", signed=True, data=params\n        )\n\n\n    def papi_get_portfolio_negative_balance_exchange_record(self, **params):\n        \"\"\"Query user negative balance auto exchange record.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account/Query-User-Negative-Balance-Auto-Exchange-Record\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"get\", \"portfolio/negative-balance-exchange-record\", signed=True, data=params\n        )\n\n    def papi_fund_auto_collection(self, **params):\n        \"\"\"Fund collection for Portfolio Margin.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account/Fund-Auto-collection\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"post\", \"auto-collection\", signed=True, data=params\n        )\n\n    def papi_fund_asset_collection(self, **params):\n        \"\"\"Transfers specific asset from Futures Account to Margin account.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account/Fund-Collection-by-Asset\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"post\", \"asset-collection\", signed=True, data=params\n        )\n\n    def papi_bnb_transfer(self, **params):\n        \"\"\"Transfer BNB in and out of UM.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account/BNB-transfer\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\"post\", \"bnb-transfer\", signed=True, data=params)\n\n    def papi_get_um_income_history(self, **params):\n        \"\"\"Get UM Income History.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account/Get-UM-Income-History\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\"get\", \"um/income\", signed=True, data=params)\n\n    def papi_get_cm_income_history(self, **params):\n        \"\"\"Get CM Income History.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account/Get-CM-Income-History\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\"get\", \"cm/income\", signed=True, data=params)\n\n    def papi_get_um_account(self, **params):\n        \"\"\"Get current UM account asset and position information.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account/Get-UM-Account-Detail\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\"get\", \"um/account\", signed=True, data=params)\n\n    def papi_get_um_account_v2(self, **params):\n        \"\"\"Get current UM account asset and position information.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account/Get-UM-Account-Detail-V2\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"get\", \"um/account\", version=2, signed=True, data=params\n        )\n\n    def papi_get_cm_account(self, **params):\n        \"\"\"Get current CM account asset and position information.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account/Get-CM-Account-Detail\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\"get\", \"cm/account\", signed=True, data=params)\n\n    def papi_get_um_account_config(self, **params):\n        \"\"\"Query UM Futures account configuration.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account/Get-UM-Futures-Account-Config\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"get\", \"um/accountConfig\", signed=True, data=params\n        )\n\n    def papi_get_um_symbol_config(self, **params):\n        \"\"\"Get current UM account symbol configuration.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account/Get-UM-Futures-Symbol-Config\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"get\", \"um/symbolConfig\", signed=True, data=params\n        )\n\n    def papi_get_um_trade_asyn(self, **params):\n        \"\"\"Get download id for UM futures trade history.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account/Get-Download-Id-For-UM-Futures-Trade-History\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\"get\", \"um/trade/asyn\", signed=True, data=params)\n\n    def papi_get_um_trade_asyn_id(self, **params):\n        \"\"\"Get UM futures trade download link by Id.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account/Get-UM-Futures-Trade-Download-Link-by-Id\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"get\", \"um/trade/asyn/id\", signed=True, data=params\n        )\n\n    def papi_get_um_order_asyn(self, **params):\n        \"\"\"Get download id for UM futures order history.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account/Get-Download-Id-For-UM-Futures-Order-History\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\"get\", \"um/order/asyn\", signed=True, data=params)\n\n    def papi_get_um_order_asyn_id(self, **params):\n        \"\"\"Get UM futures order download link by Id.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account/Get-UM-Futures-Order-Download-Link-by-Id\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"get\", \"um/order/asyn/id\", signed=True, data=params\n        )\n\n    def papi_get_um_income_asyn(self, **params):\n        \"\"\"Get download id for UM futures transaction history.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account/Get-Download-Id-For-UM-Futures-Transaction-History\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\"get\", \"um/income/asyn\", signed=True, data=params)\n\n    def papi_get_um_income_asyn_id(self, **params):\n        \"\"\"Get UM futures Transaction download link by Id.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/account/Get-UM-Futures-Transaction-Download-Link-by-Id\n\n        :param recvWindow: optional\n        :type recvWindow: int\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"get\", \"um/income/asyn/id\", signed=True, data=params\n        )\n\n    # Public papi endpoints\n\n    def papi_ping(self, **params):\n        \"\"\"Test connectivity to the Rest API.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/market-data\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\"get\", \"ping\", signed=False, data=params)\n\n    # Trade papi endpoints\n\n    def papi_create_um_order(self, **params):\n        \"\"\"Place new UM order.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade\n\n        :returns: API response\n\n        \"\"\"\n        if \"newClientOrderId\" not in params:\n            params[\"newClientOrderId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n        return self._request_papi_api(\"post\", \"um/order\", signed=True, data=params)\n\n    def papi_create_um_conditional_order(self, **params):\n        \"\"\"Place new UM Conditional order.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/New-UM-Conditional-Order\n\n        :returns: API response\n\n        \"\"\"\n        if \"newClientOrderId\" not in params:\n            params[\"newClientOrderId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n        return self._request_papi_api(\n            \"post\", \"um/conditional/order\", signed=True, data=params\n        )\n\n    def papi_create_cm_order(self, **params):\n        \"\"\"Place new CM order.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/New-CM-Order\n\n        :returns: API response\n\n        \"\"\"\n        if \"newClientOrderId\" not in params:\n            params[\"newClientOrderId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n        return self._request_papi_api(\"post\", \"cm/order\", signed=True, data=params)\n\n    def papi_create_cm_conditional_order(self, **params):\n        \"\"\"Place new CM Conditional order.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/New-CM-Conditional-Order\n\n        :returns: API response\n\n        \"\"\"\n        if \"newClientOrderId\" not in params:\n            params[\"newClientOrderId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n        return self._request_papi_api(\n            \"post\", \"cm/conditional/order\", signed=True, data=params\n        )\n\n    def papi_create_margin_order(self, **params):\n        \"\"\"New Margin Order.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/New-Margin-Order\n\n        :returns: API response\n\n        \"\"\"\n        if \"newClientOrderId\" not in params:\n            params[\"newClientOrderId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n        return self._request_papi_api(\"post\", \"margin/order\", signed=True, data=params)\n\n    def papi_margin_loan(self, **params):\n        \"\"\"Apply for a margin loan.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Margin-Account-Borrow\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\"post\", \"marginLoan\", signed=True, data=params)\n\n    def papi_repay_loan(self, **params):\n        \"\"\"Repay for a margin loan.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Margin-Account-Repay\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\"post\", \"repayLoan\", signed=True, data=params)\n\n    def papi_margin_order_oco(self, **params):\n        \"\"\"Send in a new OCO for a margin account.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Margin-Account-New-OCO\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"post\", \"margin/order/oco\", signed=True, data=params\n        )\n\n    def papi_cancel_um_order(self, **params):\n        \"\"\"Cancel an active UM LIMIT order.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Cancel-UM-Order\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\"delete\", \"um/order\", signed=True, data=params)\n\n    def papi_cancel_um_all_open_orders(self, **params):\n        \"\"\"Cancel an active UM LIMIT order.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Cancel-All-UM-Open-Orders\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"delete\", \"um/allOpenOrders\", signed=True, data=params\n        )\n\n    def papi_cancel_um_conditional_order(self, **params):\n        \"\"\"Cancel UM Conditional Order.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Cancel-UM-Conditional-Order\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"delete\", \"um/conditional/order\", signed=True, data=params\n        )\n\n    def papi_cancel_um_conditional_all_open_orders(self, **params):\n        \"\"\"Cancel All UM Open Conditional Orders.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Cancel-All-UM-Open-Conditional-Orders\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"delete\", \"um/conditional/allOpenOrders\", signed=True, data=params\n        )\n\n    def papi_cancel_cm_order(self, **params):\n        \"\"\"Cancel an active CM LIMIT order.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Cancel-CM-Order\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\"delete\", \"cm/order\", signed=True, data=params)\n\n    def papi_cancel_cm_all_open_orders(self, **params):\n        \"\"\"Cancel an active CM LIMIT order.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Cancel-All-CM-Open-Orders\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"delete\", \"cm/allOpenOrders\", signed=True, data=params\n        )\n\n    def papi_cancel_cm_conditional_order(self, **params):\n        \"\"\"Cancel CM Conditional Order.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Cancel-CM-Conditional-Order\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"delete\", \"cm/conditional/order\", signed=True, data=params\n        )\n\n    def papi_cancel_cm_conditional_all_open_orders(self, **params):\n        \"\"\"Cancel All CM Open Conditional Orders.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Cancel-All-CM-Open-Conditional-Orders\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"delete\", \"cm/conditional/allOpenOrders\", signed=True, data=params\n        )\n\n    def papi_cancel_margin_order(self, **params):\n        \"\"\"Cancel Margin Account Order.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Cancel-Margin-Account-Order\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"delete\", \"margin/order\", signed=True, data=params\n        )\n\n    def papi_cancel_margin_order_list(self, **params):\n        \"\"\"Cancel Margin Account OCO Orders.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Cancel-Margin-Account-OCO-Orders\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"delete\", \"margin/orderList\", signed=True, data=params\n        )\n\n    def papi_cancel_margin_all_open_orders(self, **params):\n        \"\"\"Cancel Margin Account All Open Orders on a Symbol.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Cancel-Margin-Account-All-Open-Orders-on-a-Symbol\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"delete\", \"margin/allOpenOrders\", signed=True, data=params\n        )\n\n    def papi_modify_um_order(self, **params):\n        \"\"\"Order modify function, currently only LIMIT order modification is supported, modified orders will be reordered in the match queue.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Modify-UM-Order\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\"put\", \"um/order\", signed=True, data=params)\n\n    def papi_modify_cm_order(self, **params):\n        \"\"\"Order modify function, currently only LIMIT order modification is supported, modified orders will be reordered in the match queue.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Modify-CM-Order\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\"put\", \"cm/order\", signed=True, data=params)\n\n    def papi_get_um_order(self, **params):\n        \"\"\"Check an UM order's status.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-UM-Order\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\"get\", \"um/order\", signed=True, data=params)\n\n    def papi_get_um_all_orders(self, **params):\n        \"\"\"Get all account UM orders; active, canceled, or filled.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-All-UM-Orders\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\"get\", \"um/allOrders\", signed=True, data=params)\n\n    def papi_get_um_open_order(self, **params):\n        \"\"\"Query current UM open order.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-Current-UM-Open-Order\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\"get\", \"um/openOrder\", signed=True, data=params)\n\n    def papi_get_um_open_orders(self, **params):\n        \"\"\"Get all open orders on a symbol.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-All-Current-UM-Open-Orders\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\"get\", \"um/openOrders\", signed=True, data=params)\n\n    def papi_get_um_conditional_all_orders(self, **params):\n        \"\"\"Query All UM Conditional Orders.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-All-UM-Conditional-Orders\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"get\", \"um/conditional/allOrders\", signed=True, data=params\n        )\n\n    def papi_get_um_conditional_open_orders(self, **params):\n        \"\"\"Get all open conditional orders on a symbol.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-All-Current-UM-Open-Conditional-Orders\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"get\", \"um/conditional/openOrders\", signed=True, data=params\n        )\n\n    def papi_get_um_conditional_open_order(self, **params):\n        \"\"\"Query Current UM Open Conditional Order.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-Current-UM-Open-Conditional-Order\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"get\", \"um/conditional/openOrder\", signed=True, data=params\n        )\n\n    def papi_get_um_conditional_order_history(self, **params):\n        \"\"\"Get all open conditional orders on a symbol.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-UM-Conditional-Order-History\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"get\", \"um/conditional/orderHistory\", signed=True, data=params\n        )\n\n    def papi_get_cm_order(self, **params):\n        \"\"\"Check an CM order's status.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-CM-Order\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\"get\", \"cm/order\", signed=True, data=params)\n\n    def papi_get_cm_all_orders(self, **params):\n        \"\"\"Get all account CM orders; active, canceled, or filled.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-All-CM-Orders\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\"get\", \"cm/allOrders\", signed=True, data=params)\n\n    def papi_get_cm_open_order(self, **params):\n        \"\"\"Query current CM open order.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-Current-CM-Open-Order\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\"get\", \"cm/openOrder\", signed=True, data=params)\n\n    def papi_get_cm_open_orders(self, **params):\n        \"\"\"Get all open orders on a symbol.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-All-Current-CM-Open-Orders\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\"get\", \"cm/openOrders\", signed=True, data=params)\n\n    def papi_get_cm_conditional_all_orders(self, **params):\n        \"\"\"Query All CM Conditional Orders.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-All-CM-Conditional-Orders\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"get\", \"cm/conditional/allOrders\", signed=True, data=params\n        )\n\n    def papi_get_cm_conditional_open_orders(self, **params):\n        \"\"\"Get all open conditional orders on a symbol.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-All-Current-CM-Open-Conditional-Orders\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"get\", \"cm/conditional/openOrders\", signed=True, data=params\n        )\n\n    def papi_get_cm_conditional_open_order(self, **params):\n        \"\"\"Query Current UM Open Conditional Order.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-Current-CM-Open-Conditional-Order\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"get\", \"cm/conditional/openOrder\", signed=True, data=params\n        )\n\n    def papi_get_cm_conditional_order_history(self, **params):\n        \"\"\"Get all open conditional orders on a symbol.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-CM-Conditional-Order-History\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"get\", \"cm/conditional/orderHistory\", signed=True, data=params\n        )\n\n    def papi_get_um_force_orders(self, **params):\n        \"\"\"Query User's UM Force Orders.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-Users-UM-Force-Orders\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\"get\", \"um/forceOrders\", signed=True, data=params)\n\n    def papi_get_cm_force_orders(self, **params):\n        \"\"\"Query User's CM Force Orders.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-Users-CM-Force-Orders\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\"get\", \"cm/forceOrders\", signed=True, data=params)\n\n    def papi_get_um_order_amendment(self, **params):\n        \"\"\"Get order modification history.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-UM-Modify-Order-History\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"get\", \"um/orderAmendment\", signed=True, data=params\n        )\n\n    def papi_get_cm_order_amendment(self, **params):\n        \"\"\"Get order modification history.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-CM-Modify-Order-History\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"get\", \"cm/orderAmendment\", signed=True, data=params\n        )\n\n    def papi_get_margin_force_orders(self, **params):\n        \"\"\"Query user's margin force orders.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-Users-Margin-Force-Orders\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"get\", \"margin/forceOrders\", signed=True, data=params\n        )\n\n    def papi_get_um_user_trades(self, **params):\n        \"\"\"Get trades for a specific account and UM symbol.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/UM-Account-Trade-List\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\"get\", \"um/userTrades\", signed=True, data=params)\n\n    def papi_get_cm_user_trades(self, **params):\n        \"\"\"Get trades for a specific account and CM symbol.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/CM-Account-Trade-List\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\"get\", \"cm/userTrades\", signed=True, data=params)\n\n    def papi_get_um_adl_quantile(self, **params):\n        \"\"\"Query UM Position ADL Quantile Estimation.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/UM-Position-ADL-Quantile-Estimation\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\"get\", \"um/adlQuantile\", signed=True, data=params)\n\n    def papi_get_cm_adl_quantile(self, **params):\n        \"\"\"Query CM Position ADL Quantile Estimation.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/CM-Position-ADL-Quantile-Estimation\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\"get\", \"cm/adlQuantile\", signed=True, data=params)\n\n    def papi_set_um_fee_burn(self, **params):\n        \"\"\"Change user's BNB Fee Discount for UM Futures (Fee Discount On or Fee Discount Off ) on EVERY symbol.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Toggle-BNB-Burn-On-UM-Futures-Trade\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\"post\", \"um/feeBurn\", signed=True, data=params)\n\n    def papi_get_um_fee_burn(self, **params):\n        \"\"\"Get user's BNB Fee Discount for UM Futures (Fee Discount On or Fee Discount Off).\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Get-UM-Futures-BNB-Burn-Status\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\"get\", \"um/feeBurn\", signed=True, data=params)\n\n    def papi_get_margin_order(self, **params):\n        \"\"\"Query Margin Account Order.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-Margin-Account-Order\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\"get\", \"margin/order\", signed=True, data=params)\n\n    def papi_get_margin_open_orders(self, **params):\n        \"\"\"Query Current Margin Open Order.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-Current-Margin-Open-Order\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"get\", \"margin/openOrders\", signed=True, data=params\n        )\n\n    def papi_get_margin_all_orders(self, **params):\n        \"\"\"Query All Margin Account Orders.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-All-Margin-Account-Orders\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"get\", \"margin/allOrders\", signed=True, data=params\n        )\n\n    def papi_get_margin_order_list(self, **params):\n        \"\"\"Retrieves a specific OCO based on provided optional parameters.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-Margin-Account-OCO\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"get\", \"margin/orderList\", signed=True, data=params\n        )\n\n    def papi_get_margin_all_order_list(self, **params):\n        \"\"\"Query all OCO for a specific margin account based on provided optional parameters.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-Margin-Account-all-OCO\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"get\", \"margin/allOrderList\", signed=True, data=params\n        )\n\n    def papi_get_margin_open_order_list(self, **params):\n        \"\"\"Query Margin Account's Open OCO.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Query-Margin-Account-Open-OCO\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"get\", \"margin/openOrderList\", signed=True, data=params\n        )\n\n    def papi_get_margin_my_trades(self, **params):\n        \"\"\"Margin Account Trade List.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Margin-Account-Trade-List\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"get\", \"margin/myTrades\", signed=True, data=params\n        )\n\n    def papi_get_margin_repay_debt(self, **params):\n        \"\"\"Repay debt for a margin loan.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin/trade/Margin-Account-Repay-Debt\n\n        :returns: API response\n\n        \"\"\"\n        return self._request_papi_api(\n            \"post\", \"margin/repay-debt\", signed=True, data=params\n        )\n\n    def close_connection(self):\n        if self.session:\n            self.session.close()\n\n    def __del__(self):\n        self.close_connection()\n\n    ############################################################\n    # WebSocket API methods\n    ############################################################\n\n    def ws_create_test_order(self, **params):\n        \"\"\"Test new order creation and signature/recvWindow long. Creates and validates a new order but does not send it into the matching engine.\n        https://binance-docs.github.io/apidocs/websocket_api/en/#test-new-order-trade\n        :param symbol: required\n        :type symbol: str\n        :param side: required\n        :type side: str\n        :param type: required\n        :type type: str\n        :param timeInForce: required if limit order\n        :type timeInForce: str\n        :param quantity: required\n        :type quantity: decimal\n        :param price: required\n        :type price: str\n        :param newClientOrderId: A unique id for the order. Automatically generated if not sent.\n        :type newClientOrderId: str\n        :param icebergQty: Used with iceberg orders\n        :type icebergQty: decimal\n        :param newOrderRespType: Set the response JSON. ACK, RESULT, or FULL; default: RESULT.\n        :type newOrderRespType: str\n        :param recvWindow: The number of milliseconds the request is valid for\n        :type recvWindow: int\n        :returns: WS response\n        .. code-block:: python\n            {}\n        \"\"\"\n\n        if \"newClientOrderId\" not in params:\n            params[\"newClientOrderId\"] = self.SPOT_ORDER_PREFIX + self.uuid22()\n\n        return self._ws_api_request_sync(\"order.test\", True, params)\n\n    def ws_create_order(self, **params):\n        \"\"\"Create an order via WebSocket.\n        https://binance-docs.github.io/apidocs/websocket_api/en/#place-new-order-trade\n        :param id: The request ID to be used. By default uuid22() is used.\n        :param symbol: The symbol to create an order for\n        :param side: BUY or SELL\n        :param type: Order type (e.g., LIMIT, MARKET)\n        :param quantity: The amount to buy or sell\n        :param kwargs: Additional order parameters\n        \"\"\"\n        if \"newClientOrderId\" not in params:\n            params[\"newClientOrderId\"] = self.SPOT_ORDER_PREFIX + self.uuid22()\n\n        return self._ws_api_request_sync(\"order.place\", True, params)\n\n    def ws_order_limit(self, timeInForce=BaseClient.TIME_IN_FORCE_GTC, **params):\n        \"\"\"Send in a new limit order\n        Any order with an icebergQty MUST have timeInForce set to GTC.\n        :param symbol: required\n        :type symbol: str\n        :param side: required\n        :type side: str\n        :param quantity: required\n        :type quantity: decimal\n        :param price: required\n        :type price: str\n        :param timeInForce: default Good till cancelled\n        :type timeInForce: str\n        :param newClientOrderId: A unique id for the order. Automatically generated if not sent.\n        :type newClientOrderId: str\n        :param icebergQty: Used with LIMIT, STOP_LOSS_LIMIT, and TAKE_PROFIT_LIMIT to create an iceberg order.\n        :type icebergQty: decimal\n        :param newOrderRespType: Set the response JSON. ACK, RESULT, or FULL; default: RESULT.\n        :type newOrderRespType: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n        :returns: WS response\n        See order endpoint for full response options\n        \"\"\"\n        params.update({\n            \"type\": self.ORDER_TYPE_LIMIT,\n            \"timeInForce\": timeInForce,\n        })\n        return self.ws_create_order(**params)\n\n    def ws_order_limit_buy(self, timeInForce=BaseClient.TIME_IN_FORCE_GTC, **params):\n        \"\"\"Send in a new limit buy order\n        Any order with an icebergQty MUST have timeInForce set to GTC.\n        :param symbol: required\n        :type symbol: str\n        :param quantity: required\n        :type quantity: decimal\n        :param price: required\n        :type price: str\n        :param timeInForce: default Good till cancelled\n        :type timeInForce: str\n        :param newClientOrderId: A unique id for the order. Automatically generated if not sent.\n        :type newClientOrderId: str\n        :param stopPrice: Used with stop orders\n        :type stopPrice: decimal\n        :param icebergQty: Used with iceberg orders\n        :type icebergQty: decimal\n        :param newOrderRespType: Set the response JSON. ACK, RESULT, or FULL; default: RESULT.\n        :type newOrderRespType: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n        :returns: WS response\n        See order endpoint for full response options\n        \"\"\"\n        params.update({\n            \"side\": self.SIDE_BUY,\n        })\n        return self.ws_order_limit(timeInForce=timeInForce, **params)\n\n    def ws_order_limit_sell(self, timeInForce=BaseClient.TIME_IN_FORCE_GTC, **params):\n        \"\"\"Send in a new limit sell order\n        :param symbol: required\n        :type symbol: str\n        :param quantity: required\n        :type quantity: decimal\n        :param price: required\n        :type price: str\n        :param timeInForce: default Good till cancelled\n        :type timeInForce: str\n        :param newClientOrderId: A unique id for the order. Automatically generated if not sent.\n        :type newClientOrderId: str\n        :param stopPrice: Used with stop orders\n        :type stopPrice: decimal\n        :param icebergQty: Used with iceberg orders\n        :type icebergQty: decimal\n        :param newOrderRespType: Set the response JSON. ACK, RESULT, or FULL; default: RESULT.\n        :type newOrderRespType: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n        :returns: WS response\n        See order endpoint for full response options\n        \"\"\"\n        params.update({\"side\": self.SIDE_SELL})\n        return self.ws_order_limit(timeInForce=timeInForce, **params)\n\n    def ws_order_market(self, **params):\n        \"\"\"Send in a new market order\n        :param symbol: required\n        :type symbol: str\n        :param side: required\n        :type side: str\n        :param quantity: required\n        :type quantity: decimal\n        :param quoteOrderQty: amount the user wants to spend (when buying) or receive (when selling)\n            of the quote asset\n        :type quoteOrderQty: decimal\n        :param newClientOrderId: A unique id for the order. Automatically generated if not sent.\n        :type newClientOrderId: str\n        :param newOrderRespType: Set the response JSON. ACK, RESULT, or FULL; default: RESULT.\n        :type newOrderRespType: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n        :returns: WS response\n        See order endpoint for full response options\n        \"\"\"\n        params.update({\"type\": self.ORDER_TYPE_MARKET})\n        return self.ws_create_order(**params)\n\n    def ws_order_market_buy(self, **params):\n        \"\"\"Send in a new market buy order\n        :param symbol: required\n        :type symbol: str\n        :param quantity: required\n        :type quantity: decimal\n        :param quoteOrderQty: the amount the user wants to spend of the quote asset\n        :type quoteOrderQty: decimal\n        :param newClientOrderId: A unique id for the order. Automatically generated if not sent.\n        :type newClientOrderId: str\n        :param newOrderRespType: Set the response JSON. ACK, RESULT, or FULL; default: RESULT.\n        :type newOrderRespType: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n        :returns: WS response\n        See order endpoint for full response options\n        \"\"\"\n        params.update({\"side\": self.SIDE_BUY})\n        return self.ws_order_market(**params)\n\n    def ws_order_market_sell(self, **params):\n        \"\"\"Send in a new market sell order\n        :param symbol: required\n        :type symbol: str\n        :param quantity: required\n        :type quantity: decimal\n        :param quoteOrderQty: the amount the user wants to receive of the quote asset\n        :type quoteOrderQty: decimal\n        :param newClientOrderId: A unique id for the order. Automatically generated if not sent.\n        :type newClientOrderId: str\n        :param newOrderRespType: Set the response JSON. ACK, RESULT, or FULL; default: RESULT.\n        :type newOrderRespType: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n        :returns: WS response\n        See order endpoint for full response options\n        \"\"\"\n        params.update({\"side\": self.SIDE_SELL})\n        return self.ws_order_market(**params)\n\n    def ws_get_order(self, **params):\n        \"\"\"Check an order's status. Either orderId or origClientOrderId must be sent.\n        https://binance-docs.github.io/apidocs/websocket_api/en/#query-order-user_data\n        :param symbol: required\n        :type symbol: str\n        :param orderId: The unique order id\n        :type orderId: int\n        :param origClientOrderId: optional\n        :type origClientOrderId: str\n        :param recvWindow: the number of milliseconds the request is valid for\n        :type recvWindow: int\n        \"\"\"\n        return self._ws_api_request_sync(\"order.status\", True, params)\n\n    def ws_cancel_order(self, **params):\n        \"\"\"Cancel an active order.\n        https://developers.binance.com/docs/binance-spot-api-docs/testnet/web-socket-api/public-api-requests#cancel-order-trade\n\n        :param symbol: required - Trading symbol, e.g. 'BTCUSDT'\n        :type symbol: str\n        :param orderId: optional - The unique order id\n        :type orderId: int\n        :param origClientOrderId: optional - The original client order id\n        :type origClientOrderId: str\n        :param newClientOrderId: optional - Used to uniquely identify this cancel. Automatically generated if not sent\n        :type newClientOrderId: str\n        :param cancelRestrictions: optional - ONLY_NEW - Cancel will succeed if the order status is NEW. ONLY_PARTIALLY_FILLED - Cancel will succeed if order status is PARTIALLY_FILLED.\n        :type cancelRestrictions: str\n        :param recvWindow: optional - The number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        Either orderId or origClientOrderId must be sent.\n\n        Weight: 1\n\n        Returns:\n        .. code-block:: python\n            {\n                \"id\": \"5633b6a2-90a9-4192-83e7-925c90b6a2fd\",\n                \"method\": \"order.cancel\",\n                \"params\": {\n                    \"symbol\": \"BTCUSDT\",\n                    \"origClientOrderId\": \"4d96324ff9d44481926157\",\n                    \"apiKey\": \"vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A\",\n                    \"signature\": \"33d5b721f278ae17a52f004a82a6f68a70c68e7dd6776ed0be77a455ab855282\",\n                    \"timestamp\": 1660801715830\n                }\n            }\n        \"\"\"\n        return self._ws_api_request_sync(\"order.cancel\", True, params)\n\n    def ws_cancel_and_replace_order(self, **params):\n        \"\"\"Cancels an existing order and places a new order on the same symbol.\n        https://developers.binance.com/docs/binance-spot-api-docs/testnet/web-socket-api/public-api-requests#cancel-and-replace-order-trade\n\n        :param symbol: required - Trading symbol, e.g. 'BTCUSDT'\n        :type symbol: str\n        :param cancelReplaceMode: required - The mode of cancel-replace: STOP_ON_FAILURE - If the cancel request fails, new order placement will not be attempted. ALLOW_FAILURE - New order placement will be attempted even if cancel request fails\n        :type cancelReplaceMode: str\n        :param cancelOrderId: optional - The order ID to cancel\n        :type cancelOrderId: int\n        :param cancelOrigClientOrderId: optional - The original client order ID to cancel\n        :type cancelOrigClientOrderId: str\n        :param cancelNewClientOrderId: optional - Used to uniquely identify this cancel. Automatically generated if not sent\n        :type cancelNewClientOrderId: str\n        :param side: required - BUY or SELL\n        :type side: str\n        :param type: required - Order type, e.g. LIMIT, MARKET\n        :type type: str\n        :param timeInForce: optional - GTC, IOC, FOK\n        :type timeInForce: str\n        :param price: optional - Order price\n        :type price: str\n        :param quantity: optional - Order quantity\n        :type quantity: str\n        :param quoteOrderQty: optional - Quote quantity\n        :type quoteOrderQty: str\n        :param newClientOrderId: optional - Used to uniquely identify this new order\n        :type newClientOrderId: str\n        :param newOrderRespType: optional - ACK, RESULT, or FULL\n        :type newOrderRespType: str\n        :param stopPrice: optional - Used with STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, and TAKE_PROFIT_LIMIT orders\n        :type stopPrice: str\n        :param trailingDelta: optional - Used with TAKE_PROFIT, TAKE_PROFIT_LIMIT, STOP_LOSS, STOP_LOSS_LIMIT orders\n        :type trailingDelta: int\n        :param icebergQty: optional - Used with iceberg orders\n        :type icebergQty: str\n        :param strategyId: optional - Arbitrary numeric value identifying the order within an order strategy\n        :type strategyId: int\n        :param strategyType: optional - Arbitrary numeric value identifying the order strategy\n        :type strategyType: int\n        :param selfTradePreventionMode: optional - The allowed enums is dependent on what is configured on the symbol\n        :type selfTradePreventionMode: str\n        :param cancelRestrictions: optional - ONLY_NEW - Cancel will succeed if order status is NEW. ONLY_PARTIALLY_FILLED - Cancel will succeed if order status is PARTIALLY_FILLED\n        :type cancelRestrictions: str\n        :param recvWindow: optional - The number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        Either cancelOrderId or cancelOrigClientOrderId must be provided.\n        Price is required for LIMIT orders.\n        Either quantity or quoteOrderQty must be provided.\n\n        Weight: 1\n\n        Returns:\n        .. code-block:: python\n           {\n                \"id\": \"99de6b92-0eda-4154-9c8d-a51d93c6f92e\",\n                \"status\": 200,\n                \"result\": {\n                    \"cancelResult\": \"SUCCESS\",\n                    \"newOrderResult\": \"SUCCESS\",\n                    \"cancelResponse\": {\n                        \"symbol\": \"BTCUSDT\",\n                        \"origClientOrderId\": \"4d96324ff9d44481926157\",\n                        \"orderId\": 12569099453,\n                        \"orderListId\": -1,\n                        \"clientOrderId\": \"91fe37ce9e69c90d6358c0\",\n                        \"price\": \"23416.10000000\",\n                        \"origQty\": \"0.00847000\",\n                        \"executedQty\": \"0.00001000\",\n                        \"cummulativeQuoteQty\": \"0.23416100\",\n                        \"status\": \"CANCELED\",\n                        \"timeInForce\": \"GTC\",\n                        \"type\": \"LIMIT\",\n                        \"side\": \"SELL\",\n                        \"selfTradePreventionMode\": \"NONE\"\n                    },\n                    \"newOrderResponse\": {\n                        \"symbol\": \"BTCUSDT\",\n                        \"orderId\": 12569099454,\n                        \"orderListId\": -1,\n                        \"clientOrderId\": \"bX5wROblo6YeDwa9iTLeyY\",\n                        \"transactTime\": 1660801715639\n                    }\n                }\n            }\n        \"\"\"\n        return self._ws_api_request_sync(\"order.cancelReplace\", True, params)\n\n    def ws_get_open_orders(self, **params):\n        \"\"\"Get all open orders on a symbol or all symbols.\n        https://developers.binance.com/docs/binance-spot-api-docs/testnet/web-socket-api/public-api-requests#current-open-orders-user_data\n\n        :param symbol: optional - Symbol to get open orders for\n        :type symbol: str\n        :param recvWindow: optional - The value cannot be greater than 60000\n        :type recvWindow: int\n\n        :returns: API response\n\n        Response format:\n        [\n            {\n                \"symbol\": \"BTCUSDT\",\n                \"orderId\": 12569099453,\n                \"orderListId\": -1,\n                \"clientOrderId\": \"4d96324ff9d44481926157\",\n                \"price\": \"23416.10000000\",\n                \"origQty\": \"0.00847000\",\n                \"executedQty\": \"0.00720000\",\n                \"cummulativeQuoteQty\": \"168.59532000\",\n                \"status\": \"PARTIALLY_FILLED\",\n                \"timeInForce\": \"GTC\",\n                \"type\": \"LIMIT\",\n                \"side\": \"SELL\",\n                \"stopPrice\": \"0.00000000\",\n                \"icebergQty\": \"0.00000000\",\n                \"time\": 1660801715639,\n                \"updateTime\": 1660801717945,\n                \"isWorking\": true,\n                \"workingTime\": 1660801715639,\n                \"origQuoteOrderQty\": \"0.00000000\",\n                \"selfTradePreventionMode\": \"NONE\"\n            }\n        ]\n\n        Weight: Adjusted based on parameters:\n        - With symbol: 6\n        - Without symbol: 12\n        \"\"\"\n        return self._ws_api_request_sync(\"openOrders.status\", True, params)\n\n    def ws_cancel_all_open_orders(self, **params):\n        \"\"\"Cancel all open orders on a symbol or all symbols.\n        https://developers.binance.com/docs/binance-spot-api-docs/testnet/web-socket-api/public-api-requests#cancel-open-orders-trade\n\n        :param symbol: optional - Symbol to cancel orders for\n        :type symbol: str\n        :param recvWindow: optional - The value cannot be greater than 60000\n        :type recvWindow: int\n\n        :returns: Websocket message\n\n        Response format:\n        [\n            {\n                \"symbol\": \"BTCUSDT\",\n                \"origClientOrderId\": \"4d96324ff9d44481926157\",\n                \"orderId\": 12569099453,\n                \"orderListId\": -1,\n                \"clientOrderId\": \"91fe37ce9e69c90d6358c0\",\n                \"price\": \"23416.10000000\",\n                \"origQty\": \"0.00847000\",\n                \"executedQty\": \"0.00847000\",\n                \"cummulativeQuoteQty\": \"198.33521500\",\n                \"status\": \"CANCELED\",\n                \"timeInForce\": \"GTC\",\n                \"type\": \"LIMIT\",\n                \"side\": \"SELL\",\n                \"stopPrice\": \"0.00000000\",\n                \"trailingDelta\": 0,\n                \"trailingTime\": -1,\n                \"icebergQty\": \"0.00000000\",\n                \"strategyId\": 37463720,\n                \"strategyType\": 1000000,\n                \"selfTradePreventionMode\": \"NONE\"\n            }\n        ]\n\n        Weight: 1\n        \"\"\"\n        return self._ws_api_request_sync(\"openOrders.cancelAll\", True, params)\n\n    def ws_create_oco_order(self, **params):\n        \"\"\"Create a new OCO (One-Cancels-the-Other) order.\n        https://developers.binance.com/docs/binance-spot-api-docs/testnet/web-socket-api/public-api-requests#place-new-order-list---oco-trade\n\n        :param symbol: required - Trading symbol\n        :type symbol: str\n        :param side: required - BUY or SELL\n        :type side: str\n        :param quantity: required - Order quantity\n        :type quantity: decimal\n        :param price: required - Order price for limit leg\n        :type price: decimal\n        :param stopPrice: required - Stop trigger price for stop leg\n        :type stopPrice: decimal\n        :param stopLimitPrice: optional - Stop limit price for stop leg\n        :type stopLimitPrice: decimal\n        :param stopLimitTimeInForce: optional - Time in force for stop leg\n        :type stopLimitTimeInForce: str\n        :param listClientOrderId: optional - Unique ID for the entire orderList\n        :type listClientOrderId: str\n        :param limitClientOrderId: optional - Unique ID for the limit order\n        :type limitClientOrderId: str\n        :param stopClientOrderId: optional - Unique ID for the stop order\n        :type stopClientOrderId: str\n        :param limitStrategyId: optional - Arbitrary numeric value identifying the limit order within an order strategy\n        :type limitStrategyId: int\n        :param limitStrategyType: optional - Arbitrary numeric value identifying the limit order strategy\n        :type limitStrategyType: int\n        :param stopStrategyId: optional - Arbitrary numeric value identifying the stop order within an order strategy\n        :type stopStrategyId: int\n        :param stopStrategyType: optional - Arbitrary numeric value identifying the stop order strategy\n        :type stopStrategyType: int\n        :param limitIcebergQty: optional - Iceberg quantity for the limit leg\n        :type limitIcebergQty: decimal\n        :param stopIcebergQty: optional - Iceberg quantity for the stop leg\n        :type stopIcebergQty: decimal\n        :param recvWindow: optional - The value cannot be greater than 60000\n        :type recvWindow: int\n\n        :returns: Websocket message\n\n        Response format:\n        .. code-block:: python\n            {\n                \"id\": \"56374a46-3261-486b-a211-99ed972eb648\",\n                \"status\": 200,\n                \"result\":\n                {\n                    \"orderListId\": 2,\n                    \"contingencyType\": \"OCO\",\n                    \"listStatusType\": \"EXEC_STARTED\",\n                    \"listOrderStatus\": \"EXECUTING\",\n                    \"listClientOrderId\": \"cKPMnDCbcLQILtDYM4f4fX\",\n                    \"transactionTime\": 1711062760648,\n                    \"symbol\": \"LTCBNB\",\n                    \"orders\":\n                    [\n                    {\n                        \"symbol\": \"LTCBNB\",\n                        \"orderId\": 2,\n                        \"clientOrderId\": \"0m6I4wfxvTUrOBSMUl0OPU\"\n                    },\n                    {\n                        \"symbol\": \"LTCBNB\",\n                        \"orderId\": 3,\n                        \"clientOrderId\": \"Z2IMlR79XNY5LU0tOxrWyW\"\n                    }\n                    ],\n                    \"orderReports\":\n                    [\n                    {\n                        \"symbol\": \"LTCBNB\",\n                        \"orderId\": 2,\n                        \"orderListId\": 2,\n                        \"clientOrderId\": \"0m6I4wfxvTUrOBSMUl0OPU\",\n                        \"transactTime\": 1711062760648,\n                        \"price\": \"1.50000000\",\n                        \"origQty\": \"1.000000\",\n                        \"executedQty\": \"0.000000\",\n                        \"origQuoteOrderQty\": \"0.000000\",\n                        \"cummulativeQuoteQty\": \"0.00000000\",\n                        \"status\": \"NEW\",\n                        \"timeInForce\": \"GTC\",\n                        \"type\": \"STOP_LOSS_LIMIT\",\n                        \"side\": \"BUY\",\n                        \"stopPrice\": \"1.50000001\",\n                        \"workingTime\": -1,\n                        \"selfTradePreventionMode\": \"NONE\"\n                    },\n                    {\n                        \"symbol\": \"LTCBNB\",\n                        \"orderId\": 3,\n                        \"orderListId\": 2,\n                        \"clientOrderId\": \"Z2IMlR79XNY5LU0tOxrWyW\",\n                        \"transactTime\": 1711062760648,\n                        \"price\": \"1.49999999\",\n                        \"origQty\": \"1.000000\",\n                        \"executedQty\": \"0.000000\",\n                        \"origQuoteOrderQty\": \"0.000000\",\n                        \"cummulativeQuoteQty\": \"0.00000000\",\n                        \"status\": \"NEW\",\n                        \"timeInForce\": \"GTC\",\n                        \"type\": \"LIMIT_MAKER\",\n                        \"side\": \"BUY\",\n                        \"workingTime\": 1711062760648,\n                        \"selfTradePreventionMode\": \"NONE\"\n                    }\n                    ]\n                },\n                \"rateLimits\":\n                [\n                    {\n                    \"rateLimitType\": \"ORDERS\",\n                    \"interval\": \"SECOND\",\n                    \"intervalNum\": 10,\n                    \"limit\": 50,\n                    \"count\": 2\n                    },\n                    {\n                    \"rateLimitType\": \"ORDERS\",\n                    \"interval\": \"DAY\",\n                    \"intervalNum\": 1,\n                    \"limit\": 160000,\n                    \"count\": 2\n                    },\n                    {\n                    \"rateLimitType\": \"REQUEST_WEIGHT\",\n                    \"interval\": \"MINUTE\",\n                    \"intervalNum\": 1,\n                    \"limit\": 6000,\n                    \"count\": 1\n                    }\n                ]\n            }\n\n        Weight: 2\n        \"\"\"\n        return self._ws_api_request_sync(\"orderList.place.oco\", True, params)\n\n    def ws_create_oto_order(self, **params):\n        \"\"\"Create a new OTO (One-Triggers-Other) order list.\n        https://developers.binance.com/docs/binance-spot-api-docs/testnet/web-socket-api/public-api-requests#place-new-order-list---oto-trade\n\n        An OTO order list consists of two orders:\n        1. Primary order that must be filled first\n        2. Secondary order that is placed only after the primary order is filled\n\n        :param symbol: required - Trading symbol\n        :type symbol: str\n        :param orders: required - Array of order objects containing:\n            [\n                {  # Primary order\n                    \"type\": required - Order type (e.g. LIMIT, MARKET),\n                    \"side\": required - BUY or SELL,\n                    \"price\": required for LIMIT orders,\n                    \"quantity\": required - Order quantity,\n                    \"timeInForce\": required for LIMIT orders,\n                    \"icebergQty\": optional,\n                    \"strategyId\": optional,\n                    \"strategyType\": optional,\n                    \"selfTradePreventionMode\": optional\n                },\n                {  # Secondary order - same parameters as primary\n                    ...\n                }\n            ]\n        :type orders: list\n        :param listClientOrderId: optional - Unique ID for the entire order list\n        :type listClientOrderId: str\n        :param limitClientOrderId: optional - Client order ID for the LIMIT leg\n        :type limitClientOrderId: str\n        :param limitStrategyId: optional - Strategy ID for the LIMIT leg\n        :type limitStrategyId: int\n        :param limitStrategyType: optional - Strategy type for the LIMIT leg\n        :type limitStrategyType: int\n        :param stopClientOrderId: optional - Client order ID for the STOP_LOSS/STOP_LOSS_LIMIT leg\n        :type stopClientOrderId: str\n        :param stopStrategyId: optional - Strategy ID for the STOP_LOSS/STOP_LOSS_LIMIT leg\n        :type stopStrategyId: int\n        :param stopStrategyType: optional - Strategy type for the STOP_LOSS/STOP_LOSS_LIMIT leg\n        :type stopStrategyType: int\n        :param newOrderRespType: optional - Set the response JSON\n        :type newOrderRespType: str\n\n        Response example:\n        .. code-block:: python\n            {\n                \"id\": \"c5899911-d3f4-47ae-8835-97da553d27d0\",\n                \"status\": 200,\n                \"result\": {\n                    \"orderListId\": 1,\n                    \"contingencyType\": \"OTO\",\n                    \"listStatusType\": \"EXEC_STARTED\",\n                    \"listOrderStatus\": \"EXECUTING\",\n                    \"listClientOrderId\": \"C3wyRVh3aqKyI2RpBZYmFz\",\n                    \"transactionTime\": 1669632210676,\n                    \"symbol\": \"BTCUSDT\",\n                    \"orders\": [\n                        {\n                            \"symbol\": \"BTCUSDT\",\n                            \"orderId\": 12569099453,\n                            \"clientOrderId\": \"bX5wROblo6YeDwa9iTLeyY\"\n                        },\n                        {\n                            \"symbol\": \"BTCUSDT\",\n                            \"orderId\": 12569099454,\n                            \"clientOrderId\": \"Tnu2IP0J5Y4mxw3IxZYeFi\"\n                        }\n                    ],\n                    \"orderReports\": [\n                        {\n                            \"symbol\": \"BTCUSDT\",\n                            \"orderId\": 12569099453,\n                            \"orderListId\": 1,\n                            \"clientOrderId\": \"bX5wROblo6YeDwa9iTLeyY\",\n                            \"transactTime\": 1669632210676,\n                            \"price\": \"23416.10000000\",\n                            \"origQty\": \"0.00847000\",\n                            \"executedQty\": \"0.00847000\",\n                            \"cummulativeQuoteQty\": \"198.33521500\",\n                            \"status\": \"FILLED\",\n                            \"timeInForce\": \"GTC\",\n                            \"type\": \"LIMIT\",\n                            \"side\": \"SELL\",\n                            \"stopPrice\": \"0.00000000\",\n                            \"workingTime\": 1669632210676,\n                            \"selfTradePreventionMode\": \"NONE\"\n                        },\n                        {\n                            \"symbol\": \"BTCUSDT\",\n                            \"orderId\": 12569099454,\n                            \"orderListId\": 1,\n                            \"clientOrderId\": \"Tnu2IP0J5Y4mxw3IxZYeFi\",\n                            \"transactTime\": 1669632210676,\n                            \"price\": \"0.00000000\",\n                            \"origQty\": \"0.00847000\",\n                            \"executedQty\": \"0.00000000\",\n                            \"cummulativeQuoteQty\": \"0.00000000\",\n                            \"status\": \"NEW\",\n                            \"timeInForce\": \"GTC\",\n                            \"type\": \"MARKET\",\n                            \"side\": \"BUY\",\n                            \"stopPrice\": \"0.00000000\",\n                            \"workingTime\": -1,\n                            \"selfTradePreventionMode\": \"NONE\"\n                        }\n                    ]\n                },\n                \"rateLimits\": [\n                    {\n                        \"rateLimitType\": \"ORDERS\",\n                        \"interval\": \"SECOND\",\n                        \"intervalNum\": 10,\n                        \"limit\": 50,\n                        \"count\": 1\n                    },\n                    {\n                        \"rateLimitType\": \"ORDERS\",\n                        \"interval\": \"DAY\",\n                        \"intervalNum\": 1,\n                        \"limit\": 160000,\n                        \"count\": 1\n                    },\n                    {\n                        \"rateLimitType\": \"REQUEST_WEIGHT\",\n                        \"interval\": \"MINUTE\",\n                        \"intervalNum\": 1,\n                        \"limit\": 6000,\n                        \"count\": 1\n                    }\n                ]\n            }\n\n        Weight: 1\n        \"\"\"\n        return self._ws_api_request_sync(\"orderList.place.oto\", True, params)\n\n    def ws_create_otoco_order(self, **params):\n        \"\"\"\n\n        Returns: Websocket message\n        .. code-block:: python\n            {\n                \"id\": \"1712544408508\",\n                \"status\": 200,\n                \"result\": {\n                    \"orderListId\": 629,\n                    \"contingencyType\": \"OTO\",\n                    \"listStatusType\": \"EXEC_STARTED\",\n                    \"listOrderStatus\": \"EXECUTING\",\n                    \"listClientOrderId\": \"GaeJHjZPasPItFj4x7Mqm6\",\n                    \"transactionTime\": 1712544408537,\n                    \"symbol\": \"1712544378871\",\n                    \"orders\": [\n                    {\n                        \"symbol\": \"1712544378871\",\n                        \"orderId\": 23,\n                        \"clientOrderId\": \"OVQOpKwfmPCfaBTD0n7e7H\"\n                    },\n                    {\n                        \"symbol\": \"1712544378871\",\n                        \"orderId\": 24,\n                        \"clientOrderId\": \"YcCPKCDMQIjNvLtNswt82X\"\n                    },\n                    {\n                        \"symbol\": \"1712544378871\",\n                        \"orderId\": 25,\n                        \"clientOrderId\": \"ilpIoShcFZ1ZGgSASKxMPt\"\n                    }\n                    ],\n                    \"orderReports\": [\n                    {\n                        \"symbol\": \"LTCBNB\",\n                        \"orderId\": 23,\n                        \"orderListId\": 629,\n                        \"clientOrderId\": \"OVQOpKwfmPCfaBTD0n7e7H\",\n                        \"transactTime\": 1712544408537,\n                        \"price\": \"1.500000\",\n                        \"origQty\": \"1.000000\",\n                        \"executedQty\": \"0.000000\",\n                        \"origQuoteOrderQty\": \"0.000000\",\n                        \"cummulativeQuoteQty\": \"0.000000\",\n                        \"status\": \"NEW\",\n                        \"timeInForce\": \"GTC\",\n                        \"type\": \"LIMIT\",\n                        \"side\": \"BUY\",\n                        \"workingTime\": 1712544408537,\n                        \"selfTradePreventionMode\": \"NONE\"\n                    },\n                    {\n                        \"symbol\": \"LTCBNB\",\n                        \"orderId\": 24,\n                        \"orderListId\": 629,\n                        \"clientOrderId\": \"YcCPKCDMQIjNvLtNswt82X\",\n                        \"transactTime\": 1712544408537,\n                        \"price\": \"0.000000\",\n                        \"origQty\": \"5.000000\",\n                        \"executedQty\": \"0.000000\",\n                        \"origQuoteOrderQty\": \"0.000000\",\n                        \"cummulativeQuoteQty\": \"0.000000\",\n                        \"status\": \"PENDING_NEW\",\n                        \"timeInForce\": \"GTC\",\n                        \"type\": \"STOP_LOSS\",\n                        \"side\": \"SELL\",\n                        \"stopPrice\": \"0.500000\",\n                        \"workingTime\": -1,\n                        \"selfTradePreventionMode\": \"NONE\"\n                    },\n                    {\n                        \"symbol\": \"LTCBNB\",\n                        \"orderId\": 25,\n                        \"orderListId\": 629,\n                        \"clientOrderId\": \"ilpIoShcFZ1ZGgSASKxMPt\",\n                        \"transactTime\": 1712544408537,\n                        \"price\": \"5.000000\",\n                        \"origQty\": \"5.000000\",\n                        \"executedQty\": \"0.000000\",\n                        \"origQuoteOrderQty\": \"0.000000\",\n                        \"cummulativeQuoteQty\": \"0.000000\",\n                        \"status\": \"PENDING_NEW\",\n                        \"timeInForce\": \"GTC\",\n                        \"type\": \"LIMIT_MAKER\",\n                        \"side\": \"SELL\",\n                        \"workingTime\": -1,\n                        \"selfTradePreventionMode\": \"NONE\"\n                    }\n                    ]\n                },\n                \"rateLimits\": [\n                    {\n                    \"rateLimitType\": \"ORDERS\",\n                    \"interval\": \"MINUTE\",\n                    \"intervalNum\": 1,\n                    \"limit\": 10000000,\n                    \"count\": 18\n                    },\n                    {\n                    \"rateLimitType\": \"REQUEST_WEIGHT\",\n                    \"interval\": \"MINUTE\",\n                    \"intervalNum\": 1,\n                    \"limit\": 1000,\n                    \"count\": 65\n                    }\n                ]\n        }\n\n        Weight: 1\n        \"\"\"\n        return self._ws_api_request_sync(\"orderList.place.otoco\", True, params)\n\n    def ws_get_oco_order(self, **params):\n        \"\"\"Query information about a specific OCO order list.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/testnet/web-socket-api/public-api-requests#query-order-list-user_data\n\n        :param orderListId: int - The identifier for the OCO order list (optional)\n        :param origClientOrderId: str - The client-specified OCO order list ID (optional)\n\n        :returns: API response containing OCO order list information including:\n        .. code-block:: python\n            {\n                \"id\": \"b53fd5ff-82c7-4a04-bd64-5f9dc42c2100\",\n                \"status\": 200,\n                \"result\": {\n                    \"orderListId\": 1274512,\n                    \"contingencyType\": \"OCO\",\n                    \"listStatusType\": \"EXEC_STARTED\",\n                    \"listOrderStatus\": \"EXECUTING\",\n                    \"listClientOrderId\": \"08985fedd9ea2cf6b28996\",\n                    \"transactionTime\": 1660801713793,\n                    \"symbol\": \"BTCUSDT\",\n                    \"orders\": [\n                    {\n                        \"symbol\": \"BTCUSDT\",\n                        \"orderId\": 12569138901,\n                        \"clientOrderId\": \"BqtFCj5odMoWtSqGk2X9tU\"\n                    },\n                    {\n                        \"symbol\": \"BTCUSDT\",\n                        \"orderId\": 12569138902,\n                        \"clientOrderId\": \"jLnZpj5enfMXTuhKB1d0us\"\n                    }\n                    ]\n                },\n                \"rateLimits\": [\n                    {\n                    \"rateLimitType\": \"REQUEST_WEIGHT\",\n                    \"interval\": \"MINUTE\",\n                    \"intervalNum\": 1,\n                    \"limit\": 6000,\n                    \"count\": 4\n                    }\n                ]\n            }\n\n        Notes:\n            - Either orderListId or origClientOrderId must be provided\n            - Weight: 4\n            - Data Source: Database\n\n        \"\"\"\n        return self._ws_api_request_sync(\"orderList.status\", True, params)\n\n    def ws_cancel_oco_order(self, **params):\n        \"\"\"Cancel an OCO (One-Cancels-the-Other) order list.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/testnet/web-socket-api/public-api-requests#cancel-order-list-trade\n\n        :param symbol: required - Trading symbol\n        :type symbol: str\n        :param orderListId: optional - The ID of the OCO order list to cancel\n        :type orderListId: int\n        :param listClientOrderId: optional - The client-specified ID of the OCO order list\n        :type listClientOrderId: str\n        :param newClientOrderId: optional - Client ID to identify the cancel request\n        :type newClientOrderId: str\n        :param apiKey: required - Your API key\n        :type apiKey: str\n        :param recvWindow: optional - Number of milliseconds the request is valid for\n        :type recvWindow: int\n        :param signature: required - HMAC SHA256 signature\n        :type signature: str\n        :param timestamp: required - Current timestamp in milliseconds\n        :type timestamp: int\n\n        **Notes**:\n            - Either orderListId or listClientOrderId must be provided\n            - newClientOrderId will be auto-generated if not provided\n\n        Response example:\n        .. code-block:: python\n            {\n                \"id\": \"c5899911-d3f4-47ae-8835-97da553d27d0\",\n                \"status\": 200,\n                \"result\": {\n                    \"orderListId\": 1274512,\n                    \"contingencyType\": \"OCO\",\n                    \"listStatusType\": \"ALL_DONE\",\n                    \"listOrderStatus\": \"ALL_DONE\",\n                    \"listClientOrderId\": \"6023531d7edaad348f5aff\",\n                    \"transactionTime\": 1660801720215,\n                    \"symbol\": \"BTCUSDT\",\n                    \"orders\": [\n                        {\n                            \"symbol\": \"BTCUSDT\",\n                            \"orderId\": 12569138901,\n                            \"clientOrderId\": \"BqtFCj5odMoWtSqGk2X9tU\"\n                        },\n                        {\n                            \"symbol\": \"BTCUSDT\",\n                            \"orderId\": 12569138902,\n                            \"clientOrderId\": \"jLnZpj5enfMXTuhKB1d0us\"\n                        }\n                    ],\n                    \"orderReports\": [\n                        {\n                            \"symbol\": \"BTCUSDT\",\n                            \"orderId\": 12569138901,\n                            \"orderListId\": 1274512,\n                            \"clientOrderId\": \"BqtFCj5odMoWtSqGk2X9tU\",\n                            \"transactTime\": 1660801720215,\n                            \"price\": \"23416.10000000\",\n                            \"origQty\": \"0.00847000\",\n                            \"executedQty\": \"0.00000000\",\n                            \"cummulativeQuoteQty\": \"0.00000000\",\n                            \"status\": \"CANCELED\",\n                            \"timeInForce\": \"GTC\",\n                            \"type\": \"STOP_LOSS_LIMIT\",\n                            \"side\": \"SELL\",\n                            \"stopPrice\": \"23416.10000000\",\n                            \"selfTradePreventionMode\": \"NONE\"\n                        },\n                        {\n                            \"symbol\": \"BTCUSDT\",\n                            \"orderId\": 12569138902,\n                            \"orderListId\": 1274512,\n                            \"clientOrderId\": \"jLnZpj5enfMXTuhKB1d0us\",\n                            \"transactTime\": 1660801720215,\n                            \"price\": \"23416.10000000\",\n                            \"origQty\": \"0.00847000\",\n                            \"executedQty\": \"0.00000000\",\n                            \"cummulativeQuoteQty\": \"0.00000000\",\n                            \"status\": \"CANCELED\",\n                            \"timeInForce\": \"GTC\",\n                            \"type\": \"LIMIT_MAKER\",\n                            \"side\": \"SELL\",\n                            \"selfTradePreventionMode\": \"NONE\"\n                        }\n                    ]\n                },\n                \"rateLimits\": [\n                    {\n                        \"rateLimitType\": \"REQUEST_WEIGHT\",\n                        \"interval\": \"MINUTE\",\n                        \"intervalNum\": 1,\n                        \"limit\": 6000,\n                        \"count\": 1\n                    }\n                ]\n            }\n\n        \"\"\"\n        return self._ws_api_request_sync(\"orderList.cancel\", True, params)\n\n    def ws_get_oco_open_orders(self, **params):\n        \"\"\"Query current open OCO (One-Cancels-the-Other) order lists.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/testnet/web-socket-api/public-api-requests#current-open-order-lists-user_data\n\n        :param recvWindow: optional - Number of milliseconds after timestamp the request is valid for. Default 5000, max 60000\n        :type recvWindow: int\n        :param apiKey: required - Your API key\n        :type apiKey: str\n        :param signature: required - HMAC SHA256 signature\n        :type signature: str\n        :param timestamp: required - Current timestamp in milliseconds\n        :type timestamp: int\n\n        :returns: API response in JSON format with open OCO orders\n\n            {\n                \"id\": \"c5899911-d3f5-47b3-9b67-4c1342f2a7e1\",\n                \"status\": 200,\n                \"result\": [\n                    {\n                        \"orderListId\": 1274512,\n                        \"contingencyType\": \"OCO\",\n                        \"listStatusType\": \"EXEC_STARTED\",\n                        \"listOrderStatus\": \"EXECUTING\",\n                        \"listClientOrderId\": \"08985fedd9ea2cf6b28996\",\n                        \"transactionTime\": 1660801713793,\n                        \"symbol\": \"BTCUSDT\",\n                        \"orders\": [\n                            {\n                                \"symbol\": \"BTCUSDT\",\n                                \"orderId\": 12569138901,\n                                \"clientOrderId\": \"BqtFCj5odMoWtSqGk2X9tU\"\n                            },\n                            {\n                                \"symbol\": \"BTCUSDT\",\n                                \"orderId\": 12569138902,\n                                \"clientOrderId\": \"jLnZpj5enfMXTuhKB1d0us\"\n                            }\n                        ]\n                    }\n                ],\n                \"rateLimits\": [\n                    {\n                        \"rateLimitType\": \"REQUEST_WEIGHT\",\n                        \"interval\": \"MINUTE\",\n                        \"intervalNum\": 1,\n                        \"limit\": 6000,\n                        \"count\": 10\n                    }\n                ]\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        Weight: 10\n        Data Source: Memory\n        \"\"\"\n        return self._ws_api_request_sync(\"openOrderLists.status\", True, params)\n\n    def ws_create_sor_order(self, **params):\n        \"\"\"Place a new order using Smart Order Routing (SOR).\n\n        https://developers.binance.com/docs/binance-spot-api-docs/testnet/web-socket-api/public-api-requests#place-new-order-using-sor-trade\n\n        :param symbol: required - Trading symbol, e.g. BTCUSDT\n        :type symbol: str\n        :param side: required - Order side: BUY or SELL\n        :type side: str\n        :param type: required - Order type: LIMIT or MARKET\n        :type type: str\n        :param quantity: required - Order quantity\n        :type quantity: float\n        :param timeInForce: required for LIMIT orders - Time in force: GTC, IOC, FOK\n        :type timeInForce: str\n        :param price: required for LIMIT orders - Order price\n        :type price: float\n        :param newClientOrderId: optional - Unique order ID. Automatically generated if not sent\n        :type newClientOrderId: str\n        :param newOrderRespType: optional - Response format: ACK, RESULT, FULL. MARKET and LIMIT orders use FULL by default\n        :type newOrderRespType: str\n        :param strategyId: optional - Arbitrary numeric value identifying the order within an order strategy\n        :type strategyId: int\n        :param strategyType: optional - Arbitrary numeric value identifying the order strategy. Values < 1000000 are reserved\n        :type strategyType: int\n        :param selfTradePreventionMode: optional - Supported values depend on exchange configuration: EXPIRE_TAKER, EXPIRE_MAKER, EXPIRE_BOTH, NONE\n        :type selfTradePreventionMode: str\n        :param recvWindow: optional - Number of milliseconds after timestamp the request is valid for. Default 5000, max 60000\n        :type recvWindow: int\n\n        :returns: Websocket message\n\n        .. code-block:: python\n            {\n                \"id\": \"3a4437e2-41a3-4c19-897c-9cadc5dce8b6\",\n                \"status\": 200,\n                \"result\": [\n                    {\n                        \"symbol\": \"BTCUSDT\",\n                        \"orderId\": 2,\n                        \"orderListId\": -1,\n                        \"clientOrderId\": \"sBI1KM6nNtOfj5tccZSKly\",\n                        \"transactTime\": 1689149087774,\n                        \"price\": \"31000.00000000\",\n                        \"origQty\": \"0.50000000\",\n                        \"executedQty\": \"0.50000000\",\n                        \"cummulativeQuoteQty\": \"14000.00000000\",\n                        \"status\": \"FILLED\",\n                        \"timeInForce\": \"GTC\",\n                        \"type\": \"LIMIT\",\n                        \"side\": \"BUY\",\n                        \"workingTime\": 1689149087774,\n                        \"fills\": [\n                            {\n                                \"matchType\": \"ONE_PARTY_TRADE_REPORT\",\n                                \"price\": \"28000.00000000\",\n                                \"qty\": \"0.50000000\",\n                                \"commission\": \"0.00000000\",\n                                \"commissionAsset\": \"BTC\",\n                                \"tradeId\": -1,\n                                \"allocId\": 0\n                            }\n                        ],\n                        \"workingFloor\": \"SOR\",\n                        \"selfTradePreventionMode\": \"NONE\",\n                        \"usedSor\": true\n                    }\n                ],\n                \"rateLimits\": [\n                    {\n                        \"rateLimitType\": \"REQUEST_WEIGHT\",\n                        \"interval\": \"MINUTE\",\n                        \"intervalNum\": 1,\n                        \"limit\": 6000,\n                        \"count\": 1\n                    }\n                ]\n            }\n\n        Notes:\n            - SOR only supports LIMIT and MARKET orders\n            - quoteOrderQty is not supported\n            - Weight: 1\n            - Data Source: Matching Engine\n        \"\"\"\n        return self._ws_api_request_sync(\"sor.order.place\", True, params)\n\n    def ws_create_test_sor_order(self, **params):\n        \"\"\"Test new order creation using Smart Order Routing (SOR).\n        Creates and validates a new order but does not send it into the matching engine.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/testnet/web-socket-api/public-api-requests#test-new-order-using-sor-trade\n\n        :param symbol: required - Trading symbol, e.g. BTCUSDT\n        :type symbol: str\n        :param side: required - Order side: BUY or SELL\n        :type side: str\n        :param type: required - Order type: LIMIT or MARKET\n        :type type: str\n        :param quantity: required - Order quantity\n        :type quantity: float\n        :param timeInForce: required for LIMIT orders - Time in force: GTC, IOC, FOK\n        :type timeInForce: str\n        :param price: required for LIMIT orders - Order price\n        :type price: float\n        :param newClientOrderId: optional - Unique order ID. Generated automatically if not sent\n        :type newClientOrderId: str\n        :param strategyId: optional - Arbitrary numeric value identifying the order within an order strategy\n        :type strategyId: int\n        :param strategyType: optional - Arbitrary numeric value identifying the order strategy. Values < 1000000 are reserved\n        :type strategyType: int\n        :param selfTradePreventionMode: optional - EXPIRE_TAKER, EXPIRE_MAKER, EXPIRE_BOTH, NONE\n        :type selfTradePreventionMode: str\n        :param computeCommissionRates: optional - Calculate commission rates. Default: False\n        :type computeCommissionRates: bool\n\n        :returns: Websocket message\n\n        Without computeCommissionRates:\n\n        .. code-block:: python\n\n            {\n                \"id\": \"3a4437e2-41a3-4c19-897c-9cadc5dce8b6\",\n                \"status\": 200,\n                \"result\": {},\n                \"rateLimits\": [\n                    {\n                        \"rateLimitType\": \"REQUEST_WEIGHT\",\n                        \"interval\": \"MINUTE\",\n                        \"intervalNum\": 1,\n                        \"limit\": 6000,\n                        \"count\": 1\n                    }\n                ]\n            }\n\n        With computeCommissionRates:\n\n        .. code-block:: python\n\n            {\n                \"id\": \"3a4437e2-41a3-4c19-897c-9cadc5dce8b6\",\n                \"status\": 200,\n                \"result\": {\n                    \"standardCommissionForOrder\": {\n                        \"maker\": \"0.00000112\",\n                        \"taker\": \"0.00000114\"\n                    },\n                    \"taxCommissionForOrder\": {\n                        \"maker\": \"0.00000112\",\n                        \"taker\": \"0.00000114\"\n                    },\n                    \"discount\": {\n                        \"enabledForAccount\": true,\n                        \"enabledForSymbol\": true,\n                        \"discountAsset\": \"BNB\",\n                        \"discount\": \"0.25\"\n                    }\n                },\n                \"rateLimits\": [...]\n            }\n\n        Notes:\n            - SOR only supports LIMIT and MARKET orders\n            - quoteOrderQty is not supported\n            - Weight: 1 (without computeCommissionRates), 20 (with computeCommissionRates)\n            - Data Source: Memory\n        \"\"\"\n        return self._ws_api_request_sync(\"sor.order.test\", True, params)\n\n    def ws_get_account(self, **params):\n        \"\"\"Get current account information.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/testnet/web-socket-api/public-api-requests#account-information-user_data\n\n        :param omitZeroBalances: optional - When set to true, emits only the non-zero balances of an account. Default: false\n        :type omitZeroBalances: bool\n        :param recvWindow: optional - The value cannot be greater than 60000\n        :type recvWindow: int\n\n        :returns: Websocket message\n\n        .. code-block:: python\n\n            {\n                \"makerCommission\": 15,\n                \"takerCommission\": 15,\n                \"buyerCommission\": 0,\n                \"sellerCommission\": 0,\n                \"canTrade\": true,\n                \"canWithdraw\": true,\n                \"canDeposit\": true,\n                \"commissionRates\": {\n                    \"maker\": \"0.00150000\",\n                    \"taker\": \"0.00150000\",\n                    \"buyer\": \"0.00000000\",\n                    \"seller\": \"0.00000000\"\n                },\n                \"brokered\": false,\n                \"requireSelfTradePrevention\": false,\n                \"preventSor\": false,\n                \"updateTime\": 1660801833000,\n                \"accountType\": \"SPOT\",\n                \"balances\": [\n                    {\n                        \"asset\": \"BNB\",\n                        \"free\": \"0.00000000\",\n                        \"locked\": \"0.00000000\"\n                    },\n                    {\n                        \"asset\": \"BTC\",\n                        \"free\": \"1.34471120\",\n                        \"locked\": \"0.08600000\"\n                    }\n                ],\n                \"permissions\": [\n                    \"SPOT\"\n                ],\n                \"uid\": 354937868\n            }\n\n        Notes:\n            - Weight: 20\n            - Data Source: Memory => Database\n        \"\"\"\n        return self._ws_api_request_sync(\"account.status\", True, params)\n\n    def ws_get_account_rate_limits_orders(self, **params):\n        \"\"\"Query your current unfilled order count for all intervals.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/testnet/web-socket-api/public-api-requests#account-unfilled-order-count-user_data\n\n        :param recvWindow: optional - The value cannot be greater than 60000\n        :type recvWindow: int\n\n        :returns: Websocket response\n\n        .. code-block:: python\n\n            {\n                \"result\": [\n                    {\n                        \"rateLimitType\": \"ORDERS\",\n                        \"interval\": \"SECOND\",\n                        \"intervalNum\": 10,\n                        \"limit\": 50,\n                        \"count\": 0\n                    },\n                    {\n                        \"rateLimitType\": \"ORDERS\",\n                        \"interval\": \"DAY\",\n                        \"intervalNum\": 1,\n                        \"limit\": 160000,\n                        \"count\": 0\n                    }\n                ],\n                \"id\": \"d3783d8d-f8d1-4d2c-b8a0-b7596af5a664\"\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        Notes:\n            - Weight: 40\n            - Data Source: Memory\n        \"\"\"\n        return self._ws_api_request_sync(\"account.rateLimits.orders\", True, params)\n\n    def ws_get_all_orders(self, **params):\n        \"\"\"Query information about all your orders – active, canceled, filled – filtered by time range.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/testnet/web-socket-api/public-api-requests#account-order-history-user_data\n\n        :param symbol: STRING - Required\n        :type symbol: str\n        :param orderId: optional - Order ID to begin at\n        :type orderId: int\n        :param startTime: optional\n        :type startTime: int\n        :param endTime: optional\n        :type endTime: int\n        :param limit: optional - Default 500; max 1000\n        :type limit: int\n        :param recvWindow: optional - The value cannot be greater than 60000\n        :type recvWindow: int\n\n        :returns: Websocket response\n\n        .. code-block:: python\n\n            {\n                \"id\": \"734235c2-13d2-4574-be68-723e818c08f3\",\n                \"status\": 200,\n                \"result\": [\n                    {\n                        \"symbol\": \"BTCUSDT\",\n                        \"orderId\": 12569099453,\n                        \"orderListId\": -1,\n                        \"clientOrderId\": \"4d96324ff9d44481926157\",\n                        \"price\": \"23416.10000000\",\n                        \"origQty\": \"0.00847000\",\n                        \"executedQty\": \"0.00847000\",\n                        \"cummulativeQuoteQty\": \"198.33521500\",\n                        \"status\": \"FILLED\",\n                        \"timeInForce\": \"GTC\",\n                        \"type\": \"LIMIT\",\n                        \"side\": \"SELL\",\n                        \"stopPrice\": \"0.00000000\",\n                        \"icebergQty\": \"0.00000000\",\n                        \"time\": 1660801715639,\n                        \"updateTime\": 1660801717945,\n                        \"isWorking\": true,\n                        \"workingTime\": 1660801715639,\n                        \"origQuoteOrderQty\": \"0.00000000\",\n                        \"selfTradePreventionMode\": \"NONE\",\n                        \"preventedMatchId\": 0,            // Only appears if order expired due to STP\n                        \"preventedQuantity\": \"1.200000\"   // Only appears if order expired due to STP\n                    }\n                ]\n            }\n\n        Notes:\n            - Weight: 20\n            - Data Source: Database\n            - If startTime and/or endTime are specified, orderId is ignored\n            - Orders are filtered by time of the last execution status update\n            - If orderId is specified, return orders with order ID >= orderId\n            - If no condition is specified, the most recent orders are returned\n            - For some historical orders the cummulativeQuoteQty response field may be negative\n            - The time between startTime and endTime can't be longer than 24 hours\n        \"\"\"\n        return self._ws_api_request_sync(\"allOrders\", True, params)\n\n    def ws_get_my_trades(self, **params):\n        \"\"\"Query information about your trades, filtered by time range.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/testnet/web-socket-api/public-api-requests#account-trade-history-user_data\n\n        :param symbol: STRING - Required\n        :type symbol: str\n        :param orderId: optional - Get trades for a specific order\n        :type orderId: int\n        :param startTime: optional\n        :type startTime: int\n        :param endTime: optional\n        :type endTime: int\n        :param fromId: optional - Trade ID to fetch from\n        :type fromId: int\n        :param limit: optional - Default 500; max 1000\n        :type limit: int\n        :param recvWindow: optional - The value cannot be greater than 60000\n        :type recvWindow: int\n\n        :returns: Websocket response\n\n            .. code-block:: python\n\n                [\n                    {\n                        \"symbol\": \"BTCUSDT\",\n                        \"id\": 1650422481,\n                        \"orderId\": 12569099453,\n                        \"orderListId\": -1,\n                        \"price\": \"23416.10000000\",\n                        \"qty\": \"0.00635000\",\n                        \"quoteQty\": \"148.69223500\",\n                        \"commission\": \"0.00000000\",\n                        \"commissionAsset\": \"BNB\",\n                        \"time\": 1660801715793,\n                        \"isBuyer\": false,\n                        \"isMaker\": true,\n                        \"isBestMatch\": true\n                    }\n                ]\n\n        Notes:\n            - Weight: 20\n            - Data Source: Memory => Database\n            - If fromId is specified, return trades with trade ID >= fromId\n            - If startTime and/or endTime are specified, trades are filtered by execution time (time)\n            - fromId cannot be used together with startTime and endTime\n            - If orderId is specified, only trades related to that order are returned\n            - startTime and endTime cannot be used together with orderId\n            - If no condition is specified, the most recent trades are returned\n            - The time between startTime and endTime can't be longer than 24 hours\n        \"\"\"\n        return self._ws_api_request_sync(\"myTrades\", True, params)\n\n    def ws_get_prevented_matches(self, **params):\n        \"\"\"Displays the list of orders that were expired due to STP (Self-Trade Prevention).\n\n        https://developers.binance.com/docs/binance-spot-api-docs/testnet/web-socket-api/public-api-requests#account-prevented-matches-user_data\n\n        :param symbol: STRING - Required\n        :type symbol: str\n        :param preventedMatchId: optional - Get specific prevented match by ID\n        :type preventedMatchId: int\n        :param orderId: optional - Get prevented matches for specific order\n        :type orderId: int\n        :param fromPreventedMatchId: optional - Get prevented matches from this ID\n        :type fromPreventedMatchId: int\n        :param limit: optional - Default 500; max 1000\n        :type limit: int\n        :param recvWindow: optional - The value cannot be greater than 60000\n        :type recvWindow: int\n\n        :returns: Websocket response\n\n        .. code-block:: python\n            {\n                \"symbol\": \"BTCUSDT\",            # Trading pair\n                \"preventedMatchId\": 1,          # Unique ID for prevented match\n                \"takerOrderId\": 5,              # Order ID of the taker order\n                \"makerSymbol\": \"BTCUSDT\",       # Symbol of maker order\n                \"makerOrderId\": 3,              # Order ID of maker order\n                \"tradeGroupId\": 1,              # Trade group ID\n                \"selfTradePreventionMode\": \"EXPIRE_MAKER\", # STP mode used\n                \"price\": \"1.100000\",            # Price level where match was prevented\n                \"makerPreventedQuantity\": \"1.300000\", # Quantity that was prevented\n                \"transactTime\": 1669101687094   # Time of prevention\n            }\n\n        Supported parameter combinations:\n            - symbol + preventedMatchId\n            - symbol + orderId\n            - symbol + orderId + fromPreventedMatchId (limit defaults to 500)\n            - symbol + orderId + fromPreventedMatchId + limit\n\n        Weight:\n            - 2 if symbol is invalid\n            - 2 when querying by preventedMatchId\n            - 20 when querying by orderId\n\n        Data Source: Database\n        \"\"\"\n        return self._ws_api_request_sync(\"myPreventedMatches\", True, params)\n\n    def ws_get_allocations(self, **params):\n        \"\"\"Get information about orders that were expired due to STP (Self-Trade Prevention).\n\n        https://developers.binance.com/docs/binance-spot-api-docs/testnet/web-socket-api/public-api-requests#account-prevented-matches-user_data\n\n        :param symbol: STRING - Required - Trading symbol\n        :type symbol: str\n        :param preventedMatchId: LONG - Optional - Get specific prevented match by ID\n        :type preventedMatchId: int\n        :param orderId: LONG - Optional - Get prevented matches for specific order\n        :type orderId: int\n        :param fromPreventedMatchId: LONG - Optional - Get prevented matches from this ID\n        :type fromPreventedMatchId: int\n        :param limit: INT - Optional - Default 500; max 1000\n        :type limit: int\n        :param recvWindow: LONG - Optional - The value cannot be greater than 60000\n        :type recvWindow: int\n        :param timestamp: LONG - Required\n        :type timestamp: int\n\n        :returns: API response\n\n        .. code-block:: python\n            {\n                \"symbol\": \"BTCUSDT\",\n                \"preventedMatchId\": 1,\n                \"takerOrderId\": 5,\n                \"makerSymbol\": \"BTCUSDT\",\n                \"makerOrderId\": 3,\n                \"tradeGroupId\": 1,\n                \"selfTradePreventionMode\": \"EXPIRE_MAKER\",\n                \"price\": \"1.100000\",\n                \"makerPreventedQuantity\": \"1.300000\",\n                \"transactTime\": 1669101687094\n            }\n\n        Supported parameter combinations:\n            - symbol + preventedMatchId\n            - symbol + orderId\n            - symbol + orderId + fromPreventedMatchId (limit defaults to 500)\n            - symbol + orderId + fromPreventedMatchId + limit\n\n        Weight:\n            - 2 if symbol is invalid\n            - 2 when querying by preventedMatchId\n            - 20 when querying by orderId\n\n        Data Source: Database\n        \"\"\"\n        return self._ws_api_request_sync(\"myAllocations\", True, params)\n\n    def ws_get_commission_rates(self, **params):\n        \"\"\"Get current account commission rates for a symbol.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/testnet/web-socket-api/public-api-requests#account-commission-rates-user_data\n\n        :param symbol: STRING - Required - Trading symbol\n        :type symbol: str\n        :param recvWindow: LONG - Optional - The value cannot be greater than 60000\n        :type recvWindow: int\n\n        :returns: API response dict with commission rates:\n\n            {\n                \"symbol\": \"BTCUSDT\",\n                \"standardCommission\": {           # Standard commission rates on trades\n                    \"maker\": \"0.00000010\",\n                    \"taker\": \"0.00000020\",\n                    \"buyer\": \"0.00000030\",\n                    \"seller\": \"0.00000040\"\n                },\n                \"taxCommission\": {               # Tax commission rates on trades\n                    \"maker\": \"0.00000112\",\n                    \"taker\": \"0.00000114\",\n                    \"buyer\": \"0.00000118\",\n                    \"seller\": \"0.00000116\"\n                },\n                \"discount\": {                    # Discount on standard commissions when paying in BNB\n                    \"enabledForAccount\": true,\n                    \"enabledForSymbol\": true,\n                    \"discountAsset\": \"BNB\",\n                    \"discount\": \"0.75000000\"     # Standard commission reduction rate when paying in BNB\n                }\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        Weight: 20\n\n        Data Source: Database\n        \"\"\"\n        return self._ws_api_request_sync(\"account.commission\", True, params)\n\n    def ws_get_order_book(self, **params):\n        \"\"\"Get current order book for a symbol.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/testnet/web-socket-api/public-api-requests#order-book\n\n        Note that this request returns limited market depth. If you need to continuously monitor\n        order book updates, consider using WebSocket Streams:\n        - <symbol>@depth<levels>\n        - <symbol>@depth\n\n        You can use `depth` request together with `<symbol>@depth` streams to maintain a local order book.\n\n        :param symbol: STRING - Required - Trading symbol\n        :type symbol: str\n        :param limit: INT - Optional - Default 100; max 5000\n        :type limit: int\n\n        :returns: Websocket message\n\n            {\n                \"lastUpdateId\": 2731179239,\n                \"bids\": [                // Bid levels sorted from highest to lowest price\n                    [\n                        \"0.01379900\",   // Price level\n                        \"3.43200000\"    // Quantity\n                    ],\n                    ...\n                ],\n                \"asks\": [                // Ask levels sorted from lowest to highest price\n                    [\n                        \"0.01380000\",   // Price level\n                        \"5.91700000\"    // Quantity\n                    ],\n                    ...\n                ]\n            }\n\n        Weight: Adjusted based on limit:\n            - 1-100: 5\n            - 101-500: 25\n            - 501-1000: 50\n            - 1001-5000: 250\n\n        Data Source: Memory\n        \"\"\"\n        return self._ws_api_request_sync(\"depth\", False, params)\n\n    def ws_get_recent_trades(self, **params):\n        \"\"\"Get recent trades for a symbol.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/testnet/web-socket-api/public-api-requests#recent-trades\n\n        If you need access to real-time trading activity, please consider using WebSocket Streams:\n        - <symbol>@trade\n\n        :param symbol: STRING - Required - Trading symbol\n        :type symbol: str\n        :param limit: INT - Optional - Default 500; max 1000\n        :type limit: int\n\n        :returns: API response\n\n        .. code-block:: python\n            {\n                \"id\": \"409a20bd-253d-41db-a6dd-687862a5882f\",\n                \"status\": 200,\n                \"result\": [\n                    {\n                        \"id\": 194686783,              # Trade ID\n                        \"price\": \"0.01361000\",        # Price\n                        \"qty\": \"0.01400000\",          # Quantity\n                        \"quoteQty\": \"0.00019054\",     # Quote quantity\n                        \"time\": 1660009530807,        # Trade time\n                        \"isBuyerMaker\": true,         # Was the buyer the maker?\n                        \"isBestMatch\": true           # Was this the best price match?\n                    }\n                ]\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        Weight: 25\n        Data Source: Memory\n        \"\"\"\n        return self._ws_api_request_sync(\"trades.recent\", False, params)\n\n    def ws_get_historical_trades(self, **params):\n        \"\"\"Get historical trades.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/testnet/web-socket-api/public-api-requests#historical-trades\n\n        :param symbol: STRING - Required - Trading symbol\n        :type symbol: str\n        :param fromId: INT - Optional - Trade ID to begin at\n        :type fromId: int\n        :param limit: INT - Optional - Default 500; max 1000\n        :type limit: int\n\n        :returns: Websocket message\n\n        .. code-block:: python\n\n            {\n                \"id\": \"cffc9c7d-4efc-4ce0-b587-6b87448f052a\",\n                \"result\": [\n                    {\n                        \"id\": 0,                      # Trade ID\n                        \"price\": \"0.00005000\",        # Price\n                        \"qty\": \"40.00000000\",         # Quantity\n                        \"quoteQty\": \"0.00200000\",     # Quote quantity\n                        \"time\": 1500004800376,        # Trade time\n                        \"isBuyerMaker\": true,         # Was the buyer the maker?\n                        \"isBestMatch\": true           # Was this the best price match?\n                    }\n                ]\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        Notes:\n            - If fromId is not specified, the most recent trades are returned\n\n        Weight: 25\n        Data Source: Database\n        \"\"\"\n        return self._ws_api_request_sync(\"trades.historical\", False, params)\n\n    def ws_get_aggregate_trades(self, **params):\n        \"\"\"Get aggregate trades.\n\n        An aggregate trade represents one or more individual trades that fill at the same time,\n        from the same taker order, with the same price.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/testnet/web-socket-api/public-api-requests#aggregate-trades\n\n        :param symbol: STRING - Required - Trading symbol\n        :type symbol: str\n        :param fromId: INT - Optional - Aggregate trade ID to begin at\n        :type fromId: int\n        :param startTime: INT - Optional - Start time in milliseconds\n        :type startTime: int\n        :param endTime: INT - Optional - End time in milliseconds\n        :type endTime: int\n        :param limit: INT - Optional - Default 500; max 1000\n        :type limit: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"id\": \"...\",\n                \"status\": 200,\n                \"result\": [\n                    {\n                        \"a\": 50000000,        # Aggregate trade ID\n                        \"p\": \"0.00274100\",    # Price\n                        \"q\": \"57.19000000\",   # Quantity\n                        \"f\": 59120167,        # First trade ID\n                        \"l\": 59120170,        # Last trade ID\n                        \"T\": 1565877971222,   # Timestamp\n                        \"m\": true,            # Was the buyer the maker?\n                        \"M\": true             # Was the trade the best price match?\n                    }\n                ]\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        Notes:\n            - If fromId is specified, return aggtrades with aggregate trade ID >= fromId.\n            Use fromId and limit to page through all aggtrades.\n            - If startTime and/or endTime are specified, aggtrades are filtered by execution time (T).\n            fromId cannot be used together with startTime and endTime.\n            - If no condition is specified, the most recent aggregate trades are returned.\n            - For real-time updates, consider using WebSocket Streams: <symbol>@aggTrade\n            - For historical data, consider using data.binance.vision\n\n        Weight: 2\n        Data Source: Database\n        \"\"\"\n        return self._ws_api_request_sync(\"trades.aggregate\", False, params)\n\n    def ws_get_klines(self, **params):\n        \"\"\"Get klines (candlestick bars).\n\n        Klines are uniquely identified by their open & close time.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/testnet/web-socket-api/public-api-requests#klines\n\n        :param symbol: STRING - Required - Trading symbol\n        :type symbol: str\n        :param interval: ENUM - Required - Kline interval\n        :type interval: str\n        :param startTime: INT - Optional - Start time in milliseconds\n        :type startTime: int\n        :param endTime: INT - Optional - End time in milliseconds\n        :type endTime: int\n        :param timeZone: STRING - Optional - Default: 0 (UTC)\n        :type timeZone: str\n        :param limit: INT - Optional - Default 500; max 1000\n        :type limit: int\n\n        Supported kline intervals:\n            - seconds: 1s\n            - minutes: 1m, 3m, 5m, 15m, 30m\n            - hours: 1h, 2h, 4h, 6h, 8h, 12h\n            - days: 1d, 3d\n            - weeks: 1w\n            - months: 1M\n\n        Notes:\n            - If startTime/endTime not specified, returns most recent klines\n            - Supported timeZone values:\n                - Hours and minutes (e.g. \"-1:00\", \"05:45\")\n                - Only hours (e.g. \"0\", \"8\", \"4\")\n                - Accepted range is strictly [-12:00 to +14:00] inclusive\n            - If timeZone provided, kline intervals interpreted in that timezone instead of UTC\n            - startTime and endTime always interpreted in UTC, regardless of timeZone\n            - For real-time updates, consider using WebSocket Streams: <symbol>@kline_<interval>\n            - For historical data, consider using data.binance.vision\n\n        Weight: 2\n        Data Source: Database\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"id\": \"1dbbeb56-8eea-466a-8f6e-86bdcfa2fc0b\",\n                \"status\": 200,\n                \"result\": [\n                    [\n                        1655971200000,      # Kline open time\n                        \"0.01086000\",       # Open price\n                        \"0.01086600\",       # High price\n                        \"0.01083600\",       # Low price\n                        \"0.01083800\",       # Close price\n                        \"2290.53800000\",    # Volume\n                        1655974799999,      # Kline close time\n                        \"24.85074442\",      # Quote asset volume\n                        2283,               # Number of trades\n                        \"1171.64000000\",    # Taker buy base asset volume\n                        \"12.71225884\",      # Taker buy quote asset volume\n                        \"0\"                 # Unused field, ignore\n                    ]\n                ]\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n        \"\"\"\n        return self._ws_api_request_sync(\"klines\", False, params)\n\n    def ws_get_uiKlines(self, **params):\n        \"\"\"Get klines (candlestick bars) optimized for presentation.\n\n        This request is similar to klines, having the same parameters and response.\n        uiKlines return modified kline data, optimized for presentation of candlestick charts.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/testnet/web-socket-api/public-api-requests#ui-klines\n\n        :param symbol: STRING - Required - Trading symbol\n        :type symbol: str\n        :param interval: ENUM - Required - Kline interval\n        :type interval: str\n        :param startTime: INT - Optional - Start time in milliseconds\n        :type startTime: int\n        :param endTime: INT - Optional - End time in milliseconds\n        :type endTime: int\n        :param timeZone: STRING - Optional - Default: 0 (UTC)\n        :type timeZone: str\n        :param limit: INT - Optional - Default 500; max 1000\n        :type limit: int\n\n        Supported kline intervals:\n            - seconds: 1s\n            - minutes: 1m, 3m, 5m, 15m, 30m\n            - hours: 1h, 2h, 4h, 6h, 8h, 12h\n            - days: 1d, 3d\n            - weeks: 1w\n            - months: 1M\n\n        Notes:\n            - If startTime/endTime not specified, returns most recent klines\n            - Supported timeZone values:\n                - Hours and minutes (e.g. \"-1:00\", \"05:45\")\n                - Only hours (e.g. \"0\", \"8\", \"4\")\n                - Accepted range is strictly [-12:00 to +14:00] inclusive\n            - If timeZone provided, kline intervals are interpreted in that timezone instead of UTC\n            - startTime and endTime are always interpreted in UTC, regardless of timeZone\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"id\": \"b137468a-fb20-4c06-bd6b-625148eec958\",\n                \"result\": [\n                    [\n                        1655971200000,      # Kline open time\n                        \"0.01086000\",       # Open price\n                        \"0.01086600\",       # High price\n                        \"0.01083600\",       # Low price\n                        \"0.01083800\",       # Close price\n                        \"2290.53800000\",    # Volume\n                        1655974799999,      # Kline close time\n                        \"24.85074442\",      # Quote asset volume\n                        2283,               # Number of trades\n                        \"1171.64000000\",    # Taker buy base asset volume\n                        \"12.71225884\",      # Taker buy quote asset volume\n                        \"0\"                 # Unused field, ignore\n                    ]\n                ]\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n        \"\"\"\n        return self._ws_api_request_sync(\"uiKlines\", False, params)\n\n    def ws_get_avg_price(self, **params):\n        \"\"\"Get current average price for a symbol.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/testnet/web-socket-api/public-api-requests#current-average-price\n\n        :param symbol: STRING - Required - Trading symbol\n        :type symbol: str\n\n        :returns: Websocket message\n\n        .. code-block:: python\n            {\n                \"mins\": 5,                    # Average price interval (in minutes)\n                \"price\": \"9.35751834\",        # Average price\n                \"closeTime\": 1694061154503    # Last trade time\n            }\n\n        Weight: 2\n        \"\"\"\n        return self._ws_api_request_sync(\"avgPrice\", False, params)\n\n    def ws_get_ticker(self, **params):\n        \"\"\"Get 24-hour rolling window price change statistics.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/testnet/web-socket-api/public-api-requests#24hr-ticker-price-change-statistics\n\n        :param symbol: STRING - Optional - Query ticker for a single symbol\n        :type symbol: str\n        :param symbols: ARRAY of STRING - Optional - Query ticker for multiple symbols\n        :type symbols: list\n        :param type: ENUM - Optional - Ticker type: FULL (default) or MINI\n        :type type: str\n\n        Note:\n            - symbol and symbols cannot be used together\n            - If no symbol is specified, returns information about all symbols currently trading on the exchange\n\n        Weight:\n            Adjusted based on the number of requested symbols:\n            - 1-20 symbols: 2\n            - 21-100 symbols: 40\n            - 101 or more symbols: 80\n            - all symbols: 80\n\n        :returns: Websocket message\n\n        For a single symbol with type=FULL:\n        .. code-block:: python\n            {\n                \"symbol\": \"BNBBTC\",\n                \"priceChange\": \"0.00013900\",         # Absolute price change\n                \"priceChangePercent\": \"1.020\",       # Relative price change in percent\n                \"weightedAvgPrice\": \"0.01382453\",    # Quote volume divided by volume\n                \"prevClosePrice\": \"0.01362800\",      # Previous day's close price\n                \"lastPrice\": \"0.01376700\",           # Latest price\n                \"lastQty\": \"1.78800000\",            # Latest quantity\n                \"bidPrice\": \"0.01376700\",           # Best bid price\n                \"bidQty\": \"4.64600000\",            # Best bid quantity\n                \"askPrice\": \"0.01376800\",           # Best ask price\n                \"askQty\": \"14.31400000\",           # Best ask quantity\n                \"openPrice\": \"0.01362800\",          # Open price 24 hours ago\n                \"highPrice\": \"0.01414900\",          # Highest price in the last 24 hours\n                \"lowPrice\": \"0.01346600\",           # Lowest price in the last 24 hours\n                \"volume\": \"69412.40500000\",         # Trading volume in base asset\n                \"quoteVolume\": \"959.59411487\",      # Trading volume in quote asset\n                \"openTime\": 1660014164909,          # Open time for 24hr rolling window\n                \"closeTime\": 1660100564909,         # Close time for 24hr rolling window\n                \"firstId\": 194696115,               # First trade ID\n                \"lastId\": 194968287,                # Last trade ID\n                \"count\": 272173                     # Number of trades\n            }\n\n        For a single symbol with type=MINI:\n        .. code-block:: python\n            {\n                \"symbol\": \"BNBBTC\",\n                \"openPrice\": \"0.01362800\",\n                \"highPrice\": \"0.01414900\",\n                \"lowPrice\": \"0.01346600\",\n                \"lastPrice\": \"0.01376700\",\n                \"volume\": \"69412.40500000\",\n                \"quoteVolume\": \"959.59411487\",\n                \"openTime\": 1660014164909,\n                \"closeTime\": 1660100564909,\n                \"firstId\": 194696115,\n                \"lastId\": 194968287,\n                \"count\": 272173\n            }\n\n        \"\"\"\n        return self._ws_api_request_sync(\"ticker.24hr\", False, params)\n\n    def ws_get_trading_day_ticker(self, **params):\n        \"\"\"Price change statistics for a trading day.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/testnet/web-socket-api/public-api-requests#trading-day-ticker\n\n        :param symbol: STRING - Optional - Query ticker of a single symbol\n        :type symbol: str\n        :param symbols: ARRAY of STRING - Optional - Query ticker for multiple symbols\n        :type symbols: list\n        :param timeZone: STRING - Optional - Default: 0 (UTC)\n            Supported values:\n            - Hours and minutes (e.g. \"-1:00\", \"05:45\")\n            - Only hours (e.g. \"0\", \"8\", \"4\")\n            - Accepted range is strictly [-12:00 to +14:00] inclusive\n        :type timeZone: str\n        :param type: ENUM - Optional - FULL (default) or MINI\n        :type type: str\n\n        :returns: Websocket message\n\n        Response FULL type example:\n        {\n            \"symbol\": \"BTCUSDT\",\n            \"priceChange\": \"-83.13000000\",           # Absolute price change\n            \"priceChangePercent\": \"-0.317\",          # Relative price change in percent\n            \"weightedAvgPrice\": \"26234.58803036\",    # quoteVolume / volume\n            \"openPrice\": \"26304.80000000\",\n            \"highPrice\": \"26397.46000000\",\n            \"lowPrice\": \"26088.34000000\",\n            \"lastPrice\": \"26221.67000000\",\n            \"volume\": \"18495.35066000\",              # Volume in base asset\n            \"quoteVolume\": \"485217905.04210480\",\n            \"openTime\": 1695686400000,\n            \"closeTime\": 1695772799999,\n            \"firstId\": 3220151555,\n            \"lastId\": 3220849281,\n            \"count\": 697727\n        }\n\n        Response MINI type example:\n        {\n            \"symbol\": \"BTCUSDT\",\n            \"openPrice\": \"26304.80000000\",\n            \"highPrice\": \"26397.46000000\",\n            \"lowPrice\": \"26088.34000000\",\n            \"lastPrice\": \"26221.67000000\",\n            \"volume\": \"18495.35066000\",              # Volume in base asset\n            \"quoteVolume\": \"485217905.04210480\",     # Volume in quote asset\n            \"openTime\": 1695686400000,\n            \"closeTime\": 1695772799999,\n            \"firstId\": 3220151555,                   # Trade ID of the first trade in the interval\n            \"lastId\": 3220849281,                    # Trade ID of the last trade in the interval\n            \"count\": 697727                          # Number of trades in the interval\n        }\n\n        Weight:\n            - 4 for each requested symbol\n            - Weight caps at 200 once number of symbols > 50\n        \"\"\"\n        return self._ws_api_request_sync(\"ticker.tradingDay\", False, params)\n\n    def ws_get_symbol_ticker_window(self, **params):\n        \"\"\"Get rolling window price change statistics.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/testnet/web-socket-api/public-api-requests#rolling-window-price-change-statistics\n\n        :param symbol: STRING - Optional - Query ticker of a single symbol\n        :type symbol: str\n        :param symbols: ARRAY of STRING - Optional - Query ticker for multiple symbols\n        :type symbols: list\n        :param windowSize: STRING - Required - Supported windowSize values:\n            - 1h, 2h, 4h, 6h, 12h\n            - 1d, 2d, 3d, 4d, 5d, 6d, 7d, 14d, 30d\n        :type windowSize: str\n        :param type: ENUM - Optional - FULL (default) or MINI\n        :type type: str\n\n        :returns: Websocket message\n\n        With symbol parameter:\n        .. code-block:: python\n            {\n                \"symbol\": \"BTCUSDT\",\n                \"priceChange\": \"-83.13000000\",         # Absolute price change\n                \"priceChangePercent\": \"-0.317\",        # Relative price change in percent\n                \"weightedAvgPrice\": \"26234.58803036\",  # quoteVolume / volume\n                \"openPrice\": \"26304.80000000\",\n                \"highPrice\": \"26397.46000000\",\n                \"lowPrice\": \"26088.34000000\",\n                \"lastPrice\": \"26221.67000000\",\n                \"volume\": \"18495.35066000\",            # Volume in base asset\n                \"quoteVolume\": \"485217905.04210480\",   # Volume in quote asset\n                \"openTime\": 1695686400000,\n                \"closeTime\": 1695772799999,\n                \"firstId\": 3220151555,                 # Trade ID of first trade in the interval\n                \"lastId\": 3220849281,                  # Trade ID of last trade in the interval\n                \"count\": 697727                        # Number of trades in the interval\n            }\n\n        With symbols parameter:\n        .. code-block:: python\n            [\n                {\n                    # Same fields as above\n                },\n                {\n                    # Same fields as above for next symbol\n                }\n            ]\n\n        For MINI type response:\n        .. code-block:: python\n            {\n                \"symbol\": \"BTCUSDT\",\n                \"openPrice\": \"26304.80000000\",\n                \"highPrice\": \"26397.46000000\",\n                \"lowPrice\": \"26088.34000000\",\n                \"lastPrice\": \"26221.67000000\",\n                \"volume\": \"18495.35066000\",\n                \"quoteVolume\": \"485217905.04210480\",\n                \"openTime\": 1695686400000,\n                \"closeTime\": 1695772799999,\n                \"firstId\": 3220151555,\n                \"lastId\": 3220849281,\n                \"count\": 697727\n            }\n\n        Weight:\n            - 4 for each requested symbol\n            - Weight caps at 200 once number of symbols > 50\n        \"\"\"\n        return self._ws_api_request_sync(\"ticker\", False, params)\n\n    def ws_get_symbol_ticker(self, **params):\n        \"\"\"Get latest price for a symbol or symbols.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/testnet/web-socket-api/public-api-requests#symbol-price-ticker\n\n        :param symbol: STRING - Optional - Query ticker of a single symbol\n        :type symbol: str\n        :param symbols: ARRAY of STRING - Optional - Query ticker for multiple symbols\n        :type symbols: list\n\n        :returns: Websocket message\n\n        With symbol parameter:\n            {\n                \"symbol\": \"BNBBTC\",\n                \"price\": \"0.01361000\"\n            }\n\n            With symbols parameter:\n            [\n                {\n                    \"symbol\": \"BNBBTC\",\n                    \"price\": \"0.01361000\"\n                },\n                {\n                    \"symbol\": \"BTCUSDT\",\n                    \"price\": \"23440.91000000\"\n                }\n            ]\n\n        Weight:\n            - 1 for a single symbol\n            - 2 for up to 20 symbols\n            - 40 for 21 to 100 symbols\n            - 40 for all symbols\n        \"\"\"\n        return self._ws_api_request_sync(\"ticker.price\", False, params)\n\n    def ws_get_orderbook_ticker(self, **params):\n        \"\"\"Get the best price/quantity on the order book for a symbol or symbols.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/testnet/web-socket-api/public-api-requests#symbol-order-book-ticker\n\n        :param symbol: STRING - Optional - Query ticker of a single symbol\n        :type symbol: str\n        :param symbols: ARRAY of STRING - Optional - Query ticker for multiple symbols\n        :type symbols: list\n\n        :returns: Websocket response\n\n            With symbol parameter:\n            {\n                \"symbol\": \"BNBBTC\",\n                \"bidPrice\": \"0.01358000\",\n                \"bidQty\": \"0.95200000\",\n                \"askPrice\": \"0.01358100\",\n                \"askQty\": \"11.91700000\"\n            }\n\n            With symbols parameter:\n            [\n                {\n                    \"symbol\": \"BNBBTC\",\n                    \"bidPrice\": \"0.01358000\",\n                    \"bidQty\": \"0.95200000\",\n                    \"askPrice\": \"0.01358100\",\n                    \"askQty\": \"11.91700000\"\n                },\n                {\n                    \"symbol\": \"BTCUSDT\",\n                    \"bidPrice\": \"23440.90000000\",\n                    \"bidQty\": \"0.00200000\",\n                    \"askPrice\": \"23440.91000000\",\n                    \"askQty\": \"0.00200000\"\n                }\n            ]\n\n        Weight:\n            - 2 for a single symbol\n            - 4 for up to 100 symbols\n            - 40 for 101 or more symbols\n        \"\"\"\n        return self._ws_api_request_sync(\"ticker.book\", False, params)\n\n    def ws_ping(self, **params):\n        \"\"\"Test connectivity to the WebSocket API.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/testnet/web-socket-api/public-api-requests#test-connectivity\n\n        :returns: API response\n\n            {\n                \"id\": \"922bcc6e-9de8-440d-9e84-7c80933a8d0d\",\n                \"status\": 200,\n                \"result\": {},\n                \"rateLimits\": [\n                    {\n                        \"rateLimitType\": \"REQUEST_WEIGHT\",\n                        \"interval\": \"MINUTE\",\n                        \"intervalNum\": 1,\n                        \"limit\": 6000,\n                        \"count\": 1\n                    }\n                ]\n            }\n\n\n        Weight: 1\n        \"\"\"\n        return self._ws_api_request_sync(\"ping\", False, params)\n\n    def ws_get_time(self, **params):\n        \"\"\"Test connectivity to the WebSocket API and get the current server time.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/testnet/web-socket-api/public-api-requests#check-server-time\n\n        :returns: API response with server time\n\n            {\n                \"id\": \"187d3cb2-942d-484c-8271-4e2141bbadb1\",\n                \"status\": 200,\n                \"result\": {\n                    \"serverTime\": 1656400526260\n                },\n                \"rateLimits\": [\n                    {\n                        \"rateLimitType\": \"REQUEST_WEIGHT\",\n                        \"interval\": \"MINUTE\",\n                        \"intervalNum\": 1,\n                        \"limit\": 6000,\n                        \"count\": 1\n                    }\n                ]\n            }\n\n        Weight: 1\n        Data Source: Memory\n        \"\"\"\n        return self._ws_api_request_sync(\"time\", False, params)\n\n    def ws_get_exchange_info(self, **params):\n        \"\"\"Query current exchange trading rules, rate limits, and symbol information.\n\n        https://developers.binance.com/docs/binance-spot-api-docs/testnet/web-socket-api/public-api-requests#exchange-information\n\n        :param symbol: str - Filter by single symbol (optional)\n        :param symbols: list - Filter by multiple symbols (optional)\n        :param permissions: list or str - Filter symbols by permissions (optional)\n\n        :returns: API response containing exchange information including:\n            - Rate limits\n            - Exchange filters\n            - Symbol information including:\n                - Status\n                - Base/quote assets\n                - Order types allowed\n                - Filters (price, lot size, etc)\n                - Trading permissions\n                - Self-trade prevention modes\n\n            Example response:\n            {\n                \"timezone\": \"UTC\",\n                \"serverTime\": 1655969291181,\n                \"rateLimits\": [\n                    {\n                        \"rateLimitType\": \"REQUEST_WEIGHT\",\n                        \"interval\": \"MINUTE\",\n                        \"intervalNum\": 1,\n                        \"limit\": 6000\n                    },\n                    ...\n                ],\n                \"exchangeFilters\": [],\n                \"symbols\": [\n                    {\n                        \"symbol\": \"BTCUSDT\",\n                        \"status\": \"TRADING\",\n                        \"baseAsset\": \"BTC\",\n                        \"baseAssetPrecision\": 8,\n                        ...\n                    }\n                ]\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        Notes:\n            - Only one of symbol, symbols, permissions parameters can be specified\n            - Without parameters, displays all symbols with [\"SPOT\", \"MARGIN\", \"LEVERAGED\"] permissions\n            - To list all active symbols, explicitly request all permissions\n            - Permissions accepts either a list or single permission name (e.g. \"SPOT\")\n\n        Weight: 20\n        Data Source: Memory\n        \"\"\"\n        return self._ws_api_request_sync(\"exchangeInfo\", False, params)\n\n    ####################################################\n    # WS Futures Endpoints\n    ####################################################\n    def ws_futures_get_order_book(self, **params):\n        \"\"\"\n        Get the order book for a symbol\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/websocket-api\n        \"\"\"\n        return self._ws_futures_api_request_sync(\"depth\", False, params)\n\n    def ws_futures_get_all_tickers(self, **params):\n        \"\"\"\n        Latest price for a symbol or symbols\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/websocket-api/Symbol-Price-Ticker\n        \"\"\"\n        return self._ws_futures_api_request_sync(\"ticker.price\", False, params)\n\n    def ws_futures_get_order_book_ticker(self, **params):\n        \"\"\"\n        Best price/qty on the order book for a symbol or symbols.\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/websocket-api/Symbol-Order-Book-Ticker\n        \"\"\"\n        return self._ws_futures_api_request_sync(\"ticker.book\", False, params)\n\n    def ws_futures_create_order(self, **params):\n        \"\"\"\n        Send in a new order\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api\n        \"\"\"\n        # Check if this is a conditional order type that needs to use algo endpoint\n        order_type = params.get(\"type\", \"\").upper()\n        conditional_types = [\n            \"STOP\",\n            \"STOP_MARKET\",\n            \"TAKE_PROFIT\",\n            \"TAKE_PROFIT_MARKET\",\n            \"TRAILING_STOP_MARKET\",\n        ]\n\n        if order_type in conditional_types:\n            # Route to algo order endpoint\n            if \"clientAlgoId\" not in params:\n                params[\"clientAlgoId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n            # Remove newClientOrderId if it was added by default\n            params.pop(\"newClientOrderId\", None)\n            if \"algoType\" not in params:\n                params[\"algoType\"] = \"CONDITIONAL\"\n            # Convert stopPrice to triggerPrice for algo orders\n            if \"stopPrice\" in params and \"triggerPrice\" not in params:\n                params[\"triggerPrice\"] = params.pop(\"stopPrice\")\n            return self._ws_futures_api_request_sync(\"algoOrder.place\", True, params)\n        else:\n            # Use regular order endpoint\n            if \"newClientOrderId\" not in params:\n                params[\"newClientOrderId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n            return self._ws_futures_api_request_sync(\"order.place\", True, params)\n\n    def ws_futures_edit_order(self, **params):\n        \"\"\"\n        Edit an order\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api/Modify-Order\n        \"\"\"\n        return self._ws_futures_api_request_sync(\"order.modify\", True, params)\n\n    def ws_futures_cancel_order(self, **params):\n        \"\"\"\n        cancel an order\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api/Cancel-Order\n        \"\"\"\n        is_conditional = False\n        if \"algoId\" in params or \"clientAlgoId\" in params:\n            is_conditional = True\n\n        if is_conditional:\n            return self._ws_futures_api_request_sync(\"algoOrder.cancel\", True, params)\n        else:\n            return self._ws_futures_api_request_sync(\"order.cancel\", True, params)\n\n    def ws_futures_get_order(self, **params):\n        \"\"\"\n        Get an order\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api/Query-Order\n\n        Note: Algo/conditional orders cannot be queried via websocket API\n        \"\"\"\n        return self._ws_futures_api_request_sync(\"order.status\", True, params)\n\n    def ws_futures_v2_account_position(self, **params):\n        \"\"\"\n        Get current position information(only symbol that has position or open orders will be returned).\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api/Position-Info-V2\n        \"\"\"\n        return self._ws_futures_api_request_sync(\"v2/account.position\", True, params)\n\n    def ws_futures_account_position(self, **params):\n        \"\"\"\n        Get current position information.\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api/Position-Information\n        \"\"\"\n        return self._ws_futures_api_request_sync(\"account.position\", True, params)\n\n    def ws_futures_v2_account_balance(self, **params):\n        \"\"\"\n        Get current account information.\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api#api-description\n        \"\"\"\n        return self._ws_futures_api_request_sync(\"v2/account.balance\", True, params)\n\n    def ws_futures_account_balance(self, **params):\n        \"\"\"\n        Get current account information.\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api/Futures-Account-Balance\n        \"\"\"\n        return self._ws_futures_api_request_sync(\"account.balance\", True, params)\n\n    def ws_futures_v2_account_status(self, **params):\n        \"\"\"\n        Get current account information. User in single-asset/ multi-assets mode will see different value, see comments in response section for detail.\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api/Account-Information-V2\n        \"\"\"\n        return self._ws_futures_api_request_sync(\"v2/account.status\", True, params)\n\n    def ws_futures_account_status(self, **params):\n        \"\"\"\n        Get current account information. User in single-asset/ multi-assets mode will see different value, see comments in response section for detail.\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/account/websocket-api/Account-Information\n        \"\"\"\n        return self._ws_futures_api_request_sync(\"account.status\", True, params)\n\n    def ws_futures_create_algo_order(self, **params):\n        \"\"\"\n        Send in a new algo order (conditional order).\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api\n\n        :param symbol: required\n        :type symbol: str\n        :param side: required - BUY or SELL\n        :type side: str\n        :param type: required - STOP, TAKE_PROFIT, STOP_MARKET, TAKE_PROFIT_MARKET, TRAILING_STOP_MARKET\n        :type type: str\n        :param algoType: required - Only support CONDITIONAL\n        :type algoType: str\n        :param positionSide: optional - Default BOTH for One-way Mode; LONG or SHORT for Hedge Mode\n        :type positionSide: str\n        :param timeInForce: optional - IOC or GTC or FOK, default GTC\n        :type timeInForce: str\n        :param quantity: optional - Cannot be sent with closePosition=true\n        :type quantity: decimal\n        :param price: optional\n        :type price: decimal\n        :param triggerPrice: optional - Used with STOP, STOP_MARKET, TAKE_PROFIT, TAKE_PROFIT_MARKET\n        :type triggerPrice: decimal\n        :param workingType: optional - triggerPrice triggered by: MARK_PRICE, CONTRACT_PRICE. Default CONTRACT_PRICE\n        :type workingType: str\n        :param priceMatch: optional - only available for LIMIT/STOP/TAKE_PROFIT order\n        :type priceMatch: str\n        :param closePosition: optional - true or false; Close-All, used with STOP_MARKET or TAKE_PROFIT_MARKET\n        :type closePosition: bool\n        :param priceProtect: optional - \"TRUE\" or \"FALSE\", default \"FALSE\"\n        :type priceProtect: str\n        :param reduceOnly: optional - \"true\" or \"false\", default \"false\"\n        :type reduceOnly: str\n        :param activationPrice: optional - Used with TRAILING_STOP_MARKET orders\n        :type activationPrice: decimal\n        :param callbackRate: optional - Used with TRAILING_STOP_MARKET orders, min 0.1, max 10\n        :type callbackRate: decimal\n        :param clientAlgoId: optional - A unique id among open orders\n        :type clientAlgoId: str\n        :param selfTradePreventionMode: optional - EXPIRE_TAKER, EXPIRE_MAKER, EXPIRE_BOTH; default NONE\n        :type selfTradePreventionMode: str\n        :param goodTillDate: optional - order cancel time for timeInForce GTD\n        :type goodTillDate: int\n        :param newOrderRespType: optional - \"ACK\", \"RESULT\", default \"ACK\"\n        :type newOrderRespType: str\n        :param recvWindow: optional - the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: WS response\n\n        \"\"\"\n        if \"clientAlgoId\" not in params:\n            params[\"clientAlgoId\"] = self.CONTRACT_ORDER_PREFIX + self.uuid22()\n        return self._ws_futures_api_request_sync(\"algoOrder.place\", True, params)\n\n    def ws_futures_cancel_algo_order(self, **params):\n        \"\"\"\n        Cancel an active algo order.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/websocket-api\n\n        :param symbol: required\n        :type symbol: str\n        :param algoId: optional - Either algoId or clientAlgoId must be sent\n        :type algoId: int\n        :param clientAlgoId: optional - Either algoId or clientAlgoId must be sent\n        :type clientAlgoId: str\n        :param recvWindow: optional - the number of milliseconds the request is valid for\n        :type recvWindow: int\n\n        :returns: WS response\n\n        \"\"\"\n        return self._ws_futures_api_request_sync(\"algoOrder.cancel\", True, params)\n\n    ###############################################\n    ### Gift card api\n    ###############################################\n    def gift_card_fetch_token_limit(self, **params):\n        \"\"\"Verify which tokens are available for you to create Stablecoin-Denominated gift cards\n        https://developers.binance.com/docs/gift_card/market-data/Fetch-Token-Limit\n\n        :param baseToken: The token you want to pay, example: BUSD\n        :type baseToken: str\n        :return: api response\n        .. code-block:: python\n            {\n                \"code\": \"000000\",\n                \"message\": \"success\",\n                \"data\": [\n                    {\n                        \"coin\": \"BNB\",\n                        \"fromMin\": \"0.01\",\n                        \"fromMax\": \"1\"\n                    }\n                ],\n                \"success\": true\n            }\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"giftcard/buyCode/token-limit\", signed=True, data=params\n        )\n\n    def gift_card_fetch_rsa_public_key(self, **params):\n        \"\"\"This API is for fetching the RSA Public Key. This RSA Public key will be used to encrypt the card code.\n\n        Important Note:\n        The RSA Public key fetched is valid only for the current day.\n\n        https://developers.binance.com/docs/gift_card/market-data/Fetch-RSA-Public-Key\n        :param recvWindow: The receive window for the request in milliseconds (optional)\n        :type recvWindow: int\n        :return: api response\n        .. code-block:: python\n            {\n                \"code\": \"000000\",\n                \"message\": \"success\",\n                \"data\": \"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCXBBVKLAc1GQ5FsIFFqOHrPTox5noBONIKr+IAedTR9FkVxq6e65updEbfdhRNkMOeYIO2i0UylrjGC0X8YSoIszmrVHeV0l06Zh1oJuZos1+7N+WLuz9JvlPaawof3GUakTxYWWCa9+8KIbLKsoKMdfS96VT+8iOXO3quMGKUmQIDAQAB\",\n                \"success\": true\n            }\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"giftcard/cryptography/rsa-public-key\", signed=True, data=params\n        )\n\n    def gift_card_verify(self, **params):\n        \"\"\"This API is for verifying whether the Binance Gift Card is valid or not by entering Gift Card Number.\n\n        Important Note:\n        If you enter the wrong Gift Card Number 5 times within an hour, you will no longer be able\n        to verify any Gift Card Number for that hour.\n\n        https://developers.binance.com/docs/gift_card/market-data/Verify-Binance-Gift-Card-by-Gift-Card-Number\n\n        :param referenceNo: Enter the Gift Card Number\n        :type referenceNo: str\n        :return: api response\n        .. code-block:: python\n            {\n                \"code\": \"000000\",\n                \"message\": \"success\",\n                \"data\": {\n                    \"valid\": true,\n                    \"token\": \"BNB\",     # coin\n                    \"amount\": \"0.00000001\"  # amount\n                },\n                \"success\": true\n            }\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"giftcard/verify\", signed=True, data=params\n        )\n\n    def gift_card_redeem(self, **params):\n        \"\"\"This API is for redeeming a Binance Gift Card. Once redeemed, the coins will be deposited in your funding wallet.\n\n        Important Note:\n        If you enter the wrong redemption code 5 times within 24 hours, you will no longer be able to\n        redeem any Binance Gift Cards that day.\n\n        Code Format Options:\n        - Plaintext\n        - Encrypted (Recommended for better security)\n\n        For encrypted format:\n        1. Fetch RSA public key from the RSA public key endpoint\n        2. Encrypt the code using algorithm: RSA/ECB/OAEPWithSHA-256AndMGF1Padding\n\n        https://developers.binance.com/docs/gift_card/market-data/Redeem-a-Binance-Gift-Card\n        :param code: Redemption code of Binance Gift Card to be redeemed, supports both Plaintext & Encrypted code\n        :type code: str\n        :param externalUid: External unique ID representing a user on the partner platform.\n                          Helps identify redemption behavior and control risks/limits.\n                          Max 400 characters. (optional)\n        :type externalUid: str\n        :param recvWindow: The receive window for the request in milliseconds (optional)\n        :type recvWindow: int\n        :return: api response\n        .. code-block:: python\n            {\n                \"code\": \"000000\",\n                \"message\": \"success\",\n                \"data\": {\n                    \"referenceNo\": \"0033002328060227\",\n                    \"identityNo\": \"10317392647411060736\",\n                    \"token\": \"BNB\",\n                    \"amount\": \"0.00000001\"\n                },\n                \"success\": true\n            }\n        \"\"\"\n        return self._request_margin_api(\n            \"post\", \"giftcard/redeemCode\", signed=True, data=params\n        )\n\n    def gift_card_create(self, **params):\n        \"\"\"\n        This API is for creating a Binance Gift Card.\n\n        To get started with, please make sure:\n\n        - You have a Binance account\n        - You have passed KYB\n        - You have a sufﬁcient balance(Gift Card amount and fee amount) in your Binance funding wallet\n        - You need Enable Withdrawals for the API Key which requests this endpoint.\n\n        https://developers.binance.com/docs/gift_card/market-data\n\n        :param token: The token type contained in the Binance Gift Card\n        :type token: str\n        :param amount: The amount of the token contained in the Binance Gift Card\n        :type amount: float\n        :return: api response\n        .. code-block:: python\n            {\n                \"code\": \"000000\",\n                \"message\": \"success\",\n                \"data\": {\n                    \"referenceNo\": \"0033002144060553\",\n                    \"code\": \"6H9EKF5ECCWFBHGE\",\n                    \"expiredTime\": 1727417154000\n                },\n                \"success\": true\n            }\n        \"\"\"\n        return self._request_margin_api(\n            \"post\", \"giftcard/createCode\", signed=True, data=params\n        )\n\n    def gift_card_create_dual_token(self, **params):\n        \"\"\"This API is for creating a dual-token ( stablecoin-denominated) Binance Gift Card. You may create a gift card using USDT as baseToken, that is redeemable to another designated token (faceToken). For example, you can create a fixed-value BTC gift card and pay with 100 USDT plus 1 USDT fee. This gift card can keep the value fixed at 100 USDT before redemption, and will be redeemable to BTC equivalent to 100 USDT upon redemption.\n\n        Once successfully created, the amount of baseToken (e.g. USDT) in the fixed-value gift card along with the fee would be deducted from your funding wallet.\n\n        To get started with, please make sure:\n        - You have a Binance account\n        - You have passed KYB\n        - You have a sufﬁcient balance(Gift Card amount and fee amount) in your Binance funding wallet\n        - You need Enable Withdrawals for the API Key which requests this endpoint.\n\n        https://developers.binance.com/docs/gift_card/market-data/Create-a-dual-token-gift-card\n        :param baseToken: The token you want to pay, example: BUSD\n        :type baseToken: str\n        :param faceToken: The token you want to buy, example: BNB. If faceToken = baseToken, it's the same as createCode endpoint.\n        :type faceToken: str\n        :param discount: Stablecoin-denominated card discount percentage, Example: 1 for 1% discount. Scale should be less than 6.\n        :type discount: float\n        :return: api response\n        .. code-block:: python\n            {\n                \"code\": \"000000\",\n                \"message\": \"success\",\n                \"data\": {\n                    \"referenceNo\": \"0033002144060553\",\n                    \"code\": \"6H9EKF5ECCWFBHGE\",\n                    \"expiredTime\": 1727417154000\n                },\n                \"success\": true\n            }\n        \"\"\"\n        return self._request_margin_api(\n            \"post\", \"giftcard/buyCode\", signed=True, data=params\n        )\n\n    ####################################################\n    # Borrow and repay Endpoints\n    ####################################################\n\n    def margin_next_hourly_interest_rate(self, **params):\n        \"\"\"Get future hourly interest rate (USER_DATA)\n\n        https://developers.binance.com/docs/margin_trading/borrow-and-repay\n\n        :param assets: required - List of assets, separated by commas, up to 20\n        :type assets: str\n        :param isIsolated: required - for isolated margin or not, \"TRUE\", \"FALSE\"\n        :type isIsolated: bool\n\n        :returns: API response\n\n        .. code-block:: python\n            [\n                {\n                    \"asset\": \"BTC\",\n                    \"nextHourlyInterestRate\": \"0.00000571\"\n                },\n                {\n                    \"asset\": \"ETH\",\n                    \"nextHourlyInterestRate\": \"0.00000578\"\n                }\n            ]\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"margin/next-hourly-interest-rate\", signed=True, data=params\n        )\n\n    def margin_interest_history(self, **params):\n        \"\"\"Get Interest History (USER_DATA)\n\n        https://developers.binance.com/docs/margin_trading/borrow-and-repay/Get-Interest-History\n\n        :param asset: optional\n        :type asset: str\n        :param isolatedSymbol: optional - isolated symbol\n        :type isolatedSymbol: str\n        :param startTime: optional\n        :type startTime: int\n        :param endTime: optional\n        :type endTime: int\n        :param current: optional - Currently querying page. Start from 1. Default:1\n        :type current: int\n        :param size: optional - Default:10 Max:100\n        :type size: int\n\n        :returns: API response\n\n        .. code-block:: python\n            {\n                \"rows\": [\n                    {\n                    \"txId\": 1352286576452864727,\n                    \"interestAccuredTime\": 1672160400000,\n                    \"asset\": \"USDT\",\n                    \"rawAsset\": “USDT”,  // will not be returned for isolated margin\n                    \"principal\": \"45.3313\",\n                    \"interest\": \"0.00024995\",\n                    \"interestRate\": \"0.00013233\",\n                    \"type\": \"ON_BORROW\",\n                    \"isolatedSymbol\": \"BNBUSDT\"  // isolated symbol, will not be returned for crossed margin\n                    }\n                ],\n                \"total\": 1\n                }\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"margin/interestHistory\", signed=True, data=params\n        )\n\n    def margin_borrow_repay(self, **params):\n        \"\"\"Margin Account Borrow/Repay (MARGIN)\n\n        https://developers.binance.com/docs/margin_trading/borrow-and-repay/Margin-Account-Borrow-Repay\n\n        :param asset: required\n        :type asset: str\n        :param amount: required\n        :type amount: float\n        :param isIsolated: optional - for isolated margin or not, \"TRUE\", \"FALSE\", default \"FALSE\"\n        :type isIsolated: str\n        :param symbol: optional - isolated symbol\n        :type symbol: str\n        :param type: str\n        :type type: str - BORROW or REPAY\n\n        :returns: API response\n        .. code-block:: python\n            {\n                //transaction id\n                \"tranId\": 100000001\n            }\n\n        \"\"\"\n        return self._request_margin_api(\n            \"post\", \"margin/borrow-repay\", signed=True, data=params\n        )\n\n    def margin_get_borrow_repay_records(self, **params):\n        \"\"\"Query Query borrow/repay records in Margin account (USER_DATA)\n\n        https://developers.binance.com/docs/margin_trading/borrow-and-repay/Query-Borrow-Repay\n\n        :param asset: required\n        :type asset: str\n        :param isolatedSymbol: optional - isolated symbol\n        :type isolatedSymbol: str\n        :param txId: optional - the tranId in POST /sapi/v1/margin/loan\n        :type txId: int\n        :param startTime: optional\n        :type startTime: int\n        :param endTime: optional\n        :type endTime: int\n        :param current: optional - Currently querying page. Start from 1. Default:1\n        :type current: int\n        :param size: optional - Default:10 Max:100\n        :type size: int\n\n        :returns: API response\n\n        .. code-block:: python\n        {\n            \"rows\": [\n                {\n                    \"type\": \"AUTO\", // AUTO,MANUAL for Cross Margin Borrow; MANUAL，AUTO，BNB_AUTO_REPAY，POINT_AUTO_REPAY for Cross Margin Repay; AUTO，MANUAL for Isolated Margin Borrow/Repay;\n                    \"isolatedSymbol\": \"BNBUSDT\",     // isolated symbol, will not be returned for crossed margin\n                    \"amount\": \"14.00000000\",   // Total amount borrowed/repaid\n                    \"asset\": \"BNB\",\n                    \"interest\": \"0.01866667\",    // Interest repaid\n                    \"principal\": \"13.98133333\",   // Principal repaid\n                    \"status\": \"CONFIRMED\",   //one of PENDING (pending execution), CONFIRMED (successfully execution), FAILED (execution failed, nothing happened to your account);\n                    \"timestamp\": 1563438204000,\n                    \"txId\": 2970933056\n                }\n            ],\n            \"total\": 1\n        }\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"margin/borrow-repay\", signed=True, data=params\n        )\n\n    def margin_interest_rate_history(self, **params):\n        \"\"\"Query Margin Interest Rate History (USER_DATA)\n\n        https://developers.binance.com/docs/margin_trading/borrow-and-repay/Query-Margin-Interest-Rate-History\n\n        :param asset: required\n        :type asset: str\n        :param vipLevel: optional\n        :type vipLevel: int\n        :param startTime: optional\n        :type startTime: int\n        :param endTime: optional\n        :type endTime: int\n\n        :returns: API response\n\n        .. code-block:: python\n        [\n            {\n                \"asset\": \"BTC\",\n                \"dailyInterestRate\": \"0.00025000\",\n                \"timestamp\": 1611544731000,\n                \"vipLevel\": 1\n            },\n            {\n                \"asset\": \"BTC\",\n                \"dailyInterestRate\": \"0.00035000\",\n                \"timestamp\": 1610248118000,\n                \"vipLevel\": 1\n            }\n        ]\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"margin/interestRateHistory\", signed=True, data=params\n        )\n\n    def margin_max_borrowable(self, **params):\n        \"\"\"Query Max Borrow (USER_DATA)\n\n        https://developers.binance.com/docs/margin_trading/borrow-and-repay/Query-Max-Borrow\n\n        :param asset: required\n        :type asset: str\n        :param isolatedSymbol: optional - isolated symbol\n        :type isolatedSymbol: str\n\n        :returns: API response\n\n        .. code-block:: python\n\n        {\n            \"amount\": \"1.69248805\", // account's currently max borrowable amount with sufficient system availability\n            \"borrowLimit\": \"60\" // max borrowable amount limited by the account level\n        }\n\n        \"\"\"\n        return self._request_margin_api(\n            \"get\", \"margin/maxBorrowable\", signed=True, data=params\n        )\n\n    ####################################################\n    # Futures Data\n    ####################################################\n\n    def futures_historical_data_link(self, **params):\n        \"\"\"Get Future TickLevel Orderbook Historical Data Download Link.\n\n        https://developers.binance.com/docs/derivatives/futures-data/market-data\n\n        :param symbol: STRING - Required - Symbol name, e.g. BTCUSDT or BTCUSD_PERP\n        :type symbol: str\n        :param dataType: ENUM - Required - Data type:\n            - T_DEPTH for ticklevel orderbook data\n            - S_DEPTH for orderbook snapshot data\n        :type dataType: str\n        :param startTime: LONG - Required - Start time in milliseconds\n        :type startTime: int\n        :param endTime: LONG - Required - End time in milliseconds\n        :type endTime: int\n        :param recvWindow: LONG - Optional - Number of milliseconds after timestamp the request is valid for\n        :type recvWindow: int\n        :param timestamp: LONG - Required - Current timestamp in milliseconds\n        :type timestamp: int\n\n        :returns: API response\n\n        .. code-block:: python\n\n            {\n                \"data\": [\n                    {\n                        \"day\": \"2023-06-30\",\n                        \"url\": \"\"\n                    }\n                ]\n            }\n\n        :raises: BinanceRequestException, BinanceAPIException\n\n        Notes:\n            - The span between startTime and endTime can't be more than 7 days\n            - The download link will be valid for 1 day\n            - Only VIP users can query this endpoint\n            - Weight: 200\n        \"\"\"\n        return self._request_margin_api(\"get\", \"futures/data/histDataLink\", signed=True, data=params)\n\n    def margin_v1_get_loan_vip_ongoing_orders(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/loan/vip/ongoing/orders.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        GET /sapi/v1/loan/vip/ongoing/orders\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"loan/vip/ongoing/orders\", signed=True, data=params, version=1)\n\n    def margin_v1_get_mining_payment_other(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/mining/payment/other.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/mining/rest-api/Extra-Bonus-List\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"mining/payment/other\", signed=True, data=params, version=1)\n\n    def futures_coin_v1_get_income_asyn_id(self, **params):\n        \"\"\"\n        Placeholder function for GET /dapi/v1/income/asyn/id.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/account/rest-api/Get-Futures-Transaction-History-Download-Link-by-Id\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_futures_coin_api(\"get\", \"income/asyn/id\", signed=True, data=params, version=1)\n\n    def margin_v1_get_simple_earn_flexible_history_subscription_record(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/simple-earn/flexible/history/subscriptionRecord.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/simple_earn/history\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"simple-earn/flexible/history/subscriptionRecord\", signed=True, data=params, version=1)\n\n    def margin_v1_post_lending_auto_invest_one_off(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/lending/auto-invest/one-off.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"lending/auto-invest/one-off\", signed=True, data=params, version=1)\n\n    def margin_v1_post_broker_sub_account_api_commission_coin_futures(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/broker/subAccountApi/commission/coinFutures.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/binance_link/exchange-link/fee/Change-Sub-Account-CM-Futures-Commission\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"broker/subAccountApi/commission/coinFutures\", signed=True, data=params, version=1)\n\n    def v3_post_order_list_otoco(self, **params):\n        \"\"\"\n        Placeholder function for POST /api/v3/orderList/otoco.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_api(\"post\", \"orderList/otoco\", signed=True, data=params, version=\"v3\")\n\n    def futures_v1_get_order_asyn(self, **params):\n        \"\"\"\n        Placeholder function for GET /fapi/v1/order/asyn.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Get-Download-Id-For-Futures-Order-History\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_futures_api(\"get\", \"order/asyn\", signed=True, data=params, version=1)\n\n    def margin_v1_get_asset_custody_transfer_history(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/asset/custody/transfer-history.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/wallet/asset/query-user-delegation\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"asset/custody/transfer-history\", signed=True, data=params, version=1)\n\n    def margin_v1_post_broker_sub_account_blvt(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/broker/subAccount/blvt.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"broker/subAccount/blvt\", signed=True, data=params, version=1)\n\n    def margin_v1_post_sol_staking_sol_redeem(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/sol-staking/sol/redeem.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/staking/sol-staking/staking/Redeem-SOL\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"sol-staking/sol/redeem\", signed=True, data=params, version=1)\n\n    def options_v1_get_countdown_cancel_all(self, **params):\n        \"\"\"\n        Placeholder function for GET /eapi/v1/countdownCancelAll.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/option/market-maker-endpoints/Get-Auto-Cancel-All-Open-Orders-Config\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_options_api(\"get\", \"countdownCancelAll\", signed=True, data=params)\n\n    def margin_v1_get_margin_trade_coeff(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/margin/tradeCoeff.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/margin_trading/account/Get-Summary-Of-Margin-Account\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"margin/tradeCoeff\", signed=True, data=params, version=1)\n\n    def futures_coin_v1_get_order_amendment(self, **params):\n        \"\"\"\n        Placeholder function for GET /dapi/v1/orderAmendment.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/rest-api/Get-Order-Modify-History\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_futures_coin_api(\"get\", \"orderAmendment\", signed=True, data=params, version=1)\n\n    def margin_v1_get_margin_available_inventory(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/margin/available-inventory.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/margin_trading/market-data/Query-margin-avaliable-inventory\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"margin/available-inventory\", signed=True, data=params, version=1)\n\n    def margin_v1_post_account_api_restrictions_ip_restriction_ip_list(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/account/apiRestrictions/ipRestriction/ipList.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"account/apiRestrictions/ipRestriction/ipList\", signed=True, data=params, version=1)\n\n    def margin_v2_get_eth_staking_account(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v2/eth-staking/account.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/staking/eth-staking/account\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"eth-staking/account\", signed=True, data=params, version=2)\n\n    def margin_v1_get_loan_income(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/loan/income.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/crypto_loan/stable-rate/market-data\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"loan/income\", signed=True, data=params, version=1)\n\n    def futures_coin_v1_get_pm_account_info(self, **params):\n        \"\"\"\n        Placeholder function for GET /dapi/v1/pmAccountInfo.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/portfolio-margin-endpoints\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_futures_coin_api(\"get\", \"pmAccountInfo\", signed=True, data=params, version=1)\n\n    def margin_v1_get_managed_subaccount_query_trans_log_for_investor(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/managed-subaccount/queryTransLogForInvestor.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/sub_account/managed-sub-account/Query-Managed-Sub-Account-Transfer-Log-Investor\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"managed-subaccount/queryTransLogForInvestor\", signed=True, data=params, version=1)\n\n    def margin_v1_post_dci_product_auto_compound_edit_status(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/dci/product/auto_compound/edit-status.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/dual_investment/trade/Change-Auto-Compound-status\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"dci/product/auto_compound/edit-status\", signed=True, data=params, version=1)\n\n    def futures_v1_get_trade_asyn(self, **params):\n        \"\"\"\n        Placeholder function for GET /fapi/v1/trade/asyn.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Get-Download-Id-For-Futures-Trade-History\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_futures_api(\"get\", \"trade/asyn\", signed=True, data=params, version=1)\n\n    def margin_v1_get_loan_vip_request_interest_rate(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/loan/vip/request/interestRate.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/vip_loan/market-data\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"loan/vip/request/interestRate\", signed=True, data=params, version=1)\n\n    def futures_v1_get_funding_info(self, **params):\n        \"\"\"\n        Placeholder function for GET /fapi/v1/fundingInfo.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Get-Funding-Rate-Info\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_futures_api(\"get\", \"fundingInfo\", signed=False, data=params, version=1)\n\n    def margin_v2_get_loan_flexible_repay_rate(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v2/loan/flexible/repay/rate.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/crypto_loan/flexible-rate/user-information/Check-Collateral-Repay-Rate\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"loan/flexible/repay/rate\", signed=True, data=params, version=2)\n\n    def margin_v1_get_lending_auto_invest_plan_id(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/lending/auto-invest/plan/id.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"lending/auto-invest/plan/id\", signed=True, data=params, version=1)\n\n    def margin_v1_post_loan_adjust_ltv(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/loan/adjust/ltv.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"loan/adjust/ltv\", signed=True, data=params, version=1)\n\n    def margin_v1_get_mining_statistics_user_status(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/mining/statistics/user/status.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/mining/rest-api/Statistic-List\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"mining/statistics/user/status\", signed=True, data=params, version=1)\n\n    def margin_v1_get_broker_transfer_futures(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/broker/transfer/futures.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/binance_link/exchange-link/asset/Query-Sub-Account-Transfer-History-Futures\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"broker/transfer/futures\", signed=True, data=params, version=1)\n\n    def margin_v1_post_algo_spot_new_order_twap(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/algo/spot/newOrderTwap.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/algo/spot-algo/Time-Weighted-Average-Price-New-Order\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"algo/spot/newOrderTwap\", signed=True, data=params, version=1)\n\n    def margin_v1_get_lending_auto_invest_target_asset_list(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/lending/auto-invest/target-asset/list.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"lending/auto-invest/target-asset/list\", signed=True, data=params, version=1)\n\n    def margin_v1_get_capital_deposit_address_list(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/capital/deposit/address/list.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/wallet/capital/deposite-address\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"capital/deposit/address/list\", signed=True, data=params, version=1)\n\n    def margin_v1_post_broker_sub_account_bnb_burn_margin_interest(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/broker/subAccount/bnbBurn/marginInterest.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/binance_link/exchange-link/account/Enable-Or-Disable-BNB-Burn-for-Sub-Account-Margin-Interest\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"broker/subAccount/bnbBurn/marginInterest\", signed=True, data=params, version=1)\n\n    def margin_v2_post_loan_flexible_repay(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v2/loan/flexible/repay.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/crypto_loan/flexible-rate/trade/Flexible-Loan-Repay\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"loan/flexible/repay\", signed=True, data=params, version=2)\n\n    def margin_v2_get_loan_flexible_loanable_data(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v2/loan/flexible/loanable/data.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/crypto_loan/flexible-rate/market-data/Get-Flexible-Loan-Assets-Data\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"loan/flexible/loanable/data\", signed=True, data=params, version=2)\n\n    def margin_v1_post_broker_sub_account_api_permission(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/broker/subAccountApi/permission.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/binance_link/exchange-link/account/Change-Sub-Account-Api-Permission\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"broker/subAccountApi/permission\", signed=True, data=params, version=1)\n\n    def margin_v1_post_broker_sub_account_api(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/broker/subAccountApi.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/binance_link/exchange-link/account/Create-Api-Key-for-Sub-Account\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"broker/subAccountApi\", signed=True, data=params, version=1)\n\n    def margin_v1_get_dci_product_positions(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/dci/product/positions.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/dual_investment/trade/Get-Dual-Investment-positions\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"dci/product/positions\", signed=True, data=params, version=1)\n\n    def margin_v1_post_convert_limit_cancel_order(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/convert/limit/cancelOrder.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/convert/trade/Cancel-Order\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"convert/limit/cancelOrder\", signed=True, data=params, version=1)\n\n    def v3_post_order_list_oto(self, **params):\n        \"\"\"\n        Placeholder function for POST /api/v3/orderList/oto.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_api(\"post\", \"orderList/oto\", signed=True, data=params, version=\"v3\")\n\n    def margin_v1_get_mining_hash_transfer_config_details_list(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/mining/hash-transfer/config/details/list.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/mining/rest-api/Hashrate-Resale-List\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"mining/hash-transfer/config/details/list\", signed=True, data=params, version=1)\n\n    def margin_v1_get_mining_hash_transfer_profit_details(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/mining/hash-transfer/profit/details.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/mining/rest-api/Hashrate-Resale-Detail\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"mining/hash-transfer/profit/details\", signed=True, data=params, version=1)\n\n    def margin_v1_get_broker_sub_account(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/broker/subAccount.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/binance_link/exchange-link/account/Query-Sub-Account\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"broker/subAccount\", signed=True, data=params, version=1)\n\n    def margin_v1_get_portfolio_balance(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/portfolio/balance.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin-pro/account/Get-Classic-Portfolio-Margin-Balance-Info\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"portfolio/balance\", signed=True, data=params, version=1)\n\n    def margin_v1_post_sub_account_eoptions_enable(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/sub-account/eoptions/enable.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/sub_account/account-management/Enable-Options-for-Sub-account\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"sub-account/eoptions/enable\", signed=True, data=params, version=1)\n\n    def papi_v1_post_ping(self, **params):\n        \"\"\"\n        Placeholder function for POST /papi/v1/ping.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_papi_api(\"post\", \"ping\", signed=True, data=params, version=1)\n\n    def margin_v1_get_loan_loanable_data(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/loan/loanable/data.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"loan/loanable/data\", signed=True, data=params, version=1)\n\n    def margin_v1_post_eth_staking_wbeth_unwrap(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/eth-staking/wbeth/unwrap.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"eth-staking/wbeth/unwrap\", signed=True, data=params, version=1)\n\n    def margin_v1_get_eth_staking_eth_history_staking_history(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/eth-staking/eth/history/stakingHistory.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/staking/eth-staking/history\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"eth-staking/eth/history/stakingHistory\", signed=True, data=params, version=1)\n\n    def margin_v1_get_staking_staking_record(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/staking/stakingRecord.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"staking/stakingRecord\", signed=True, data=params, version=1)\n\n    def margin_v1_get_broker_rebate_recent_record(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/broker/rebate/recentRecord.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/binance_link/exchange-link/fee/Query-Spot-Commission-Rebate-Recent-Record\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"broker/rebate/recentRecord\", signed=True, data=params, version=1)\n\n    def margin_v1_get_loan_vip_collateral_account(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/loan/vip/collateral/account.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/vip_loan/user-information/Check-Locked-Value-of-VIP-Collateral-Account\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"loan/vip/collateral/account\", signed=True, data=params, version=1)\n\n    def margin_v1_get_algo_spot_open_orders(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/algo/spot/openOrders.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/algo/spot-algo/Query-Current-Algo-Open-Orders\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"algo/spot/openOrders\", signed=True, data=params, version=1)\n\n    def margin_v1_post_loan_repay(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/loan/repay.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"loan/repay\", signed=True, data=params, version=1)\n\n    def futures_coin_v1_get_funding_info(self, **params):\n        \"\"\"\n        Placeholder function for GET /dapi/v1/fundingInfo.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/market-data/rest-api/Get-Funding-Info\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_futures_coin_api(\"get\", \"fundingInfo\", signed=False, data=params, version=1)\n\n    def margin_v1_get_margin_leverage_bracket(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/margin/leverageBracket.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/margin_trading/market-data/Query-Liability-Coin-Leverage-Bracket-in-Cross-Margin-Pro-Mode\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"margin/leverageBracket\", signed=True, data=params, version=1)\n\n    def margin_v2_get_portfolio_collateral_rate(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v2/portfolio/collateralRate.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin-pro/market-data/Portfolio-Margin-Pro-Tiered-Collateral-Rate\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"portfolio/collateralRate\", signed=True, data=params, version=2)\n\n    def margin_v2_post_loan_flexible_adjust_ltv(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v2/loan/flexible/adjust/ltv.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/crypto_loan/flexible-rate/trade/Flexible-Loan-Adjust-LTV\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"loan/flexible/adjust/ltv\", signed=True, data=params, version=2)\n\n    def margin_v1_get_convert_order_status(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/convert/orderStatus.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/convert/trade/Order-Status\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"convert/orderStatus\", signed=True, data=params, version=1)\n\n    def margin_v1_get_broker_sub_account_api_ip_restriction(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/broker/subAccountApi/ipRestriction.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/binance_link/exchange-link/account/Get-IPRestriction-for-Sub-Account-Api-Key\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"broker/subAccountApi/ipRestriction\", signed=True, data=params, version=1)\n\n    def margin_v1_post_dci_product_subscribe(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/dci/product/subscribe.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/dual_investment/trade\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"dci/product/subscribe\", signed=True, data=params, version=1)\n\n    def futures_v1_get_income_asyn_id(self, **params):\n        \"\"\"\n        Placeholder function for GET /fapi/v1/income/asyn/id.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Get-Futures-Transaction-History-Download-Link-by-Id\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_futures_api(\"get\", \"income/asyn/id\", signed=True, data=params, version=1)\n\n    def options_v1_post_countdown_cancel_all(self, **params):\n        \"\"\"\n        Placeholder function for POST /eapi/v1/countdownCancelAll.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/option/market-maker-endpoints/Set-Auto-Cancel-All-Open-Orders-Config\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_options_api(\"post\", \"countdownCancelAll\", signed=True, data=params)\n\n    def margin_v1_post_mining_hash_transfer_config_cancel(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/mining/hash-transfer/config/cancel.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/mining/rest-api/Cancel-hashrate-resale-configuration\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"mining/hash-transfer/config/cancel\", signed=True, data=params, version=1)\n\n    def margin_v1_get_broker_sub_account_deposit_hist(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/broker/subAccount/depositHist.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/binance_link/exchange-link/asset/Get-Sub-Account-Deposit-History\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"broker/subAccount/depositHist\", signed=True, data=params, version=1)\n\n    def margin_v1_get_mining_payment_list(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/mining/payment/list.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/mining/rest-api/Earnings-List\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"mining/payment/list\", signed=True, data=params, version=1)\n\n    def futures_v1_get_pm_account_info(self, **params):\n        \"\"\"\n        Placeholder function for GET /fapi/v1/pmAccountInfo.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/portfolio-margin-endpoints\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_futures_api(\"get\", \"pmAccountInfo\", signed=True, data=params, version=1)\n\n    def futures_coin_v1_get_adl_quantile(self, **params):\n        \"\"\"\n        Placeholder function for GET /dapi/v1/adlQuantile.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/rest-api/Position-ADL-Quantile-Estimation\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_futures_coin_api(\"get\", \"adlQuantile\", signed=True, data=params, version=1)\n\n    def options_v1_get_income_asyn_id(self, **params):\n        \"\"\"\n        Placeholder function for GET /eapi/v1/income/asyn/id.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/option/account/Get-Option-Transaction-History-Download-Link-by-Id\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_options_api(\"get\", \"income/asyn/id\", signed=True, data=params)\n\n    def v3_post_cancel_replace(self, **params):\n        \"\"\"\n        Placeholder function for POST /api/v3/cancelReplace.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_api(\"post\", \"cancelReplace\", signed=True, data=params, version=\"v3\")\n\n    def margin_v1_post_account_enable_fast_withdraw_switch(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/account/enableFastWithdrawSwitch.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/wallet/account/enable-fast-withdraw-switch\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"account/enableFastWithdrawSwitch\", signed=True, data=params, version=1)\n\n    def margin_v1_post_broker_transfer_futures(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/broker/transfer/futures.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/binance_link/exchange-link/asset/Sub-Account-Transfer-Futures\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"broker/transfer/futures\", signed=True, data=params, version=1)\n\n    def margin_v1_post_sol_staking_sol_stake(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/sol-staking/sol/stake.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/staking/sol-staking/staking\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"sol-staking/sol/stake\", signed=True, data=params, version=1)\n\n    def margin_v1_post_loan_borrow(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/loan/borrow.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"loan/borrow\", signed=True, data=params, version=1)\n\n    def margin_v1_get_managed_subaccount_info(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/managed-subaccount/info.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/sub_account/managed-sub-account/Query-Managed-Sub-account-List\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"managed-subaccount/info\", signed=True, data=params, version=1)\n\n    def margin_v1_post_lending_auto_invest_plan_edit_status(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/lending/auto-invest/plan/edit-status.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"lending/auto-invest/plan/edit-status\", signed=True, data=params, version=1)\n\n    def margin_v1_get_sol_staking_sol_history_unclaimed_rewards(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/sol-staking/sol/history/unclaimedRewards.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/staking/sol-staking/history/Get-Unclaimed-rewards\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"sol-staking/sol/history/unclaimedRewards\", signed=True, data=params, version=1)\n\n    def margin_v1_post_asset_convert_transfer_query_by_page(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/asset/convert-transfer/queryByPage.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"asset/convert-transfer/queryByPage\", signed=True, data=params, version=1)\n\n    def margin_v1_get_sol_staking_sol_history_boost_rewards_history(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/sol-staking/sol/history/boostRewardsHistory.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/staking/sol-staking/history/Get-Boost-rewards-History\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"sol-staking/sol/history/boostRewardsHistory\", signed=True, data=params, version=1)\n\n    def margin_v1_get_lending_auto_invest_one_off_status(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/lending/auto-invest/one-off/status.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"lending/auto-invest/one-off/status\", signed=True, data=params, version=1)\n\n    def margin_v1_post_broker_sub_account(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/broker/subAccount.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/binance_link/exchange-link/account\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"broker/subAccount\", signed=True, data=params, version=1)\n\n    def margin_v1_get_asset_ledger_transfer_cloud_mining_query_by_page(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/asset/ledger-transfer/cloud-mining/queryByPage.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/wallet/asset/cloud-mining-payment-and-refund-history\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"asset/ledger-transfer/cloud-mining/queryByPage\", signed=True, data=params, version=1)\n\n    def margin_v1_get_mining_pub_coin_list(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/mining/pub/coinList.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/mining/rest-api/Acquiring-CoinName\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"mining/pub/coinList\", signed=True, data=params, version=1)\n\n    def margin_v2_get_loan_flexible_repay_history(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v2/loan/flexible/repay/history.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/crypto_loan/flexible-rate/user-information/Get-Flexible-Loan-Repayment-History\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"loan/flexible/repay/history\", signed=True, data=params, version=2)\n\n    def v3_post_sor_order(self, **params):\n        \"\"\"\n        Placeholder function for POST /api/v3/sor/order.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_api(\"post\", \"sor/order\", signed=True, data=params, version=\"v3\")\n\n    def margin_v1_post_capital_deposit_credit_apply(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/capital/deposit/credit-apply.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/wallet/capital/one-click-arrival-deposite-apply\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"capital/deposit/credit-apply\", signed=True, data=params, version=1)\n\n    def futures_v1_put_batch_order(self, **params):\n        \"\"\"\n        Placeholder function for PUT /fapi/v1/batchOrder.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_futures_api(\"put\", \"batchOrder\", signed=True, data=params, version=1)\n\n    def margin_v1_get_mining_statistics_user_list(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/mining/statistics/user/list.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/mining/rest-api/Account-List\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"mining/statistics/user/list\", signed=True, data=params, version=1)\n\n    def futures_v1_post_batch_order(self, **params):\n        \"\"\"\n        Placeholder function for POST /fapi/v1/batchOrder.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_futures_api(\"post\", \"batchOrder\", signed=True, data=params, version=1)\n\n    def v3_get_ticker_trading_day(self, **params):\n        \"\"\"\n        Placeholder function for GET /api/v3/ticker/tradingDay.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_api(\"get\", \"ticker/tradingDay\", signed=False, data=params, version=\"v3\")\n\n    def margin_v1_get_mining_worker_detail(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/mining/worker/detail.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/mining/rest-api/Request-for-Detail-Miner-List\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"mining/worker/detail\", signed=True, data=params, version=1)\n\n    def margin_v1_get_managed_subaccount_fetch_future_asset(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/managed-subaccount/fetch-future-asset.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/sub_account/managed-sub-account/Query-Managed-Sub-account-Futures-Asset-Details\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"managed-subaccount/fetch-future-asset\", signed=True, data=params, version=1)\n\n    def margin_v1_get_margin_rate_limit_order(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/margin/rateLimit/order.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/margin_trading/trade/Query-Current-Margin-Order-Count-Usage\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"margin/rateLimit/order\", signed=True, data=params, version=1)\n\n    def margin_v1_get_localentity_vasp(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/localentity/vasp.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/wallet/travel-rule/onboarded-vasp-list\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"localentity/vasp\", signed=True, data=params, version=1)\n\n    def margin_v1_get_sol_staking_sol_history_rate_history(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/sol-staking/sol/history/rateHistory.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/staking/sol-staking/history/Get-BNSOL-Rate-History\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"sol-staking/sol/history/rateHistory\", signed=True, data=params, version=1)\n\n    def margin_v1_post_broker_sub_account_api_ip_restriction(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/broker/subAccountApi/ipRestriction.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"broker/subAccountApi/ipRestriction\", signed=True, data=params, version=1)\n\n    def margin_v1_get_broker_transfer(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/broker/transfer.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/binance_link/exchange-link/asset/Query-Sub-Account-Transfer-History-Spot\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"broker/transfer\", signed=True, data=params, version=1)\n\n    def margin_v1_get_sol_staking_account(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/sol-staking/account.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/staking/sol-staking/account\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"sol-staking/account\", signed=True, data=params, version=1)\n\n    def margin_v1_get_account_info(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/account/info.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/wallet/account\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"account/info\", signed=True, data=params, version=1)\n\n    def margin_v1_post_portfolio_repay_futures_switch(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/portfolio/repay-futures-switch.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin-pro/account/Change-Auto-repay-futures-Status\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"portfolio/repay-futures-switch\", signed=True, data=params, version=1)\n\n    def margin_v1_post_loan_vip_borrow(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/loan/vip/borrow.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"loan/vip/borrow\", signed=True, data=params, version=1)\n\n    def margin_v2_get_loan_flexible_ltv_adjustment_history(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v2/loan/flexible/ltv/adjustment/history.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/crypto_loan/flexible-rate/user-information\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"loan/flexible/ltv/adjustment/history\", signed=True, data=params, version=2)\n\n    def options_v1_delete_all_open_orders_by_underlying(self, **params):\n        \"\"\"\n        Placeholder function for DELETE /eapi/v1/allOpenOrdersByUnderlying.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/option/trade/Cancel-All-Option-Orders-By-Underlying\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_options_api(\"delete\", \"allOpenOrdersByUnderlying\", signed=True, data=params)\n\n    def margin_v1_get_broker_sub_account_futures_summary(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/broker/subAccount/futuresSummary.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"broker/subAccount/futuresSummary\", signed=True, data=params, version=1)\n\n    def margin_v1_get_broker_sub_account_spot_summary(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/broker/subAccount/spotSummary.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/binance_link/exchange-link/asset/Query-Sub-Account-Spot-Asset-Info\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"broker/subAccount/spotSummary\", signed=True, data=params, version=1)\n\n    def margin_v1_post_sub_account_blvt_enable(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/sub-account/blvt/enable.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"sub-account/blvt/enable\", signed=True, data=params, version=1)\n\n    def margin_v1_get_algo_spot_historical_orders(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/algo/spot/historicalOrders.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/algo/spot-algo/Query-Historical-Algo-Orders\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"algo/spot/historicalOrders\", signed=True, data=params, version=1)\n\n    def margin_v1_get_loan_vip_repay_history(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/loan/vip/repay/history.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/vip_loan/user-information/Get-VIP-Loan-Repayment-History\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"loan/vip/repay/history\", signed=True, data=params, version=1)\n\n    def margin_v1_get_loan_borrow_history(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/loan/borrow/history.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/crypto_loan/stable-rate/user-information\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"loan/borrow/history\", signed=True, data=params, version=1)\n\n    def margin_v1_post_lending_auto_invest_redeem(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/lending/auto-invest/redeem.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"lending/auto-invest/redeem\", signed=True, data=params, version=1)\n\n    def futures_coin_v1_get_income_asyn(self, **params):\n        \"\"\"\n        Placeholder function for GET /dapi/v1/income/asyn.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/account/rest-api/Get-Download-Id-For-Futures-Transaction-History\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_futures_coin_api(\"get\", \"income/asyn\", signed=True, data=params, version=1)\n\n    def margin_v1_post_managed_subaccount_deposit(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/managed-subaccount/deposit.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/sub_account/managed-sub-account\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"managed-subaccount/deposit\", signed=True, data=params, version=1)\n\n    def margin_v1_post_lending_daily_purchase(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/lending/daily/purchase.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"lending/daily/purchase\", signed=True, data=params, version=1)\n\n    def futures_v1_get_trade_asyn_id(self, **params):\n        \"\"\"\n        Placeholder function for GET /fapi/v1/trade/asyn/id.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Get-Futures-Trade-Download-Link-by-Id\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_futures_api(\"get\", \"trade/asyn/id\", signed=True, data=params, version=1)\n\n    def margin_v1_delete_sub_account_sub_account_api_ip_restriction_ip_list(self, **params):\n        \"\"\"\n        Placeholder function for DELETE /sapi/v1/sub-account/subAccountApi/ipRestriction/ipList.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/sub_account/api-management/Delete-IP-List-For-a-Sub-account-API-Key\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"delete\", \"sub-account/subAccountApi/ipRestriction/ipList\", signed=True, data=params, version=1)\n\n    def margin_v1_get_copy_trading_futures_user_status(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/copyTrading/futures/userStatus.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/copy_trading/future-copy-trading\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"copyTrading/futures/userStatus\", signed=True, data=params, version=1)\n\n    def options_v1_get_margin_account(self, **params):\n        \"\"\"\n        Placeholder function for GET /eapi/v1/marginAccount.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/option/market-maker-endpoints\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_options_api(\"get\", \"marginAccount\", signed=True, data=params)\n\n    def options_get_market_maker_protection_config(self, **params):\n        \"\"\"\n        Get config for MMP.\n\n        https://developers.binance.com/docs/derivatives/option/market-maker-endpoints/Get-Market-Maker-Protection-Config\n\n        :param underlying: required\n        :type underlying: str\n        :param recvWindow: optional\n        :type recvWindow: int\n        \"\"\"\n        return self._request_options_api(\"get\", \"mmp\", signed=True, data=params)\n\n    def options_post_market_maker_protection_config(self, **params):\n        \"\"\"\n        Set config for MMP.\n\n        https://developers.binance.com/docs/derivatives/option/market-maker-endpoints/Set-Market-Maker-Protection-Config\n\n        :param underlying: required\n        :type underlying: str\n        :param windowTimeInMilliseconds: required\n        :type windowTimeInMilliseconds: int\n        :param frozenTimeInMilliseconds: required\n        :type frozenTimeInMilliseconds: int\n        :param qtyLimit: required\n        :type qtyLimit: decimal\n        :param deltaLimit: required\n        :type deltaLimit: decimal\n        :param recvWindow: optional\n        :type recvWindow: int\n        \"\"\"\n        return self._request_options_api(\"post\", \"mmpSet\", signed=True, data=params)\n\n    def options_reset_market_maker_protection_config(self, **params):\n        \"\"\"\n        Reset MMP, start MMP order again.\n\n        https://developers.binance.com/docs/derivatives/option/market-maker-endpoints/Reset-Market-Maker-Protection-Config\n\n        :param underlying: required\n        :type underlying: str\n        :param recvWindow: optional\n        :type recvWindow: int\n        \"\"\"\n        return self._request_options_api(\"post\", \"mmpReset\", signed=True, data=params)\n\n    def margin_v1_post_localentity_withdraw_apply(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/localentity/withdraw/apply.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/wallet/travel-rule/withdraw\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"localentity/withdraw/apply\", signed=True, data=params, version=1)\n\n    def margin_v1_get_asset_wallet_balance(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/asset/wallet/balance.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/wallet/asset/query-user-wallet-balance\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"asset/wallet/balance\", signed=True, data=params, version=1)\n\n    def margin_v1_post_broker_transfer(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/broker/transfer.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/binance_link/exchange-link/asset\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"broker/transfer\", signed=True, data=params, version=1)\n\n    def margin_v1_post_lending_customized_fixed_purchase(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/lending/customizedFixed/purchase.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"lending/customizedFixed/purchase\", signed=True, data=params, version=1)\n\n    def margin_v1_post_algo_futures_new_order_twap(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/algo/futures/newOrderTwap.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/algo/future-algo/Time-Weighted-Average-Price-New-Order\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"algo/futures/newOrderTwap\", signed=True, data=params, version=1)\n\n    def margin_v2_post_eth_staking_eth_stake(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v2/eth-staking/eth/stake.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/staking/eth-staking/staking\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"eth-staking/eth/stake\", signed=True, data=params, version=2)\n\n    def margin_v1_post_loan_flexible_repay_history(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/loan/flexible/repay/history.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"loan/flexible/repay/history\", signed=True, data=params, version=1)\n\n    def margin_v1_get_lending_auto_invest_index_info(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/lending/auto-invest/index/info.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"lending/auto-invest/index/info\", signed=True, data=params, version=1)\n\n    def margin_v1_get_sol_staking_sol_history_redemption_history(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/sol-staking/sol/history/redemptionHistory.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/staking/sol-staking/history/Get-SOL-redemption-history\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"sol-staking/sol/history/redemptionHistory\", signed=True, data=params, version=1)\n\n    def margin_v1_get_broker_rebate_futures_recent_record(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/broker/rebate/futures/recentRecord.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/binance_link/exchange-link/fee/Query-Futures-Commission-Rebate-Record\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"broker/rebate/futures/recentRecord\", signed=True, data=params, version=1)\n\n    def margin_v3_get_broker_sub_account_futures_summary(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v3/broker/subAccount/futuresSummary.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/binance_link/exchange-link/asset/Query-Sub-Account-Futures-Asset-Info\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"broker/subAccount/futuresSummary\", signed=True, data=params, version=3)\n\n    def margin_v1_get_lending_auto_invest_target_asset_roi_list(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/lending/auto-invest/target-asset/roi/list.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"lending/auto-invest/target-asset/roi/list\", signed=True, data=params, version=1)\n\n    def margin_v1_get_broker_universal_transfer(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/broker/universalTransfer.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/binance_link/exchange-link/asset/Query-Universal-Transfer-History\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"broker/universalTransfer\", signed=True, data=params, version=1)\n\n    def futures_v1_put_batch_orders(self, **params):\n        \"\"\"\n        Placeholder function for PUT /fapi/v1/batchOrders.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Modify-Multiple-Orders\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_futures_api(\"put\", \"batchOrders\", signed=True, data=params, version=1)\n\n    def options_v1_post_countdown_cancel_all_heart_beat(self, **params):\n        \"\"\"\n        Placeholder function for POST /eapi/v1/countdownCancelAllHeartBeat.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/option/market-maker-endpoints/Auto-Cancel-All-Open-Orders-Heartbeat\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_options_api(\"post\", \"countdownCancelAllHeartBeat\", signed=True, data=params)\n\n    def margin_v1_get_loan_collateral_data(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/loan/collateral/data.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"loan/collateral/data\", signed=True, data=params, version=1)\n\n    def margin_v1_get_loan_repay_history(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/loan/repay/history.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/crypto_loan/stable-rate/user-information/Get-Loan-Repayment-History\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"loan/repay/history\", signed=True, data=params, version=1)\n\n    def margin_v1_post_convert_limit_place_order(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/convert/limit/placeOrder.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/convert/trade/Place-Order\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"convert/limit/placeOrder\", signed=True, data=params, version=1)\n\n    def futures_v1_get_convert_exchange_info(self, **params):\n        \"\"\"\n        Placeholder function for GET /fapi/v1/convert/exchangeInfo.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/convert\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_futures_api(\"get\", \"convert/exchangeInfo\", signed=False, data=params, version=1)\n\n    def v3_get_all_order_list(self, **params):\n        \"\"\"\n        Placeholder function for GET /api/v3/allOrderList.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_api(\"get\", \"allOrderList\", signed=True, data=params, version=\"v3\")\n\n    def margin_v1_delete_broker_sub_account_api_ip_restriction_ip_list(self, **params):\n        \"\"\"\n        Placeholder function for DELETE /sapi/v1/broker/subAccountApi/ipRestriction/ipList.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/binance_link/exchange-link/account/Delete-IPRestriction-for-Sub-Account-Api-Key\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"delete\", \"broker/subAccountApi/ipRestriction/ipList\", signed=True, data=params, version=1)\n\n    def margin_v1_post_sub_account_virtual_sub_account(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/sub-account/virtualSubAccount.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/sub_account/account-management\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"sub-account/virtualSubAccount\", signed=True, data=params, version=1)\n\n    def margin_v1_put_localentity_deposit_provide_info(self, **params):\n        \"\"\"\n        Placeholder function for PUT /sapi/v1/localentity/deposit/provide-info.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/wallet/travel-rule/deposit-provide-info\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"put\", \"localentity/deposit/provide-info\", signed=True, data=params, version=1)\n\n    def margin_v1_post_portfolio_mint(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/portfolio/mint.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin-pro/account/Mint-BFUSD-Portfolio-Margin\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"portfolio/mint\", signed=True, data=params, version=1)\n\n    def futures_v1_get_order_amendment(self, **params):\n        \"\"\"\n        Placeholder function for GET /fapi/v1/orderAmendment.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Get-Order-Modify-History\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_futures_api(\"get\", \"orderAmendment\", signed=True, data=params, version=1)\n\n    def margin_v1_post_sol_staking_sol_claim(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/sol-staking/sol/claim.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/staking/sol-staking/staking/Claim-Boost-rewards\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"sol-staking/sol/claim\", signed=True, data=params, version=1)\n\n    def margin_v1_post_lending_daily_redeem(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/lending/daily/redeem.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"lending/daily/redeem\", signed=True, data=params, version=1)\n\n    def margin_v1_post_mining_hash_transfer_config(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/mining/hash-transfer/config.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/mining/rest-api/Hashrate-Resale-Request\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"mining/hash-transfer/config\", signed=True, data=params, version=1)\n\n    def margin_v1_get_lending_auto_invest_rebalance_history(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/lending/auto-invest/rebalance/history.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"lending/auto-invest/rebalance/history\", signed=True, data=params, version=1)\n\n    def margin_v1_get_loan_repay_collateral_rate(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/loan/repay/collateral/rate.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"loan/repay/collateral/rate\", signed=True, data=params, version=1)\n\n    def futures_v1_get_income_asyn(self, **params):\n        \"\"\"\n        Placeholder function for GET /fapi/v1/income/asyn.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Get-Download-Id-For-Futures-Transaction-History\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_futures_api(\"get\", \"income/asyn\", signed=True, data=params, version=1)\n\n    def margin_v1_get_mining_payment_uid(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/mining/payment/uid.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/mining/rest-api/Mining-Account-Earning\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"mining/payment/uid\", signed=True, data=params, version=1)\n\n    def margin_v2_get_loan_flexible_borrow_history(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v2/loan/flexible/borrow/history.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/crypto_loan/flexible-rate/user-information/Get-Flexible-Loan-Borrow-History\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"loan/flexible/borrow/history\", signed=True, data=params, version=2)\n\n    def margin_v1_get_capital_contract_convertible_coins(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/capital/contract/convertible-coins.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"capital/contract/convertible-coins\", signed=True, data=params, version=1)\n\n    def margin_v1_post_broker_sub_account_api_permission_vanilla_options(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/broker/subAccountApi/permission/vanillaOptions.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"broker/subAccountApi/permission/vanillaOptions\", signed=True, data=params, version=1)\n\n    def margin_v1_get_lending_auto_invest_redeem_history(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/lending/auto-invest/redeem/history.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/wallet/travel-rule/withdraw-history\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"lending/auto-invest/redeem/history\", signed=True, data=params, version=1)\n\n    def margin_v2_get_localentity_withdraw_history(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v2/localentity/withdraw/history.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/wallet/travel-rule/withdraw-history-v2\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"localentity/withdraw/history\", signed=True, data=params, version=2)\n\n    def margin_v1_get_eth_staking_eth_history_redemption_history(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/eth-staking/eth/history/redemptionHistory.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/staking/eth-staking/history/Get-ETH-redemption-history\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"eth-staking/eth/history/redemptionHistory\", signed=True, data=params, version=1)\n\n    def futures_v1_get_fee_burn(self, **params):\n        \"\"\"\n        Placeholder function for GET /fapi/v1/feeBurn.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Get-BNB-Burn-Status\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_futures_api(\"get\", \"feeBurn\", signed=True, data=params, version=1)\n\n    def margin_v1_get_lending_auto_invest_index_user_summary(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/lending/auto-invest/index/user-summary.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"lending/auto-invest/index/user-summary\", signed=True, data=params, version=1)\n\n    def margin_v2_post_loan_flexible_borrow(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v2/loan/flexible/borrow.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/crypto_loan/flexible-rate/trade\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"loan/flexible/borrow\", signed=True, data=params, version=2)\n\n    def margin_v1_post_loan_vip_repay(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/loan/vip/repay.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/vip_loan/trade/VIP-Loan-Repay\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"loan/vip/repay\", signed=True, data=params, version=1)\n\n    def futures_coin_v1_get_commission_rate(self, **params):\n        \"\"\"\n        Placeholder function for GET /dapi/v1/commissionRate.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/account/rest-api/User-Commission-Rate\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_futures_coin_api(\"get\", \"commissionRate\", signed=True, data=params, version=1)\n\n    def margin_v1_get_convert_asset_info(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/convert/assetInfo.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/convert/market-data/Query-order-quantity-precision-per-asset\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"convert/assetInfo\", signed=True, data=params, version=1)\n\n    def v3_post_sor_order_test(self, **params):\n        \"\"\"\n        Placeholder function for POST /api/v3/sor/order/test.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_api(\"post\", \"sor/order/test\", signed=True, data=params, version=\"v3\")\n\n    def margin_v1_post_broker_universal_transfer(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/broker/universalTransfer.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/binance_link/exchange-link/asset/Universal-Transfer\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"broker/universalTransfer\", signed=True, data=params, version=1)\n\n    def margin_v1_post_account_disable_fast_withdraw_switch(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/account/disableFastWithdrawSwitch.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/wallet/account/disable-fast-withdraw-switch\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"account/disableFastWithdrawSwitch\", signed=True, data=params, version=1)\n\n    def futures_v1_get_asset_index(self, **params):\n        \"\"\"\n        Placeholder function for GET /fapi/v1/assetIndex.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/rest-api/Multi-Assets-Mode-Asset-Index\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_futures_api(\"get\", \"assetIndex\", signed=False, data=params, version=1)\n\n    def margin_v1_get_account_api_restrictions_ip_restriction(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/account/apiRestrictions/ipRestriction.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"account/apiRestrictions/ipRestriction\", signed=True, data=params, version=1)\n\n    def margin_v1_post_broker_sub_account_bnb_burn_spot(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/broker/subAccount/bnbBurn/spot.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/binance_link/exchange-link/account/Enable-Or-Disable-BNB-Burn-for-Sub-Account-Spot-Margin\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"broker/subAccount/bnbBurn/spot\", signed=True, data=params, version=1)\n\n    def futures_coin_v1_put_order(self, **params):\n        \"\"\"\n        Placeholder function for PUT /dapi/v1/order.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/rest-api/Modify-Order\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_futures_coin_api(\"put\", \"order\", signed=True, data=params, version=1)\n\n    def futures_coin_v1_put_batch_orders(self, **params):\n        \"\"\"\n        Placeholder function for PUT /dapi/v1/batchOrders.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/coin-margined-futures/trade/rest-api/Modify-Multiple-Orders\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_futures_coin_api(\"put\", \"batchOrders\", signed=True, data=params, version=1)\n\n    def margin_v1_get_margin_delist_schedule(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/margin/delist-schedule.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"margin/delist-schedule\", signed=True, data=params, version=1)\n\n    def margin_v1_post_broker_sub_account_api_permission_universal_transfer(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/broker/subAccountApi/permission/universalTransfer.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/binance_link/exchange-link/account/Enable-Universal-Transfer-Permission-For-SubAccount-Api-Key\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"broker/subAccountApi/permission/universalTransfer\", signed=True, data=params, version=1)\n\n    def margin_v1_get_loan_ltv_adjustment_history(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/loan/ltv/adjustment/history.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/crypto_loan/stable-rate/user-information/Get-Loan-LTV-Adjustment-History\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"loan/ltv/adjustment/history\", signed=True, data=params, version=1)\n\n    def margin_v1_get_localentity_withdraw_history(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/localentity/withdraw/history.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"localentity/withdraw/history\", signed=True, data=params, version=1)\n\n    def margin_v2_post_sub_account_sub_account_api_ip_restriction(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v2/sub-account/subAccountApi/ipRestriction.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/sub_account/api-management/Add-IP-Restriction-for-Sub-Account-API-key\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"sub-account/subAccountApi/ipRestriction\", signed=True, data=params, version=2)\n\n    def futures_v1_get_rate_limit_order(self, **params):\n        \"\"\"\n        Placeholder function for GET /fapi/v1/rateLimit/order.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Query-Rate-Limit\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_futures_api(\"get\", \"rateLimit/order\", signed=True, data=params, version=1)\n\n    def margin_v1_get_broker_sub_account_api_commission_futures(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/broker/subAccountApi/commission/futures.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/binance_link/exchange-link/fee/Query-Sub-Account-UM-Futures-Commission\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"broker/subAccountApi/commission/futures\", signed=True, data=params, version=1)\n\n    def margin_v1_get_sol_staking_sol_history_staking_history(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/sol-staking/sol/history/stakingHistory.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/staking/sol-staking/history\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"sol-staking/sol/history/stakingHistory\", signed=True, data=params, version=1)\n\n    def futures_v1_get_open_order(self, **params):\n        \"\"\"\n        Placeholder function for GET /fapi/v1/openOrder.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/Query-Current-Open-Order\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_futures_api(\"get\", \"openOrder\", signed=True, data=params, version=1)\n\n    def margin_v1_delete_algo_spot_order(self, **params):\n        \"\"\"\n        Placeholder function for DELETE /sapi/v1/algo/spot/order.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/algo/spot-algo/Cancel-Algo-Order\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"delete\", \"algo/spot/order\", signed=True, data=params, version=1)\n\n    def margin_v1_delete_account_api_restrictions_ip_restriction_ip_list(self, **params):\n        \"\"\"\n        Placeholder function for DELETE /sapi/v1/account/apiRestrictions/ipRestriction/ipList.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"delete\", \"account/apiRestrictions/ipRestriction/ipList\", signed=True, data=params, version=1)\n\n    def margin_v1_post_capital_contract_convertible_coins(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/capital/contract/convertible-coins.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"capital/contract/convertible-coins\", signed=True, data=params, version=1)\n\n    def margin_v1_get_managed_subaccount_margin_asset(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/managed-subaccount/marginAsset.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/sub_account/managed-sub-account/Query-Managed-Sub-account-Margin-Asset-Details\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"managed-subaccount/marginAsset\", signed=True, data=params, version=1)\n\n    def v3_delete_order_list(self, **params):\n        \"\"\"\n        Placeholder function for DELETE /api/v3/orderList.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_api(\"delete\", \"orderList\", signed=True, data=params, version=\"v3\")\n\n    def margin_v1_post_sub_account_sub_account_api_ip_restriction_ip_list(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/sub-account/subAccountApi/ipRestriction/ipList.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"sub-account/subAccountApi/ipRestriction/ipList\", signed=True, data=params, version=1)\n\n    def margin_v1_post_broker_sub_account_api_commission(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/broker/subAccountApi/commission.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/binance_link/exchange-link/fee\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"broker/subAccountApi/commission\", signed=True, data=params, version=1)\n\n    def futures_v1_post_fee_burn(self, **params):\n        \"\"\"\n        Placeholder function for POST /fapi/v1/feeBurn.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Toggle-BNB-Burn-On-Futures-Trade\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_futures_api(\"post\", \"feeBurn\", signed=True, data=params, version=1)\n\n    def margin_v1_get_broker_sub_account_margin_summary(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/broker/subAccount/marginSummary.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/binance_link/exchange-link/asset/Query-Sub-Account-Margin-Asset-Info\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"broker/subAccount/marginSummary\", signed=True, data=params, version=1)\n\n    def margin_v1_get_lending_auto_invest_plan_list(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/lending/auto-invest/plan/list.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"lending/auto-invest/plan/list\", signed=True, data=params, version=1)\n\n    def margin_v1_get_loan_vip_loanable_data(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/loan/vip/loanable/data.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/vip_loan/market-data/Get-Loanable-Assets-Data\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"loan/vip/loanable/data\", signed=True, data=params, version=1)\n\n    def margin_v2_get_loan_flexible_collateral_data(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v2/loan/flexible/collateral/data.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/crypto_loan/flexible-rate/market-data\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"loan/flexible/collateral/data\", signed=True, data=params, version=2)\n\n    def margin_v1_delete_broker_sub_account_api(self, **params):\n        \"\"\"\n        Placeholder function for DELETE /sapi/v1/broker/subAccountApi.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/binance_link/exchange-link/account/Delete-Sub-Account-Api-Key\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"delete\", \"broker/subAccountApi\", signed=True, data=params, version=1)\n\n    def margin_v1_get_sol_staking_sol_history_bnsol_rewards_history(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/sol-staking/sol/history/bnsolRewardsHistory.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/staking/sol-staking/history/Get-BNSOL-rewards-history\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"sol-staking/sol/history/bnsolRewardsHistory\", signed=True, data=params, version=1)\n\n    def margin_v1_get_convert_limit_query_open_orders(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/convert/limit/queryOpenOrders.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/convert/trade/Query-Order\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"convert/limit/queryOpenOrders\", signed=True, data=params, version=1)\n\n    def v3_get_account_commission(self, **params):\n        \"\"\"\n        Placeholder function for GET /api/v3/account/commission.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_api(\"get\", \"account/commission\", signed=True, data=params, version=\"v3\")\n\n    def margin_v1_get_managed_subaccount_query_trans_log(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/managed-subaccount/query-trans-log.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/sub_account/managed-sub-account/Query-Managed-Sub-Account-Transfer-Log-Trading-Team-Sub\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"managed-subaccount/query-trans-log\", signed=True, data=params, version=1)\n\n    def margin_v2_post_broker_sub_account_api_ip_restriction(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v2/broker/subAccountApi/ipRestriction.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/binance_link/exchange-link/account/Update-IP-Restriction-for-Sub-Account-API-key-For-Master-Account\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"broker/subAccountApi/ipRestriction\", signed=True, data=params, version=2)\n\n    def margin_v1_get_lending_auto_invest_all_asset(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/lending/auto-invest/all/asset.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"lending/auto-invest/all/asset\", signed=True, data=params, version=1)\n\n    def futures_v1_post_convert_accept_quote(self, **params):\n        \"\"\"\n        Placeholder function for POST /fapi/v1/convert/acceptQuote.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/convert/Accept-Quote\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_futures_api(\"post\", \"convert/acceptQuote\", signed=True, data=params, version=1)\n\n    def margin_v1_get_spot_delist_schedule(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/spot/delist-schedule.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/wallet/asset/spot-delist-schedule\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"spot/delist-schedule\", signed=True, data=params, version=1)\n\n    def margin_v1_post_account_api_restrictions_ip_restriction(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/account/apiRestrictions/ipRestriction.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"account/apiRestrictions/ipRestriction\", signed=True, data=params, version=1)\n\n    def margin_v1_get_dci_product_accounts(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/dci/product/accounts.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/dual_investment/trade/Check-Dual-Investment-accounts\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"dci/product/accounts\", signed=True, data=params, version=1)\n\n    def margin_v1_get_sub_account_sub_account_api_ip_restriction(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/sub-account/subAccountApi/ipRestriction.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/sub_account/api-management\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"sub-account/subAccountApi/ipRestriction\", signed=True, data=params, version=1)\n\n    def margin_v1_get_sub_account_transaction_statistics(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/sub-account/transaction-statistics.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/sub_account/account-management/Query-Sub-account-Transaction-Statistics\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"sub-account/transaction-statistics\", signed=True, data=params, version=1)\n\n    def margin_v1_get_managed_subaccount_deposit_address(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/managed-subaccount/deposit/address.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/sub_account/managed-sub-account/Get-Managed-Sub-account-Deposit-Address\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"managed-subaccount/deposit/address\", signed=True, data=params, version=1)\n\n    def margin_v2_get_portfolio_account(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v2/portfolio/account.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin-pro/account/Get-Classic-Portfolio-Margin-Account-Info-V2\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"portfolio/account\", signed=True, data=params, version=2)\n\n    def margin_v1_get_simple_earn_locked_history_redemption_record(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/simple-earn/locked/history/redemptionRecord.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/simple_earn/history/Get-Locked-Redemption-Record\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"simple-earn/locked/history/redemptionRecord\", signed=True, data=params, version=1)\n\n    def futures_v1_get_order_asyn_id(self, **params):\n        \"\"\"\n        Placeholder function for GET /fapi/v1/order/asyn/id.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/account/rest-api/Get-Futures-Order-History-Download-Link-by-Id\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_futures_api(\"get\", \"order/asyn/id\", signed=True, data=params, version=1)\n\n    def margin_v1_post_managed_subaccount_withdraw(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/managed-subaccount/withdraw.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/sub_account/managed-sub-account/Withdrawl-Assets-From-The-Managed-Sub-account\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"managed-subaccount/withdraw\", signed=True, data=params, version=1)\n\n    def margin_v1_get_localentity_deposit_history(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/localentity/deposit/history.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/wallet/travel-rule/deposit-history\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"localentity/deposit/history\", signed=True, data=params, version=1)\n\n    def margin_v1_post_eth_staking_wbeth_wrap(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/eth-staking/wbeth/wrap.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/staking/eth-staking/staking/Wrap-BETH\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"eth-staking/wbeth/wrap\", signed=True, data=params, version=1)\n\n    def margin_v1_post_simple_earn_locked_set_redeem_option(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/simple-earn/locked/setRedeemOption.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/simple_earn/earn/Set-Locked-Redeem-Option\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"simple-earn/locked/setRedeemOption\", signed=True, data=params, version=1)\n\n    def margin_v1_post_broker_sub_account_api_ip_restriction_ip_list(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/broker/subAccountApi/ipRestriction/ipList.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"broker/subAccountApi/ipRestriction/ipList\", signed=True, data=params, version=1)\n\n    def margin_v1_post_broker_sub_account_api_commission_futures(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/broker/subAccountApi/commission/futures.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/binance_link/exchange-link/fee/Change-Sub-Account-UM-Futures-Commission\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"broker/subAccountApi/commission/futures\", signed=True, data=params, version=1)\n\n    def margin_v1_get_lending_auto_invest_history_list(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/lending/auto-invest/history/list.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"lending/auto-invest/history/list\", signed=True, data=params, version=1)\n\n    def margin_v1_post_loan_customize_margin_call(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/loan/customize/margin_call.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"loan/customize/margin_call\", signed=True, data=params, version=1)\n\n    def margin_v1_get_broker_sub_account_bnb_burn_status(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/broker/subAccount/bnbBurn/status.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/binance_link/exchange-link/account/Get-BNB-Burn-Status-for-Sub-Account\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"broker/subAccount/bnbBurn/status\", signed=True, data=params, version=1)\n\n    def margin_v1_get_managed_subaccount_account_snapshot(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/managed-subaccount/accountSnapshot.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/sub_account/managed-sub-account/Query-Managed-Sub-account-Snapshot\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"managed-subaccount/accountSnapshot\", signed=True, data=params, version=1)\n\n    def margin_v1_post_asset_convert_transfer(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/asset/convert-transfer.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"asset/convert-transfer\", signed=True, data=params, version=1)\n\n    def options_v1_get_income_asyn(self, **params):\n        \"\"\"\n        Placeholder function for GET /eapi/v1/income/asyn.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/option/account/Get-Download-Id-For-Option-Transaction-History\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_options_api(\"get\", \"income/asyn\", signed=True, data=params)\n\n    def margin_v1_get_broker_sub_account_api_commission_coin_futures(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/broker/subAccountApi/commission/coinFutures.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/binance_link/exchange-link/fee/Query-Sub-Account-CM-Futures-Commission\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"broker/subAccountApi/commission/coinFutures\", signed=True, data=params, version=1)\n\n    def margin_v2_get_broker_sub_account_futures_summary(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v2/broker/subAccount/futuresSummary.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"broker/subAccount/futuresSummary\", signed=True, data=params, version=2)\n\n    def margin_v1_get_loan_ongoing_orders(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/loan/ongoing/orders.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"loan/ongoing/orders\", signed=True, data=params, version=1)\n\n    def margin_v2_get_loan_flexible_ongoing_orders(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v2/loan/flexible/ongoing/orders.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/crypto_loan/flexible-rate/user-information/Get-Flexible-Loan-Ongoing-Orders\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"loan/flexible/ongoing/orders\", signed=True, data=params, version=2)\n\n    def margin_v1_post_algo_futures_new_order_vp(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/algo/futures/newOrderVp.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/algo/future-algo\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"algo/futures/newOrderVp\", signed=True, data=params, version=1)\n\n    def futures_v1_post_convert_get_quote(self, **params):\n        \"\"\"\n        Placeholder function for POST /fapi/v1/convert/getQuote.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/convert/Send-quote-request\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_futures_api(\"post\", \"convert/getQuote\", signed=True, data=params, version=1)\n\n    def margin_v1_get_algo_spot_sub_orders(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/algo/spot/subOrders.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/algo/spot-algo/Query-Sub-Orders\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"algo/spot/subOrders\", signed=True, data=params, version=1)\n\n    def margin_v1_post_portfolio_redeem(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/portfolio/redeem.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/portfolio-margin-pro/account/Redeem-BFUSD-Portfolio-Margin\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"portfolio/redeem\", signed=True, data=params, version=1)\n\n    def margin_v1_post_lending_auto_invest_plan_add(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/lending/auto-invest/plan/add.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"lending/auto-invest/plan/add\", signed=True, data=params, version=1)\n\n    def v3_get_order_list(self, **params):\n        \"\"\"\n        Placeholder function for GET /api/v3/orderList.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_api(\"get\", \"orderList\", signed=True, data=params, version=\"v3\")\n\n    def margin_v1_get_lending_auto_invest_source_asset_list(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/lending/auto-invest/source-asset/list.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"lending/auto-invest/source-asset/list\", signed=True, data=params, version=1)\n\n    def margin_v1_get_margin_all_order_list(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/margin/allOrderList.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/margin_trading/trade/Query-Margin-Account-All-OCO\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"margin/allOrderList\", signed=True, data=params, version=1)\n\n    def margin_v1_post_eth_staking_eth_redeem(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/eth-staking/eth/redeem.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/staking/eth-staking/staking/Redeem-ETH\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"eth-staking/eth/redeem\", signed=True, data=params, version=1)\n\n    def margin_v1_get_broker_rebate_historical_record(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/broker/rebate/historicalRecord.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"broker/rebate/historicalRecord\", signed=True, data=params, version=1)\n\n    def margin_v1_get_simple_earn_locked_history_subscription_record(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/simple-earn/locked/history/subscriptionRecord.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/simple_earn/history/Get-Locked-Subscription-Record\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"simple-earn/locked/history/subscriptionRecord\", signed=True, data=params, version=1)\n\n    def margin_v1_get_managed_subaccount_asset(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/managed-subaccount/asset.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/sub_account/managed-sub-account/Query-Managed-Sub-account-Asset-Details\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"managed-subaccount/asset\", signed=True, data=params, version=1)\n\n    def margin_v1_get_sol_staking_sol_quota(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/sol-staking/sol/quota.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/staking/sol-staking/account/Get-SOL-staking-quota-details\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"sol-staking/sol/quota\", signed=True, data=params, version=1)\n\n    def margin_v1_post_loan_vip_renew(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/loan/vip/renew.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"loan/vip/renew\", signed=True, data=params, version=1)\n\n    def margin_v1_get_managed_subaccount_query_trans_log_for_trade_parent(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/managed-subaccount/queryTransLogForTradeParent.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/sub_account/managed-sub-account/Query-Managed-Sub-Account-Transfer-Log-Trading-Team-Master\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"managed-subaccount/queryTransLogForTradeParent\", signed=True, data=params, version=1)\n\n    def margin_v1_post_sub_account_sub_account_api_ip_restriction(self, **params):\n        \"\"\"\n        Placeholder function for POST /sapi/v1/sub-account/subAccountApi/ipRestriction.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"post\", \"sub-account/subAccountApi/ipRestriction\", signed=True, data=params, version=1)\n\n    def margin_v1_get_simple_earn_flexible_history_redemption_record(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/simple-earn/flexible/history/redemptionRecord.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/simple_earn/history/Get-Flexible-Redemption-Record\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"simple-earn/flexible/history/redemptionRecord\", signed=True, data=params, version=1)\n\n    def margin_v1_get_broker_sub_account_api(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/broker/subAccountApi.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/binance_link/exchange-link/account/Query-Sub-Account-Api-Key\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"broker/subAccountApi\", signed=True, data=params, version=1)\n\n    def options_v1_get_exercise_history(self, **params):\n        \"\"\"\n        Placeholder function for GET /eapi/v1/exerciseHistory.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/option/market-data/Historical-Exercise-Records\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_options_api(\"get\", \"exerciseHistory\", signed=False, data=params)\n\n    def options_open_interest(self, **params):\n        \"\"\"Get present open interest specific underlying asset on specific expiration date.\n\n        https://developers.binance.com/docs/derivatives/option/market-data/Open-Interest\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n        :param underlyingAsset: required\n        :type underlyingAsset: str\n        :param expiration: required (e.g '221225')\n        :type expiration: str\n\n        \"\"\"\n        return self._request_options_api(\"get\", \"openInterest\", data=params)\n\n    def margin_v1_get_convert_exchange_info(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/convert/exchangeInfo.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/convert/market-data\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"convert/exchangeInfo\", signed=False, data=params, version=1)\n\n    def futures_v1_delete_batch_order(self, **params):\n        \"\"\"\n        Placeholder function for DELETE /fapi/v1/batchOrder.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_futures_api(\"delete\", \"batchOrder\", signed=True, data=params, version=1)\n\n    def margin_v1_get_eth_staking_eth_history_wbeth_rewards_history(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/eth-staking/eth/history/wbethRewardsHistory.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/staking/eth-staking/history/Get-WBETH-rewards-history\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"eth-staking/eth/history/wbethRewardsHistory\", signed=True, data=params, version=1)\n\n    def margin_v1_get_mining_pub_algo_list(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/mining/pub/algoList.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/mining/rest-api\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"mining/pub/algoList\", signed=True, data=params, version=1)\n\n    def options_v1_get_block_trades(self, **params):\n        \"\"\"\n        Placeholder function for GET /eapi/v1/blockTrades.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/option/market-data/Recent-Block-Trade-List\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_options_api(\"get\", \"blockTrades\", signed=False, data=params)\n\n    def margin_v1_get_copy_trading_futures_lead_symbol(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/copyTrading/futures/leadSymbol.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/copy_trading/future-copy-trading/Get-Futures-Lead-Trading-Symbol-Whitelist\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"copyTrading/futures/leadSymbol\", signed=True, data=params, version=1)\n\n    def margin_v1_get_mining_worker_list(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/mining/worker/list.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/mining/rest-api/Request-for-Miner-List\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"mining/worker/list\", signed=True, data=params, version=1)\n\n    def margin_v1_get_dci_product_list(self, **params):\n        \"\"\"\n        Placeholder function for GET /sapi/v1/dci/product/list.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/dual_investment/market-data\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_margin_api(\"get\", \"dci/product/list\", signed=True, data=params, version=1)\n\n    def futures_v1_get_convert_order_status(self, **params):\n        \"\"\"\n        Placeholder function for GET /fapi/v1/convert/orderStatus.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/convert/Order-Status\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \"\"\"\n        return self._request_futures_api(\"get\", \"convert/orderStatus\", signed=True, data=params, version=1)\n"
  },
  {
    "path": "binance/enums.py",
    "content": "from enum import Enum\n\nSYMBOL_TYPE_SPOT = \"SPOT\"\n\nORDER_STATUS_NEW = \"NEW\"\nORDER_STATUS_PARTIALLY_FILLED = \"PARTIALLY_FILLED\"\nORDER_STATUS_FILLED = \"FILLED\"\nORDER_STATUS_CANCELED = \"CANCELED\"\nORDER_STATUS_PENDING_CANCEL = \"PENDING_CANCEL\"\nORDER_STATUS_REJECTED = \"REJECTED\"\nORDER_STATUS_EXPIRED = \"EXPIRED\"\nORDER_STATUS_ACCEPTED = \"ACCEPTED\"\nORDER_STATUS_TRIGGERING = \"TRIGGERING\"\nORDER_STATUS_TRIGGERED = \"TRIGGERED\"\nORDER_STATUS_FINISHED = \"FINISHED\"\n\nKLINE_INTERVAL_1SECOND = \"1s\"\nKLINE_INTERVAL_1MINUTE = \"1m\"\nKLINE_INTERVAL_3MINUTE = \"3m\"\nKLINE_INTERVAL_5MINUTE = \"5m\"\nKLINE_INTERVAL_15MINUTE = \"15m\"\nKLINE_INTERVAL_30MINUTE = \"30m\"\nKLINE_INTERVAL_1HOUR = \"1h\"\nKLINE_INTERVAL_2HOUR = \"2h\"\nKLINE_INTERVAL_4HOUR = \"4h\"\nKLINE_INTERVAL_6HOUR = \"6h\"\nKLINE_INTERVAL_8HOUR = \"8h\"\nKLINE_INTERVAL_12HOUR = \"12h\"\nKLINE_INTERVAL_1DAY = \"1d\"\nKLINE_INTERVAL_3DAY = \"3d\"\nKLINE_INTERVAL_1WEEK = \"1w\"\nKLINE_INTERVAL_1MONTH = \"1M\"\n\nSIDE_BUY = \"BUY\"\nSIDE_SELL = \"SELL\"\n\nORDER_TYPE_LIMIT = \"LIMIT\"\nORDER_TYPE_MARKET = \"MARKET\"\nORDER_TYPE_STOP_LOSS = \"STOP_LOSS\"\nORDER_TYPE_STOP_LOSS_LIMIT = \"STOP_LOSS_LIMIT\"\nORDER_TYPE_TAKE_PROFIT = \"TAKE_PROFIT\"\nORDER_TYPE_TAKE_PROFIT_LIMIT = \"TAKE_PROFIT_LIMIT\"\nORDER_TYPE_LIMIT_MAKER = \"LIMIT_MAKER\"\n\nFUTURE_ORDER_TYPE_LIMIT = \"LIMIT\"\nFUTURE_ORDER_TYPE_MARKET = \"MARKET\"\nFUTURE_ORDER_TYPE_STOP = \"STOP\"\nFUTURE_ORDER_TYPE_STOP_MARKET = \"STOP_MARKET\"\nFUTURE_ORDER_TYPE_TAKE_PROFIT = \"TAKE_PROFIT\"\nFUTURE_ORDER_TYPE_TAKE_PROFIT_MARKET = \"TAKE_PROFIT_MARKET\"\nFUTURE_ORDER_TYPE_LIMIT_MAKER = \"LIMIT_MAKER\"\nFUTURE_ORDER_TYPE_TRAILING_STOP_MARKET = \"TRAILING_STOP_MARKET\"\n\nTIME_IN_FORCE_GTC = \"GTC\"  # Good till cancelled\nTIME_IN_FORCE_IOC = \"IOC\"  # Immediate or cancel\nTIME_IN_FORCE_FOK = \"FOK\"  # Fill or kill\nTIME_IN_FORCE_GTX = \"GTX\"  # Post only order\nTIME_IN_FORCE_GTD = \"GTD\"  # Good till date\nTIME_IN_FORCE_RPI = \"RPI\"  # Retail Price Improvement\n\nORDER_RESP_TYPE_ACK = \"ACK\"\nORDER_RESP_TYPE_RESULT = \"RESULT\"\nORDER_RESP_TYPE_FULL = \"FULL\"\n\nWEBSOCKET_DEPTH_5 = \"5\"\nWEBSOCKET_DEPTH_10 = \"10\"\nWEBSOCKET_DEPTH_20 = \"20\"\n\nNO_SIDE_EFFECT_TYPE = \"NO_SIDE_EFFECT\"\nMARGIN_BUY_TYPE = \"MARGIN_BUY\"\nAUTO_REPAY_TYPE = \"AUTO_REPAY\"\n\n\nclass HistoricalKlinesType(Enum):\n    SPOT = 1\n    FUTURES = 2\n    FUTURES_COIN = 3\n    FUTURES_MARK_PRICE = 4\n    FUTURES_INDEX_PRICE = 5\n    FUTURES_COIN_MARK_PRICE = 6\n    FUTURES_COIN_INDEX_PRICE = 7\n\n\nclass FuturesType(Enum):\n    USD_M = 1\n    COIN_M = 2\n\n\nclass ContractType(Enum):\n    PERPETUAL = \"perpetual\"\n    CURRENT_QUARTER = \"current_quarter\"\n    NEXT_QUARTER = \"next_quarter\"\n"
  },
  {
    "path": "binance/exceptions.py",
    "content": "# coding=utf-8\nimport json\n\n\nclass BinanceAPIException(Exception):\n    def __init__(self, response, status_code, text):\n        self.code = 0\n        try:\n            json_res = json.loads(text)\n        except ValueError:\n            self.message = \"Invalid JSON error message from Binance: {}\".format(\n                response.text\n            )\n        else:\n            self.code = json_res.get(\"code\")\n            self.message = json_res.get(\"msg\")\n        self.status_code = status_code\n        self.response = response\n        self.request = getattr(response, \"request\", None)\n\n    def __str__(self):  # pragma: no cover\n        return \"APIError(code=%s): %s\" % (self.code, self.message)\n\n\nclass BinanceRequestException(Exception):\n    def __init__(self, message):\n        self.message = message\n\n    def __str__(self):\n        return \"BinanceRequestException: %s\" % self.message\n\n\nclass BinanceOrderException(Exception):\n    def __init__(self, code, message):\n        self.code = code\n        self.message = message\n\n    def __str__(self):\n        return \"BinanceOrderException(code=%s): %s\" % (self.code, self.message)\n\n\nclass BinanceOrderMinAmountException(BinanceOrderException):\n    def __init__(self, value):\n        message = \"Amount must be a multiple of %s\" % value\n        super().__init__(-1013, message)\n\n\nclass BinanceOrderMinPriceException(BinanceOrderException):\n    def __init__(self, value):\n        message = \"Price must be at least %s\" % value\n        super().__init__(-1013, message)\n\n\nclass BinanceOrderMinTotalException(BinanceOrderException):\n    def __init__(self, value):\n        message = \"Total must be at least %s\" % value\n        super().__init__(-1013, message)\n\n\nclass BinanceOrderUnknownSymbolException(BinanceOrderException):\n    def __init__(self, value):\n        message = \"Unknown symbol %s\" % value\n        super().__init__(-1013, message)\n\n\nclass BinanceOrderInactiveSymbolException(BinanceOrderException):\n    def __init__(self, value):\n        message = \"Attempting to trade an inactive symbol %s\" % value\n        super().__init__(-1013, message)\n\n\nclass BinanceWebsocketUnableToConnect(Exception):\n    pass\n\n\nclass BinanceWebsocketQueueOverflow(Exception):\n    \"\"\"Raised when the websocket message queue exceeds its maximum size.\"\"\"\n    pass\n\nclass BinanceWebsocketClosed(Exception):\n    \"\"\"Raised when websocket connection is closed.\"\"\"\n    pass\n\nclass ReadLoopClosed(Exception):\n    \"\"\"Raised when trying to read from read loop but already closed\"\"\"\n    pass\n\nclass NotImplementedException(Exception):\n    def __init__(self, value):\n        message = f\"Not implemented: {value}\"\n        super().__init__(message)\n\n\nclass UnknownDateFormat(Exception):\n    ...\n\n\nclass BinanceRegionException(Exception):\n    \"\"\"Raised when using a region-specific endpoint with incompatible client.\"\"\"\n\n    def __init__(\n        self, required_tld: str, actual_tld: str, endpoint_name: str = \"endpoint\"\n    ):\n        self.required_tld = required_tld\n        self.actual_tld = actual_tld\n        self.endpoint_name = endpoint_name\n        self.message = (\n            f\"{endpoint_name} is only available on binance.{required_tld}, \"\n            f\"but client is configured for binance.{actual_tld}\"\n        )\n        super().__init__(self.message)\n\n    def __str__(self):\n        return f\"BinanceRegionException: {self.message}\"\n"
  },
  {
    "path": "binance/helpers.py",
    "content": "import asyncio\nfrom decimal import Decimal\nimport json\nfrom typing import Union, Optional, Dict\n\nimport dateparser\nimport pytz\n\nfrom datetime import datetime, timezone\n\nfrom binance.exceptions import UnknownDateFormat\n\n\ndef date_to_milliseconds(date_str: str) -> int:\n    \"\"\"Convert UTC date to milliseconds\n\n    If using offset strings add \"UTC\" to date string e.g. \"now UTC\", \"11 hours ago UTC\"\n\n    See dateparse docs for formats http://dateparser.readthedocs.io/en/latest/\n\n    :param date_str: date in readable format, i.e. \"January 01, 2018\", \"11 hours ago UTC\", \"now UTC\"\n    \"\"\"\n    # get epoch value in UTC\n    epoch: datetime = datetime.fromtimestamp(0,timezone.utc)\n    # parse our date string\n    d: Optional[datetime] = dateparser.parse(date_str, settings={\"TIMEZONE\": \"UTC\"})\n    if not d:\n        raise UnknownDateFormat(date_str)\n\n    # if the date is not timezone aware apply UTC timezone\n    if d.tzinfo is None or d.tzinfo.utcoffset(d) is None:\n        d = d.replace(tzinfo=pytz.utc)\n\n    # return the difference in time\n    return int((d - epoch).total_seconds() * 1000.0)\n\n\ndef interval_to_milliseconds(interval: str) -> Optional[int]:\n    \"\"\"Convert a Binance interval string to milliseconds\n\n    :param interval: Binance interval string, e.g.: 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w\n\n    :return:\n         int value of interval in milliseconds\n         None if interval prefix is not a decimal integer\n         None if interval suffix is not one of m, h, d, w\n\n    \"\"\"\n    seconds_per_unit: Dict[str, int] = {\n        \"s\": 1,\n        \"m\": 60,\n        \"h\": 60 * 60,\n        \"d\": 24 * 60 * 60,\n        \"w\": 7 * 24 * 60 * 60,\n    }\n    try:\n        return int(interval[:-1]) * seconds_per_unit[interval[-1]] * 1000\n    except (ValueError, KeyError):\n        return None\n\n\ndef round_step_size(\n    quantity: Union[float, Decimal], step_size: Union[float, Decimal]\n) -> float:\n    \"\"\"Rounds a given quantity to a specific step size\n\n    :param quantity: required\n    :param step_size: required\n\n    :return: decimal\n    \"\"\"\n    quantity = Decimal(str(quantity))\n    return float(quantity - quantity % Decimal(str(step_size)))\n\n\ndef convert_ts_str(ts_str):\n    if ts_str is None:\n        return ts_str\n    if isinstance(ts_str, int):\n        return ts_str\n    return date_to_milliseconds(ts_str)\n\n\ndef convert_list_to_json_array(l):\n    if l is None:\n        return l\n    res = json.dumps(l)\n    return res.replace(\" \", \"\")\n\n\ndef get_loop():\n    \"\"\"check if there is an event loop in the current thread, if not create one\n    inspired by https://stackoverflow.com/questions/46727787/runtimeerror-there-is-no-current-event-loop-in-thread-in-async-apscheduler\n    \"\"\"\n    try:\n        loop = asyncio.get_event_loop()\n        return loop\n    except RuntimeError as e:\n        if str(e).startswith(\"There is no current event loop in thread\"):\n            loop = asyncio.new_event_loop()\n            asyncio.set_event_loop(loop)\n            return loop\n        else:\n            raise\n"
  },
  {
    "path": "binance/ws/__init__.py",
    "content": ""
  },
  {
    "path": "binance/ws/constants.py",
    "content": "from enum import Enum\n\nKEEPALIVE_TIMEOUT = 5 * 60  # 5 minutes\n\n\nclass WSListenerState(Enum):\n    INITIALISING = \"Initialising\"\n    STREAMING = \"Streaming\"\n    RECONNECTING = \"Reconnecting\"\n    EXITING = \"Exiting\"\n"
  },
  {
    "path": "binance/ws/depthcache.py",
    "content": "import logging\nfrom operator import itemgetter\nimport asyncio\nimport time\nfrom typing import Optional, Dict, Callable\n\nfrom ..helpers import get_loop\nfrom .streams import BinanceSocketManager\nfrom .threaded_stream import ThreadedApiManager\n\n\nclass DepthCache(object):\n    def __init__(self, symbol, conv_type: Callable = float):\n        \"\"\"Initialise the DepthCache\n\n        :param symbol: Symbol to create depth cache for\n        :type symbol: string\n        :param conv_type: Optional type to represent price, and amount, default is float.\n        :type conv_type: function.\n\n        \"\"\"\n        self.symbol = symbol\n        self._bids = {}\n        self._asks = {}\n        self.update_time = None\n        self.conv_type: Callable = conv_type\n        self._log = logging.getLogger(__name__)\n\n    def add_bid(self, bid):\n        \"\"\"Add a bid to the cache\n\n        :param bid:\n        :return:\n\n        \"\"\"\n        self._bids[bid[0]] = self.conv_type(bid[1])\n        if bid[1] == \"0.00000000\":\n            del self._bids[bid[0]]\n\n    def add_ask(self, ask):\n        \"\"\"Add an ask to the cache\n\n        :param ask:\n        :return:\n\n        \"\"\"\n        self._asks[ask[0]] = self.conv_type(ask[1])\n        if ask[1] == \"0.00000000\":\n            del self._asks[ask[0]]\n\n    def get_bids(self):\n        \"\"\"Get the current bids\n\n        :return: list of bids with price and quantity as conv_type\n\n        .. code-block:: python\n\n            [\n                [\n                    0.0001946,  # Price\n                    45.0        # Quantity\n                ],\n                [\n                    0.00019459,\n                    2384.0\n                ],\n                [\n                    0.00019158,\n                    5219.0\n                ],\n                [\n                    0.00019157,\n                    1180.0\n                ],\n                [\n                    0.00019082,\n                    287.0\n                ]\n            ]\n\n        \"\"\"\n        return DepthCache.sort_depth(self._bids, reverse=True, conv_type=self.conv_type)\n\n    def get_asks(self):\n        \"\"\"Get the current asks\n\n        :return: list of asks with price and quantity as conv_type.\n\n        .. code-block:: python\n\n            [\n                [\n                    0.0001955,  # Price\n                    57.0'       # Quantity\n                ],\n                [\n                    0.00019699,\n                    778.0\n                ],\n                [\n                    0.000197,\n                    64.0\n                ],\n                [\n                    0.00019709,\n                    1130.0\n                ],\n                [\n                    0.0001971,\n                    385.0\n                ]\n            ]\n\n        \"\"\"\n        return DepthCache.sort_depth(\n            self._asks, reverse=False, conv_type=self.conv_type\n        )\n\n    @staticmethod\n    def sort_depth(vals, reverse=False, conv_type: Callable = float):\n        \"\"\"Sort bids or asks by price\"\"\"\n        if isinstance(vals, dict):\n            lst = [\n                [conv_type(price), conv_type(quantity)]\n                for price, quantity in vals.items()\n            ]\n        elif isinstance(vals, list):\n            lst = [[conv_type(price), conv_type(quantity)] for price, quantity in vals]\n        else:\n            raise ValueError(f\"Unknown order book depth data type: {type(vals)}\")\n        lst = sorted(lst, key=itemgetter(0), reverse=reverse)\n        return lst\n\n\nDEFAULT_REFRESH = 60 * 30  # 30 minutes\n\n\nclass BaseDepthCacheManager:\n    TIMEOUT = 60\n\n    def __init__(\n        self,\n        client,\n        symbol,\n        loop=None,\n        refresh_interval: Optional[int] = DEFAULT_REFRESH,\n        bm=None,\n        limit=10,\n        conv_type=float,\n    ):\n        \"\"\"Create a DepthCacheManager instance\n\n        :param client: Binance API client\n        :type client: binance.Client\n        :param loop:\n        :type loop:\n        :param symbol: Symbol to create depth cache for\n        :type symbol: string\n        :param refresh_interval: Optional number of seconds between cache refresh, use 0 or None to disable\n        :type refresh_interval: int\n        :param bm: Optional BinanceSocketManager\n        :type bm: BinanceSocketManager\n        :param limit: Optional number of orders to get from orderbook\n        :type limit: int\n        :param conv_type: Optional type to represent price, and amount, default is float.\n        :type conv_type: function.\n\n        \"\"\"\n\n        self._client = client\n        self._depth_cache = None\n        self._loop = loop or get_loop()\n        self._symbol = symbol\n        self._limit = limit\n        self._last_update_id = None\n        self._bm = bm or BinanceSocketManager(self._client)\n        self._refresh_interval = refresh_interval\n        self._conn_key = None\n        self._conv_type = conv_type\n        self._log = logging.getLogger(__name__)\n\n    async def __aenter__(self):\n        await asyncio.gather(self._init_cache(), self._start_socket())\n        await self._socket.__aenter__()\n        return self\n\n    async def __aexit__(self, *args, **kwargs):\n        self._log.debug(f\"Exiting depth cache manager for {self._symbol}\")\n        await self._socket.__aexit__(*args, **kwargs)\n\n    async def recv(self):\n        dc = None\n        while not dc:\n            try:\n                res = await asyncio.wait_for(self._socket.recv(), timeout=self.TIMEOUT)\n                self._log.debug(f\"Received message: {res}\")\n            except Exception as e:\n                self._log.warning(f\"Exception recieving message: {e.__class__.__name__} (e) \")\n            else:\n                dc = await self._depth_event(res)\n        return dc\n\n    async def _init_cache(self):\n        \"\"\"Initialise the depth cache calling REST endpoint\n\n        :return:\n        \"\"\"\n        self._log.debug(f\"Initialising depth cache for {self._symbol}\")\n        # initialise or clear depth cache\n        self._depth_cache = DepthCache(self._symbol, conv_type=self._conv_type)\n\n        # set a time to refresh the depth cache\n        if self._refresh_interval:\n            self._refresh_time = int(time.time()) + self._refresh_interval\n\n    async def _start_socket(self):\n        \"\"\"Start the depth cache socket\n\n        :return:\n        \"\"\"\n        self._socket = self._get_socket()\n\n    def _get_socket(self):\n        raise NotImplementedError\n\n    async def _depth_event(self, msg):\n        \"\"\"Handle a depth event\n\n        :param msg:\n        :return:\n\n        \"\"\"\n        self._log.debug(f\"Received depth event: {msg}\")\n\n        if not msg:\n            return None\n\n        if \"e\" in msg and msg[\"e\"] == \"error\":\n            # notify user by return msg with error\n            self._log.error(f\"Error in depth event restarting cache: {msg}\")\n            return msg\n\n        return await self._process_depth_message(msg)\n\n    async def _process_depth_message(self, msg):\n        \"\"\"Process a depth event message.\n\n        :param msg: Depth event message.\n        :return:\n\n        \"\"\"\n\n        # add any bid or ask values\n        self._apply_orders(msg)\n\n        # call the callback with the updated depth cache\n        res = self._depth_cache\n\n        # after processing event see if we need to refresh the depth cache\n        if self._refresh_interval and int(time.time()) > self._refresh_time:\n            await self._init_cache()\n\n        return res\n\n    def _apply_orders(self, msg):\n        assert self._depth_cache\n        for bid in msg.get(\"b\", []) + msg.get(\"bids\", []):\n            self._depth_cache.add_bid(bid)\n        for ask in msg.get(\"a\", []) + msg.get(\"asks\", []):\n            self._depth_cache.add_ask(ask)\n\n        # keeping update time\n        self._depth_cache.update_time = msg.get(\"E\") or msg.get(\"lastUpdateId\")\n\n    def get_depth_cache(self):\n        \"\"\"Get the current depth cache\n\n        :return: DepthCache object\n\n        \"\"\"\n        return self._depth_cache\n\n    async def close(self):\n        \"\"\"Close the open socket for this manager\n\n        :return:\n        \"\"\"\n        self._depth_cache = None\n\n    def get_symbol(self):\n        \"\"\"Get the symbol\n\n        :return: symbol\n        \"\"\"\n        return self._symbol\n\n\nclass DepthCacheManager(BaseDepthCacheManager):\n    def __init__(\n        self,\n        client,\n        symbol,\n        loop=None,\n        refresh_interval: Optional[int] = None,\n        bm=None,\n        limit=500,\n        conv_type=float,\n        ws_interval=None,\n    ):\n        \"\"\"Initialise the DepthCacheManager\n\n        :param client: Binance API client\n        :type client: binance.Client\n        :param loop: asyncio loop\n        :param symbol: Symbol to create depth cache for\n        :type symbol: string\n        :param refresh_interval: Optional number of seconds between cache refresh, use 0 or None to disable\n        :type refresh_interval: int\n        :param limit: Optional number of orders to get from orderbook\n        :type limit: int\n        :param conv_type: Optional type to represent price, and amount, default is float.\n        :type conv_type: function.\n        :param ws_interval: Optional interval for updates on websocket, default None. If not set, updates happen every second. Must be 0, None (1s) or 100 (100ms).\n        :type ws_interval: int\n\n        \"\"\"\n        super().__init__(client, symbol, loop, refresh_interval, bm, limit, conv_type)\n        self._ws_interval = ws_interval\n\n    async def _init_cache(self):\n        \"\"\"Initialise the depth cache calling REST endpoint\n\n        :return:\n        \"\"\"\n        self._last_update_id = None\n        self._depth_message_buffer = []\n\n        res = await self._client.get_order_book(symbol=self._symbol, limit=self._limit)\n\n        # initialise or clear depth cache\n        await super()._init_cache()\n\n        # process bid and asks from the order book\n        self._apply_orders(res)\n        assert self._depth_cache\n        for bid in res[\"bids\"]:\n            self._depth_cache.add_bid(bid)\n        for ask in res[\"asks\"]:\n            self._depth_cache.add_ask(ask)\n\n        # set first update id\n        self._last_update_id = res[\"lastUpdateId\"]\n\n        # Apply any updates from the websocket\n        for msg in self._depth_message_buffer:\n            await self._process_depth_message(msg)\n\n        # clear the depth buffer\n        self._depth_message_buffer = []\n\n    async def _start_socket(self):\n        \"\"\"Start the depth cache socket\n\n        :return:\n        \"\"\"\n        if not getattr(self, \"_depth_message_buffer\", None):\n            self._depth_message_buffer = []\n\n        await super()._start_socket()\n\n    def _get_socket(self):\n        return self._bm.depth_socket(self._symbol, interval=self._ws_interval)\n\n    async def _process_depth_message(self, msg):\n        \"\"\"Process a depth event message.\n\n        :param msg: Depth event message.\n        :return:\n\n        \"\"\"\n\n        if self._last_update_id is None:\n            # Initial depth snapshot fetch not yet performed, buffer messages\n            self._depth_message_buffer.append(msg)\n            return\n\n        if msg[\"u\"] <= self._last_update_id:\n            # ignore any updates before the initial update id\n            return\n        elif msg[\"U\"] != self._last_update_id + 1:\n            # if not buffered check we get sequential updates\n            # otherwise init cache again\n            await self._init_cache()\n\n        # add any bid or ask values\n        self._apply_orders(msg)\n\n        # call the callback with the updated depth cache\n        res = self._depth_cache\n\n        self._last_update_id = msg[\"u\"]\n\n        # after processing event see if we need to refresh the depth cache\n        if self._refresh_interval and int(time.time()) > self._refresh_time:\n            await self._init_cache()\n\n        return res\n\n\nclass FuturesDepthCacheManager(BaseDepthCacheManager):\n    async def _process_depth_message(self, msg):\n        \"\"\"Process a depth event message.\n\n        :param msg: Depth event message.\n        :return:\n\n        \"\"\"\n        msg = msg.get(\"data\")\n        return await super()._process_depth_message(msg)\n\n    def _apply_orders(self, msg):\n        assert self._depth_cache\n        self._depth_cache._bids = msg.get(\"b\", [])\n        self._depth_cache._asks = msg.get(\"a\", [])\n\n        # keeping update time\n        self._depth_cache.update_time = msg.get(\"E\") or msg.get(\"lastUpdateId\")\n\n    def _get_socket(self):\n        sock = self._bm.futures_depth_socket(self._symbol)\n        return sock\n\n\nclass OptionsDepthCacheManager(BaseDepthCacheManager):\n    def _get_socket(self):\n        return self._bm.options_depth_socket(self._symbol)\n\n\nclass ThreadedDepthCacheManager(ThreadedApiManager):\n    def __init__(\n        self,\n        api_key: Optional[str] = None,\n        api_secret: Optional[str] = None,\n        requests_params: Optional[Dict[str, str]] = None,\n        tld: str = \"com\",\n        testnet: bool = False,\n    ):\n        super().__init__(api_key, api_secret, requests_params, tld, testnet)\n\n    def _start_depth_cache(\n        self,\n        dcm_class,\n        callback: Callable,\n        symbol: str,\n        refresh_interval=None,\n        bm=None,\n        limit=10,\n        conv_type=float,\n        **kwargs,\n    ) -> str:\n        while not self._client:\n            time.sleep(0.01)\n\n        dcm = dcm_class(\n            client=self._client,\n            symbol=symbol,\n            loop=self._loop,\n            refresh_interval=refresh_interval,\n            bm=bm,\n            limit=limit,\n            conv_type=conv_type,\n            **kwargs,\n        )\n        path = symbol.lower() + \"@depth\" + str(limit)\n        self._socket_running[path] = True\n        self._loop.call_soon(\n            asyncio.create_task, self.start_listener(dcm, path, callback)\n        )\n        return path\n\n    def start_depth_cache(\n        self,\n        callback: Callable,\n        symbol: str,\n        refresh_interval=None,\n        bm=None,\n        limit=10,\n        conv_type=float,\n        ws_interval=0,\n    ) -> str:\n        return self._start_depth_cache(\n            dcm_class=DepthCacheManager,\n            callback=callback,\n            symbol=symbol,\n            refresh_interval=refresh_interval,\n            bm=bm,\n            limit=limit,\n            conv_type=conv_type,\n            ws_interval=ws_interval,\n        )\n\n    def start_futures_depth_socket(\n        self,\n        callback: Callable,\n        symbol: str,\n        refresh_interval=None,\n        bm=None,\n        limit=10,\n        conv_type=float,\n    ) -> str:\n        return self._start_depth_cache(\n            dcm_class=FuturesDepthCacheManager,\n            callback=callback,\n            symbol=symbol,\n            refresh_interval=refresh_interval,\n            bm=bm,\n            limit=limit,\n            conv_type=conv_type,\n        )\n\n    def start_options_depth_socket(\n        self,\n        callback: Callable,\n        symbol: str,\n        refresh_interval=None,\n        bm=None,\n        limit=10,\n        conv_type=float,\n    ) -> str:\n        return self._start_depth_cache(\n            dcm_class=OptionsDepthCacheManager,\n            callback=callback,\n            symbol=symbol,\n            refresh_interval=refresh_interval,\n            bm=bm,\n            limit=limit,\n            conv_type=conv_type,\n        )\n"
  },
  {
    "path": "binance/ws/keepalive_websocket.py",
    "content": "import asyncio\nimport uuid\nfrom binance.async_client import AsyncClient\nfrom binance.ws.reconnecting_websocket import ReconnectingWebsocket\nfrom binance.ws.constants import KEEPALIVE_TIMEOUT\n\n\nclass KeepAliveWebsocket(ReconnectingWebsocket):\n    def __init__(\n        self,\n        client: AsyncClient,\n        url,\n        keepalive_type,\n        prefix=\"ws/\",\n        is_binary=False,\n        exit_coro=None,\n        user_timeout=None,\n        **kwargs,\n    ):\n        super().__init__(\n            path=None,\n            url=url,\n            prefix=prefix,\n            is_binary=is_binary,\n            exit_coro=exit_coro,\n            **kwargs,\n        )\n        self._keepalive_type = keepalive_type\n        self._client = client\n        self._user_timeout = user_timeout or KEEPALIVE_TIMEOUT\n        self._timer = None\n        self._subscription_id = None\n        self._listen_key = None  # Used for non spot stream types\n        self._uses_ws_api_subscription = False  # True when using ws_api\n        self._listen_token_expiration = (\n            None  # Expiration time for listenToken-based subscriptions\n        )\n\n    async def __aexit__(self, *args, **kwargs):\n        if self._timer:\n            self._timer.cancel()\n            self._timer = None\n        # Clean up subscription if it exists\n        if self._subscription_id is not None:\n            # Unregister the queue from ws_api before unsubscribing\n            if hasattr(self._client, \"ws_api\") and self._client.ws_api:\n                self._client.ws_api.unregister_subscription_queue(self._subscription_id)\n            await self._unsubscribe_from_user_data_stream()\n        if self._uses_ws_api_subscription:\n            # For ws_api subscriptions, we don't manage the connection\n            return\n        if not self._path:\n            return\n        await super().__aexit__(*args, **kwargs)\n\n    def _build_path(self):\n        self._path = self._listen_key\n        time_unit = getattr(self._client, \"TIME_UNIT\", None)\n        if time_unit:\n            self._path = f\"{self._listen_key}?timeUnit={time_unit}\"\n\n    async def _before_connect(self):\n        if self._keepalive_type == \"user\":\n            # Subscribe via ws_api and register our own queue for events\n            self._subscription_id = await self._subscribe_to_user_data_stream()\n            if self._subscription_id is None:\n                raise ValueError(\n                    \"Failed to subscribe to user data stream: no subscription ID returned\"\n                )\n            self._uses_ws_api_subscription = True\n            # Register our queue with ws_api so events get routed to us\n            self._client.ws_api.register_subscription_queue(\n                self._subscription_id, self._queue\n            )\n            self._path = f\"user_subscription:{self._subscription_id}\"\n            return\n        if self._keepalive_type == \"margin\":\n            # Subscribe to cross-margin via ws_api\n            self._subscription_id = await self._subscribe_to_margin_data_stream()\n            if self._subscription_id is None:\n                raise ValueError(\n                    \"Failed to subscribe to margin data stream: no subscription ID returned\"\n                )\n            self._uses_ws_api_subscription = True\n            # Register our queue with ws_api so events get routed to us\n            self._client.ws_api.register_subscription_queue(\n                self._subscription_id, self._queue\n            )\n            self._path = f\"margin_subscription:{self._subscription_id}\"\n            return\n        # Check if this is isolated margin (when keepalive_type is a symbol string)\n        if self._keepalive_type not in [\n            \"user\",\n            \"margin\",\n            \"futures\",\n            \"coin_futures\",\n            \"portfolio_margin\",\n        ]:\n            # This is isolated margin with symbol as keepalive_type\n            self._subscription_id = (\n                await self._subscribe_to_isolated_margin_data_stream(\n                    self._keepalive_type\n                )\n            )\n            if self._subscription_id is None:\n                raise ValueError(\n                    f\"Failed to subscribe to isolated margin data stream for {self._keepalive_type}: no subscription ID returned\"\n                )\n            self._uses_ws_api_subscription = True\n            # Register our queue with ws_api so events get routed to us\n            self._client.ws_api.register_subscription_queue(\n                self._subscription_id, self._queue\n            )\n            self._path = f\"isolated_margin_subscription:{self._subscription_id}\"\n            return\n        if not self._listen_key:\n            self._listen_key = await self._get_listen_key()\n            self._build_path()\n\n    async def connect(self):\n        \"\"\"Override connect to handle ws_api subscriptions differently.\"\"\"\n        # Check if this keepalive type uses ws_api subscription\n        if self._keepalive_type in [\"user\", \"margin\"] or self._keepalive_type not in [\n            \"futures\",\n            \"coin_futures\",\n            \"portfolio_margin\",\n        ]:\n            # For sockets using ws_api subscription:\n            # - Subscribe via ws_api (done in _before_connect)\n            # - Don't create our own websocket connection\n            # - Don't start a read loop (ws_api handles reading)\n            await self._before_connect()\n            # Check if ws_api subscription was actually used\n            if self._uses_ws_api_subscription:\n                await self._after_connect()\n                return\n        # For other keepalive types, use normal connection logic\n        await super().connect()\n\n    async def recv(self):\n        \"\"\"Override recv to work without a read loop for ws_api subscriptions.\"\"\"\n        if self._uses_ws_api_subscription:\n            # For ws_api subscriptions, just read from queue\n            res = None\n            while not res:\n                try:\n                    res = await asyncio.wait_for(\n                        self._queue.get(), timeout=self.TIMEOUT\n                    )\n                except asyncio.TimeoutError:\n                    self._log.debug(f\"no message in {self.TIMEOUT} seconds\")\n            return res\n        return await super().recv()\n\n    async def _after_connect(self):\n        if self._timer is None:\n            self._start_socket_timer()\n\n    def _start_socket_timer(self):\n        self._timer = self._loop.call_later(\n            self._user_timeout, lambda: asyncio.create_task(self._keepalive_socket())\n        )\n\n    async def _subscribe_to_user_data_stream(self):\n        \"\"\"Subscribe to user data stream using WebSocket API\"\"\"\n        params = {\n            \"id\": str(uuid.uuid4()),\n        }\n        response = await self._client._ws_api_request(\n            \"userDataStream.subscribe.signature\", signed=True, params=params\n        )\n        return response.get(\"subscriptionId\")\n\n    async def _subscribe_to_margin_data_stream(self):\n        \"\"\"Subscribe to cross-margin data stream using WebSocket API with listenToken\"\"\"\n        # Create listenToken for cross-margin\n        token_response = await self._client.margin_create_listen_token(\n            is_isolated=False\n        )\n        listen_token = token_response[\"token\"]\n        self._listen_token_expiration = token_response.get(\"expirationTime\")\n\n        # Subscribe using listenToken\n        params = {\n            \"id\": str(uuid.uuid4()),\n            \"listenToken\": listen_token,\n        }\n        response = await self._client._ws_api_request(\n            \"userDataStream.subscribe.listenToken\", signed=False, params=params\n        )\n        return response.get(\"subscriptionId\")\n\n    async def _subscribe_to_isolated_margin_data_stream(self, symbol: str):\n        \"\"\"Subscribe to isolated margin data stream using WebSocket API with listenToken\"\"\"\n        # Create listenToken for isolated margin\n        token_response = await self._client.margin_create_listen_token(\n            symbol=symbol, is_isolated=True\n        )\n        listen_token = token_response[\"token\"]\n        self._listen_token_expiration = token_response.get(\"expirationTime\")\n\n        # Subscribe using listenToken\n        params = {\n            \"id\": str(uuid.uuid4()),\n            \"listenToken\": listen_token,\n        }\n        response = await self._client._ws_api_request(\n            \"userDataStream.subscribe.listenToken\", signed=False, params=params\n        )\n        return response.get(\"subscriptionId\")\n\n    async def _unsubscribe_from_user_data_stream(self):\n        \"\"\"Unsubscribe from user data stream using WebSocket API\"\"\"\n        if self._subscription_id is not None:\n            params = {\n                \"id\": str(uuid.uuid4()),\n                \"subscriptionId\": self._subscription_id,\n            }\n            await self._client._ws_api_request(\n                \"userDataStream.unsubscribe\", signed=False, params=params\n            )\n            self._subscription_id = None\n\n    async def _get_listen_key(self):\n        if self._keepalive_type == \"user\":\n            listen_key = await self._client.stream_get_listen_key()\n        elif self._keepalive_type == \"margin\":  # cross-margin\n            listen_key = await self._client.margin_stream_get_listen_key()\n        elif self._keepalive_type == \"futures\":\n            listen_key = await self._client.futures_stream_get_listen_key()\n        elif self._keepalive_type == \"coin_futures\":\n            listen_key = await self._client.futures_coin_stream_get_listen_key()\n        elif self._keepalive_type == \"portfolio_margin\":\n            listen_key = await self._client.papi_stream_get_listen_key()\n        else:  # isolated margin\n            # Passing symbol for isolated margin\n            listen_key = await self._client.isolated_margin_stream_get_listen_key(\n                self._keepalive_type\n            )\n        return listen_key\n\n    async def _keepalive_socket(self):\n        try:\n            # Skip keepalive for ws_api subscriptions (user, margin, isolated margin)\n            if self._uses_ws_api_subscription:\n                return\n            listen_key = await self._get_listen_key()\n            if listen_key != self._listen_key:\n                self._log.debug(\"listen key changed: reconnect\")\n                self._listen_key = listen_key\n                self._build_path()\n                self._reconnect()\n            else:\n                self._log.debug(\"listen key same: keepalive\")\n                if self._keepalive_type == \"margin\":  # cross-margin\n                    await self._client.margin_stream_keepalive(self._listen_key)\n                elif self._keepalive_type == \"futures\":\n                    await self._client.futures_stream_keepalive(self._listen_key)\n                elif self._keepalive_type == \"coin_futures\":\n                    await self._client.futures_coin_stream_keepalive(self._listen_key)\n                elif self._keepalive_type == \"portfolio_margin\":\n                    await self._client.papi_stream_keepalive(self._listen_key)\n                else:  # isolated margin\n                    # Passing symbol for isolated margin\n                    await self._client.isolated_margin_stream_keepalive(\n                        self._keepalive_type, self._listen_key\n                    )\n        except Exception as e:\n            self._log.error(f\"error in keepalive_socket: {e}\")\n        finally:\n            if self._timer is not None:\n                self._start_socket_timer()\n            else:\n                self._log.info(\"skip timer restart - web socket is exiting\")\n"
  },
  {
    "path": "binance/ws/reconnecting_websocket.py",
    "content": "import asyncio\nimport gzip\nimport json\nimport logging\nfrom socket import gaierror\nfrom typing import Optional\nfrom asyncio import sleep\nfrom random import random\n\n# load orjson if available, otherwise default to json\norjson = None\ntry:\n    import orjson as orjson\nexcept ImportError:\n    pass\n\ntry:\n    from websockets.exceptions import ConnectionClosedError, ConnectionClosedOK # type: ignore\nexcept ImportError:\n    from websockets import ConnectionClosedError, ConnectionClosedOK  # type: ignore\n\n\nProxy = None\nproxy_connect = None\ntry:\n    from websockets_proxy import Proxy as w_Proxy, proxy_connect as w_proxy_connect\n\n    Proxy = w_Proxy\n    proxy_connect = w_proxy_connect\nexcept ImportError:\n    pass\n\nimport websockets as ws\n\nfrom binance.exceptions import (\n    BinanceWebsocketClosed,\n    BinanceWebsocketUnableToConnect,\n    BinanceWebsocketQueueOverflow,\n    ReadLoopClosed,\n)\nfrom binance.helpers import get_loop\nfrom binance.ws.constants import WSListenerState\n\n\nclass ReconnectingWebsocket:\n    MAX_RECONNECTS = 5\n    MAX_RECONNECT_SECONDS = 60\n    MIN_RECONNECT_WAIT = 0.1\n    TIMEOUT = 10\n    NO_MESSAGE_RECONNECT_TIMEOUT = 60\n\n    def __init__(\n        self,\n        url: str,\n        path: Optional[str] = None,\n        prefix: str = \"ws/\",\n        is_binary: bool = False,\n        exit_coro=None,\n        https_proxy: Optional[str] = None,\n        max_queue_size: int = 100,\n        **kwargs,\n    ):\n        self._loop = get_loop()\n        self._log = logging.getLogger(__name__)\n        self._path = path\n        self._url = url\n        self._exit_coro = exit_coro\n        self._prefix = prefix\n        self._reconnects = 0\n        self._is_binary = is_binary\n        self._conn = None\n        self._socket = None\n        self.ws: Optional[ws.WebSocketClientProtocol] = None  # type: ignore\n        self.ws_state = WSListenerState.INITIALISING\n        self._queue = asyncio.Queue()\n        self._handle_read_loop = None\n        self._https_proxy = https_proxy\n        self._ws_kwargs = kwargs\n        self.max_queue_size = max_queue_size\n\n    def json_dumps(self, msg) -> str:\n        if orjson:\n            return orjson.dumps(msg).decode(\"utf-8\")\n        return json.dumps(msg)\n\n    def json_loads(self, msg):\n        if orjson:\n            return orjson.loads(msg)\n        return json.loads(msg)\n\n    async def __aenter__(self):\n        await self.connect()\n        return self\n\n    async def close(self):\n        await self.__aexit__(None, None, None)\n\n    async def __aexit__(self, exc_type, exc_val, exc_tb):\n        self._log.debug(f\"Closing Websocket {self._url}{self._prefix}{self._path}\")\n        if self._handle_read_loop:\n            await self._kill_read_loop()\n        if self._exit_coro:\n            await self._exit_coro(self._path)\n        if self.ws:\n            await self.ws.close()\n        if self._conn and hasattr(self._conn, \"protocol\"):\n            await self._conn.__aexit__(exc_type, exc_val, exc_tb)\n        self.ws = None\n\n    async def connect(self):\n        self._log.debug(\"Establishing new WebSocket connection\")\n        self.ws_state = WSListenerState.RECONNECTING\n        await self._before_connect()\n\n        ws_url = (\n            f\"{self._url}{getattr(self, '_prefix', '')}{getattr(self, '_path', '')}\"\n        )\n\n        # handle https_proxy\n        if self._https_proxy:\n            if not Proxy or not proxy_connect:\n                raise ImportError(\n                    \"websockets_proxy is not installed, please install it to use a websockets proxy (pip install websockets_proxy)\"\n                )\n            proxy = Proxy.from_url(self._https_proxy)  # type: ignore\n            self._conn = proxy_connect(\n                ws_url, close_timeout=0.1, proxy=proxy, **self._ws_kwargs\n            )  # type: ignore\n        else:\n            self._conn = ws.connect(ws_url, close_timeout=0.1, **self._ws_kwargs)  # type: ignore\n\n        try:\n            self.ws = await self._conn.__aenter__()\n        except Exception as e:  # noqa\n            self._log.error(f\"Failed to connect to websocket: {e}\")\n            self.ws_state = WSListenerState.RECONNECTING\n            raise e\n        self.ws_state = WSListenerState.STREAMING\n        self._reconnects = 0\n        await self._after_connect()\n        if not self._handle_read_loop:\n            self._handle_read_loop = self._loop.call_soon_threadsafe(\n                asyncio.create_task, self._read_loop()\n            )\n\n    async def _kill_read_loop(self):\n        self.ws_state = WSListenerState.EXITING\n        while self._handle_read_loop:\n            await sleep(0.1)\n        self._log.debug(\"Finished killing read_loop\")\n\n    async def _before_connect(self):\n        pass\n\n    async def _after_connect(self):\n        pass\n\n    def _handle_message(self, evt):\n        if self._is_binary:\n            try:\n                evt = gzip.decompress(evt)\n            except (ValueError, OSError) as e:\n                self._log.error(f\"Failed to decompress message: {(e)}\")\n                raise\n            except Exception as e:\n                self._log.error(f\"Unexpected decompression error: {(e)}\")\n                raise\n        try:\n            return self.json_loads(evt)\n        except ValueError as e:\n            self._log.error(f\"JSON Value Error parsing message: Error: {(e)}\")\n            raise\n        except TypeError as e:\n            self._log.error(f\"JSON Type Error parsing message. Error: {(e)}\")\n            raise\n        except Exception as e:\n            self._log.error(f\"Unexpected error parsing message. Error: {(e)}\")\n            raise\n\n    async def _read_loop(self):\n        try:\n            while True:\n                try:\n                    while self.ws_state == WSListenerState.RECONNECTING:\n                        await self._run_reconnect()\n\n                    if self.ws_state == WSListenerState.EXITING:\n                        self._log.debug(\n                            f\"_read_loop {self._path} break for {self.ws_state}\"\n                        )\n                        break\n                    elif self.ws.state == ws.protocol.State.CLOSING:  # type: ignore\n                        await asyncio.sleep(0.1)\n                        continue\n                    elif self.ws.state == ws.protocol.State.CLOSED:  # type: ignore\n                        self._reconnect()\n                        raise BinanceWebsocketClosed(\n                            \"Connection closed. Reconnecting...\"\n                        )\n                    elif self.ws_state == WSListenerState.STREAMING:\n                        assert self.ws\n                        res = await asyncio.wait_for(\n                            self.ws.recv(), timeout=self.TIMEOUT\n                        )\n                        res = self._handle_message(res)\n                        self._log.debug(f\"Received message: {res}\")\n                        if res:\n                            if self._queue.qsize() < self.max_queue_size:\n                                await self._queue.put(res)\n                            else:\n                                raise BinanceWebsocketQueueOverflow(\n                                    f\"Message queue size {self._queue.qsize()} exceeded maximum {self.max_queue_size}\"\n                                )\n                except asyncio.TimeoutError:\n                    self._log.debug(f\"no message in {self.TIMEOUT} seconds\")\n                    # _no_message_received_reconnect\n                except asyncio.CancelledError as e:\n                    self._log.debug(f\"_read_loop cancelled error {e}\")\n                    await self._queue.put({\n                        \"e\": \"error\",\n                        \"type\": f\"{e.__class__.__name__}\",\n                        \"m\": f\"{e}\",\n                    })\n                    break\n                except (\n                    asyncio.IncompleteReadError,\n                    gaierror,\n                    ConnectionClosedError,\n                    ConnectionClosedOK,\n                    BinanceWebsocketClosed,\n                ) as e:\n                    # reports errors and continue loop\n                    self._log.error(f\"{e.__class__.__name__} ({e})\")\n                    await self._queue.put({\n                        \"e\": \"error\",\n                        \"type\": f\"{e.__class__.__name__}\",\n                        \"m\": f\"{e}\",\n                    })\n                except (\n                    BinanceWebsocketUnableToConnect,\n                    BinanceWebsocketQueueOverflow,\n                    Exception,\n                ) as e:\n                    # reports errors and break the loop\n                    self._log.error(f\"Unknown exception: {e.__class__.__name__} ({e})\")\n                    await self._queue.put({\n                        \"e\": \"error\",\n                        \"type\": e.__class__.__name__,\n                        \"m\": f\"{e}\",\n                    })\n                    break\n        except Exception as e:\n            self._log.error(f\"Unknown exception: {e.__class__.__name__} ({e})\")\n        finally:\n            self._handle_read_loop = None  # Signal the coro is stopped\n            self._reconnects = 0\n\n    async def _run_reconnect(self):\n        await self.before_reconnect()\n        if self._reconnects < self.MAX_RECONNECTS:\n            reconnect_wait = self._get_reconnect_wait(self._reconnects)\n            self._log.debug(\n                f\"websocket reconnecting. {self.MAX_RECONNECTS - self._reconnects} reconnects left - \"\n                f\"waiting {reconnect_wait}\"\n            )\n            await asyncio.sleep(reconnect_wait)\n            try:\n                await self.connect()\n            except Exception as e:\n                pass\n        else:\n            self._log.error(f\"Max reconnections {self.MAX_RECONNECTS} reached:\")\n            # Signal the error\n            raise BinanceWebsocketUnableToConnect\n\n    async def recv(self):\n        res = None\n        while not res:\n            if not self._handle_read_loop:\n                raise ReadLoopClosed(\n                    \"Read loop has been closed, please reset the websocket connection and listen to the message error.\"\n                )\n            try:\n                res = await asyncio.wait_for(self._queue.get(), timeout=self.TIMEOUT)\n            except asyncio.TimeoutError:\n                self._log.debug(f\"no message in {self.TIMEOUT} seconds\")\n        return res\n\n    async def _wait_for_reconnect(self):\n        while (\n            self.ws_state != WSListenerState.STREAMING\n            and self.ws_state != WSListenerState.EXITING\n        ):\n            await sleep(0.1)\n\n    def _get_reconnect_wait(self, attempts: int) -> int:\n        expo = 2**attempts\n        return round(random() * min(self.MAX_RECONNECT_SECONDS, expo - 1) + 1)\n\n    async def before_reconnect(self):\n        if self.ws:\n            self.ws = None\n\n        if self._conn and hasattr(self._conn, \"protocol\"):\n            await self._conn.__aexit__(None, None, None)\n\n        self._reconnects += 1\n\n    def _reconnect(self):\n        self.ws_state = WSListenerState.RECONNECTING\n"
  },
  {
    "path": "binance/ws/streams.py",
    "content": "import asyncio\nimport time\nfrom enum import Enum\nfrom typing import Optional, List, Dict, Callable, Any\nimport logging\n\nfrom binance.ws.constants import KEEPALIVE_TIMEOUT\nfrom binance.ws.keepalive_websocket import KeepAliveWebsocket\nfrom binance.ws.reconnecting_websocket import ReconnectingWebsocket\nfrom binance.ws.threaded_stream import ThreadedApiManager\n\n\nfrom binance.async_client import AsyncClient\nfrom binance.enums import FuturesType\nfrom binance.enums import ContractType\nfrom binance.helpers import get_loop\n\n\nclass BinanceSocketType(str, Enum):\n    SPOT = \"Spot\"\n    USD_M_FUTURES = \"USD_M_Futures\"\n    COIN_M_FUTURES = \"Coin_M_Futures\"\n    OPTIONS = \"Vanilla_Options\"\n    ACCOUNT = \"Account\"\n\n\nclass BinanceSocketManager:\n    STREAM_URL = \"wss://stream.binance.{}:9443/\"\n    STREAM_TESTNET_URL = \"wss://stream.testnet.binance.vision/\"\n    STREAM_DEMO_URL = \"wss://demo-stream.binance.com/\"\n    FSTREAM_URL = \"wss://fstream.binance.{}/\"\n    FSTREAM_TESTNET_URL = \"wss://stream.binancefuture.com/\"\n    FSTREAM_DEMO_URL = \"wss://fstream.binancefuture.com/\"\n    DSTREAM_URL = \"wss://dstream.binance.{}/\"\n    DSTREAM_TESTNET_URL = \"wss://dstream.binancefuture.com/\"\n    DSTREAM_DEMO_URL = \"wss://dstream.binancefuture.com/\"\n    OPTIONS_URL = \"wss://nbstream.binance.{}/eoptions/\"\n\n    WEBSOCKET_DEPTH_5 = \"5\"\n    WEBSOCKET_DEPTH_10 = \"10\"\n    WEBSOCKET_DEPTH_20 = \"20\"\n\n    def __init__(\n        self,\n        client: AsyncClient,\n        user_timeout=KEEPALIVE_TIMEOUT,\n        max_queue_size: int = 100,\n        verbose: bool = False,\n    ):\n        \"\"\"Initialise the BinanceSocketManager\n\n        :param client: Binance API client\n        :type client: binance.AsyncClient\n        :param user_timeout: Timeout for user socket in seconds\n        :param max_queue_size: Max size of the websocket queue, defaults to 100\n        :type max_queue_size: int\n        :param verbose: Enable verbose logging for WebSocket connections\n        :type verbose: bool\n        \"\"\"\n        self.STREAM_URL = self.STREAM_URL.format(client.tld)\n        self.FSTREAM_URL = self.FSTREAM_URL.format(client.tld)\n        self.DSTREAM_URL = self.DSTREAM_URL.format(client.tld)\n        self.OPTIONS_URL = self.OPTIONS_URL.format(client.tld)\n\n        self._conns = {}\n        self._loop = get_loop()\n        self._client = client\n        self._user_timeout = user_timeout\n        self.testnet = self._client.testnet\n        self.demo = self._client.demo\n        self._max_queue_size = max_queue_size\n        self.verbose = verbose\n        self.ws_kwargs = {}\n\n        if verbose:\n            logging.getLogger('binance.ws').setLevel(logging.DEBUG)\n\n    def _get_stream_url(self, stream_url: Optional[str] = None):\n        if stream_url:\n            return stream_url\n        stream_url = self.STREAM_URL\n        if self.testnet:\n            stream_url = self.STREAM_TESTNET_URL\n        elif self.demo:\n            stream_url = self.STREAM_DEMO_URL\n        return stream_url\n\n    def _get_socket(\n        self,\n        path: str,\n        stream_url: Optional[str] = None,\n        prefix: str = \"ws/\",\n        is_binary: bool = False,\n        socket_type: BinanceSocketType = BinanceSocketType.SPOT,\n    ) -> ReconnectingWebsocket:\n        conn_id = f\"{socket_type}_{path}\"\n        time_unit = getattr(self._client, \"TIME_UNIT\", None)\n        if time_unit:\n            path = f\"{path}?timeUnit={time_unit}\"\n        if conn_id not in self._conns:\n            self._conns[conn_id] = ReconnectingWebsocket(\n                path=path,\n                url=self._get_stream_url(stream_url),\n                prefix=prefix,\n                exit_coro=lambda p: self._exit_socket(f\"{socket_type}_{p}\"),\n                is_binary=is_binary,\n                https_proxy=self._client.https_proxy,\n                max_queue_size=self._max_queue_size,\n                **self.ws_kwargs,\n            )\n\n        return self._conns[conn_id]\n\n    def _get_account_socket(\n        self,\n        path: str,\n        stream_url: Optional[str] = None,\n        prefix: str = \"ws/\",\n        is_binary: bool = False,\n    ) -> KeepAliveWebsocket:\n        conn_id = f\"{BinanceSocketType.ACCOUNT}_{path}\"\n        if conn_id not in self._conns:\n            self._conns[conn_id] = KeepAliveWebsocket(\n                client=self._client,\n                url=self._get_stream_url(stream_url),\n                keepalive_type=path,\n                prefix=prefix,\n                exit_coro=lambda p: self._exit_socket(conn_id),\n                is_binary=is_binary,\n                user_timeout=self._user_timeout,\n                https_proxy=self._client.https_proxy,\n                max_queue_size=self._max_queue_size,\n                **self.ws_kwargs,\n            )\n\n        return self._conns[conn_id]\n\n    def _get_futures_socket(\n        self, path: str, futures_type: FuturesType, prefix: str = \"stream?streams=\"\n    ):\n        socket_type: BinanceSocketType = BinanceSocketType.USD_M_FUTURES\n        if futures_type == FuturesType.USD_M:\n            stream_url = self.FSTREAM_URL\n            if self.testnet:\n                stream_url = self.FSTREAM_TESTNET_URL\n            elif self.demo:\n                stream_url = self.FSTREAM_DEMO_URL\n        else:\n            stream_url = self.DSTREAM_URL\n            if self.testnet:\n                stream_url = self.DSTREAM_TESTNET_URL\n            elif self.demo:\n                stream_url = self.DSTREAM_DEMO_URL\n        return self._get_socket(path, stream_url, prefix, socket_type=socket_type)\n\n    def _get_options_socket(self, path: str, prefix: str = \"ws/\"):\n        stream_url = self.OPTIONS_URL\n        return self._get_socket(\n            path,\n            stream_url,\n            prefix,\n            is_binary=False,\n            socket_type=BinanceSocketType.OPTIONS,\n        )\n\n    async def _exit_socket(self, path: str):\n        await self._stop_socket(path)\n\n    def depth_socket(\n        self, symbol: str, depth: Optional[str] = None, interval: Optional[int] = None\n    ):\n        \"\"\"Start a websocket for symbol market depth returning either a diff or a partial book\n\n        https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#partial-book-depth-streams\n\n        :param symbol: required\n        :type symbol: str\n        :param depth: optional Number of depth entries to return, default None. If passed returns a partial book instead of a diff\n        :type depth: str\n        :param interval: optional interval for updates, default None. If not set, updates happen every second. Must be 0, None (1s) or 100 (100ms)\n        :type interval: int\n\n        :returns: connection key string if successful, False otherwise\n\n        Partial Message Format\n\n        .. code-block:: python\n\n            {\n                \"lastUpdateId\": 160,  # Last update ID\n                \"bids\": [             # Bids to be updated\n                    [\n                        \"0.0024\",     # price level to be updated\n                        \"10\",         # quantity\n                        []            # ignore\n                    ]\n                ],\n                \"asks\": [             # Asks to be updated\n                    [\n                        \"0.0026\",     # price level to be updated\n                        \"100\",        # quantity\n                        []            # ignore\n                    ]\n                ]\n            }\n\n\n        Diff Message Format\n\n        .. code-block:: python\n\n            {\n                \"e\": \"depthUpdate\", # Event type\n                \"E\": 123456789,     # Event time\n                \"s\": \"BNBBTC\",      # Symbol\n                \"U\": 157,           # First update ID in event\n                \"u\": 160,           # Final update ID in event\n                \"b\": [              # Bids to be updated\n                    [\n                        \"0.0024\",   # price level to be updated\n                        \"10\",       # quantity\n                        []          # ignore\n                    ]\n                ],\n                \"a\": [              # Asks to be updated\n                    [\n                        \"0.0026\",   # price level to be updated\n                        \"100\",      # quantity\n                        []          # ignore\n                    ]\n                ]\n            }\n\n        \"\"\"\n        socket_name = symbol.lower() + \"@depth\"\n        if depth and depth != \"1\":\n            socket_name = f\"{socket_name}{depth}\"\n        if interval:\n            if interval in [0, 100]:\n                socket_name = f\"{socket_name}@{interval}ms\"\n            else:\n                raise ValueError(\n                    \"Websocket interval value not allowed. Allowed values are [0, 100]\"\n                )\n        return self._get_socket(socket_name)\n\n    def kline_socket(self, symbol: str, interval=AsyncClient.KLINE_INTERVAL_1MINUTE):\n        \"\"\"Start a websocket for symbol kline data\n\n        https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#klinecandlestick-streams\n\n        :param symbol: required\n        :type symbol: str\n        :param interval: Kline interval, default KLINE_INTERVAL_1MINUTE\n        :type interval: str\n\n        :returns: connection key string if successful, False otherwise\n\n        Message Format\n\n        .. code-block:: python\n\n            {\n                \"e\": \"kline\",\t\t\t\t\t# event type\n                \"E\": 1499404907056,\t\t\t\t# event time\n                \"s\": \"ETHBTC\",\t\t\t\t\t# symbol\n                \"k\": {\n                    \"t\": 1499404860000, \t\t# start time of this bar\n                    \"T\": 1499404919999, \t\t# end time of this bar\n                    \"s\": \"ETHBTC\",\t\t\t\t# symbol\n                    \"i\": \"1m\",\t\t\t\t\t# interval\n                    \"f\": 77462,\t\t\t\t\t# first trade id\n                    \"L\": 77465,\t\t\t\t\t# last trade id\n                    \"o\": \"0.10278577\",\t\t\t# open\n                    \"c\": \"0.10278645\",\t\t\t# close\n                    \"h\": \"0.10278712\",\t\t\t# high\n                    \"l\": \"0.10278518\",\t\t\t# low\n                    \"v\": \"17.47929838\",\t\t\t# volume\n                    \"n\": 4,\t\t\t\t\t\t# number of trades\n                    \"x\": false,\t\t\t\t\t# whether this bar is final\n                    \"q\": \"1.79662878\",\t\t\t# quote volume\n                    \"V\": \"2.34879839\",\t\t\t# volume of active buy\n                    \"Q\": \"0.24142166\",\t\t\t# quote volume of active buy\n                    \"B\": \"13279784.01349473\"\t# can be ignored\n                    }\n            }\n        \"\"\"\n        path = f\"{symbol.lower()}@kline_{interval}\"\n        return self._get_socket(path)\n\n    def kline_futures_socket(\n        self,\n        symbol: str,\n        interval=AsyncClient.KLINE_INTERVAL_1MINUTE,\n        futures_type: FuturesType = FuturesType.USD_M,\n        contract_type: ContractType = ContractType.PERPETUAL,\n    ):\n        \"\"\"Start a websocket for symbol kline data for the perpeual futures stream\n\n        https://binance-docs.github.io/apidocs/futures/en/#continuous-contract-kline-candlestick-streams\n\n        :param symbol: required\n        :type symbol: str\n        :param interval: Kline interval, default KLINE_INTERVAL_1MINUTE\n        :type interval: str\n        :param futures_type: use USD-M or COIN-M futures default USD-M\n        :param contract_type: use PERPETUAL or CURRENT_QUARTER or NEXT_QUARTER default PERPETUAL\n\n        :returns: connection key string if successful, False otherwise\n\n        Message Format\n\n        .. code-block:: python\n\n                {\n                \"e\":\"continuous_kline\",   // Event type\n                \"E\":1607443058651,        // Event time\n                \"ps\":\"BTCUSDT\",           // Pair\n                \"ct\":\"PERPETUAL\"          // Contract type\n                \"k\":{\n                    \"t\":1607443020000,      // Kline start time\n                    \"T\":1607443079999,      // Kline close time\n                    \"i\":\"1m\",               // Interval\n                    \"f\":116467658886,       // First trade ID\n                    \"L\":116468012423,       // Last trade ID\n                    \"o\":\"18787.00\",         // Open price\n                    \"c\":\"18804.04\",         // Close price\n                    \"h\":\"18804.04\",         // High price\n                    \"l\":\"18786.54\",         // Low price\n                    \"v\":\"197.664\",          // volume\n                    \"n\": 543,               // Number of trades\n                    \"x\":false,              // Is this kline closed?\n                    \"q\":\"3715253.19494\",    // Quote asset volume\n                    \"V\":\"184.769\",          // Taker buy volume\n                    \"Q\":\"3472925.84746\",    //Taker buy quote asset volume\n                    \"B\":\"0\"                 // Ignore\n                }\n            }\n            <pair>_<contractType>@continuousKline_<interval>\n        \"\"\"\n\n        path = f\"{symbol.lower()}_{contract_type.value}@continuousKline_{interval}\"\n        return self._get_futures_socket(path, prefix=\"ws/\", futures_type=futures_type)\n\n    def miniticker_socket(self, update_time: int = 1000):\n        \"\"\"Start a miniticker websocket for all trades\n\n        This is not in the official Binance api docs, but this is what\n        feeds the right column on a ticker page on Binance.\n\n        :param update_time: time between callbacks in milliseconds, must be 1000 or greater\n        :type update_time: int\n\n        :returns: connection key string if successful, False otherwise\n\n        Message Format\n\n        .. code-block:: python\n\n            [\n                {\n                    'e': '24hrMiniTicker',  # Event type\n                    'E': 1515906156273,     # Event time\n                    's': 'QTUMETH',         # Symbol\n                    'c': '0.03836900',      # close\n                    'o': '0.03953500',      # open\n                    'h': '0.04400000',      # high\n                    'l': '0.03756000',      # low\n                    'v': '147435.80000000', # volume\n                    'q': '5903.84338533'    # quote volume\n                }\n            ]\n        \"\"\"\n\n        return self._get_socket(f\"!miniTicker@arr@{update_time}ms\")\n\n    def trade_socket(self, symbol: str):\n        \"\"\"Start a websocket for symbol trade data\n\n        https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#trade-streams\n\n        :param symbol: required\n        :type symbol: str\n\n        :returns: connection key string if successful, False otherwise\n\n        Message Format\n\n        .. code-block:: python\n\n            {\n                \"e\": \"trade\",     # Event type\n                \"E\": 123456789,   # Event time\n                \"s\": \"BNBBTC\",    # Symbol\n                \"t\": 12345,       # Trade ID\n                \"p\": \"0.001\",     # Price\n                \"q\": \"100\",       # Quantity\n                \"b\": 88,          # Buyer order Id\n                \"a\": 50,          # Seller order Id\n                \"T\": 123456785,   # Trade time\n                \"m\": true,        # Is the buyer the market maker?\n                \"M\": true         # Ignore.\n            }\n\n        \"\"\"\n\n        return self._get_socket(symbol.lower() + \"@trade\")\n\n    def aggtrade_socket(self, symbol: str):\n        \"\"\"Start a websocket for symbol trade data\n\n        https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#aggregate-trade-streams\n\n        :param symbol: required\n        :type symbol: str\n\n        :returns: connection key string if successful, False otherwise\n\n        Message Format\n\n        .. code-block:: python\n\n            {\n                \"e\": \"aggTrade\",\t\t# event type\n                \"E\": 1499405254326,\t\t# event time\n                \"s\": \"ETHBTC\",\t\t\t# symbol\n                \"a\": 70232,\t\t\t\t# aggregated tradeid\n                \"p\": \"0.10281118\",\t\t# price\n                \"q\": \"8.15632997\",\t\t# quantity\n                \"f\": 77489,\t\t\t\t# first breakdown trade id\n                \"l\": 77489,\t\t\t\t# last breakdown trade id\n                \"T\": 1499405254324,\t\t# trade time\n                \"m\": false,\t\t\t\t# whether buyer is a maker\n                \"M\": true\t\t\t\t# can be ignored\n            }\n\n        \"\"\"\n        return self._get_socket(symbol.lower() + \"@aggTrade\")\n\n    def aggtrade_futures_socket(\n        self, symbol: str, futures_type: FuturesType = FuturesType.USD_M\n    ):\n        \"\"\"Start a websocket for aggregate symbol trade data for the futures stream\n\n        :param symbol: required\n        :param futures_type: use USD-M or COIN-M futures default USD-M\n\n        :returns: connection key string if successful, False otherwise\n\n        Message Format\n\n        .. code-block:: python\n\n            {\n                \"e\": \"aggTrade\",  // Event type\n                \"E\": 123456789,   // Event time\n                \"s\": \"BTCUSDT\",    // Symbol\n                \"a\": 5933014,     // Aggregate trade ID\n                \"p\": \"0.001\",     // Price\n                \"q\": \"100\",       // Quantity\n                \"f\": 100,         // First trade ID\n                \"l\": 105,         // Last trade ID\n                \"T\": 123456785,   // Trade time\n                \"m\": true,        // Is the buyer the market maker?\n            }\n\n        \"\"\"\n        return self._get_futures_socket(\n            symbol.lower() + \"@aggTrade\", futures_type=futures_type\n        )\n\n    def symbol_miniticker_socket(self, symbol: str):\n        \"\"\"Start a websocket for a symbol's miniTicker data\n\n        https://binance-docs.github.io/apidocs/spot/en/#individual-symbol-mini-ticker-stream\n\n        :param symbol: required\n        :type symbol: str\n\n        :returns: connection key string if successful, False otherwise\n\n        Message Format\n\n        .. code-block:: python\n\n            {\n                \"e\": \"24hrMiniTicker\",  // Event type\n                \"E\": 123456789,         // Event time\n                \"s\": \"BNBBTC\",          // Symbol\n                \"c\": \"0.0025\",          // Close price\n                \"o\": \"0.0010\",          // Open price\n                \"h\": \"0.0025\",          // High price\n                \"l\": \"0.0010\",          // Low price\n                \"v\": \"10000\",           // Total traded base asset volume\n                \"q\": \"18\"               // Total traded quote asset volume\n            }\n\n        \"\"\"\n        return self._get_socket(symbol.lower() + \"@miniTicker\")\n\n    def symbol_ticker_socket(self, symbol: str):\n        \"\"\"Start a websocket for a symbol's ticker data\n\n        https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#individual-symbol-ticker-streams\n\n        :param symbol: required\n        :type symbol: str\n\n        :returns: connection key string if successful, False otherwise\n\n        Message Format\n\n        .. code-block:: python\n\n            {\n                \"e\": \"24hrTicker\",  # Event type\n                \"E\": 123456789,     # Event time\n                \"s\": \"BNBBTC\",      # Symbol\n                \"p\": \"0.0015\",      # Price change\n                \"P\": \"250.00\",      # Price change percent\n                \"w\": \"0.0018\",      # Weighted average price\n                \"x\": \"0.0009\",      # Previous day's close price\n                \"c\": \"0.0025\",      # Current day's close price\n                \"Q\": \"10\",          # Close trade's quantity\n                \"b\": \"0.0024\",      # Best bid price\n                \"B\": \"10\",          # Bid bid quantity\n                \"a\": \"0.0026\",      # Best ask price\n                \"A\": \"100\",         # Best ask quantity\n                \"o\": \"0.0010\",      # Open price\n                \"h\": \"0.0025\",      # High price\n                \"l\": \"0.0010\",      # Low price\n                \"v\": \"10000\",       # Total traded base asset volume\n                \"q\": \"18\",          # Total traded quote asset volume\n                \"O\": 0,             # Statistics open time\n                \"C\": 86400000,      # Statistics close time\n                \"F\": 0,             # First trade ID\n                \"L\": 18150,         # Last trade Id\n                \"n\": 18151          # Total number of trades\n            }\n\n        \"\"\"\n        return self._get_socket(symbol.lower() + \"@ticker\")\n\n    def ticker_socket(self):\n        \"\"\"Start a websocket for all ticker data\n\n        By default all markets are included in an array.\n\n        https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#all-market-tickers-stream\n\n        :param coro: callback function to handle messages\n        :type coro: function\n\n        :returns: connection key string if successful, False otherwise\n\n        Message Format\n\n        .. code-block:: python\n\n            [\n                {\n                    'F': 278610,\n                    'o': '0.07393000',\n                    's': 'BCCBTC',\n                    'C': 1509622420916,\n                    'b': '0.07800800',\n                    'l': '0.07160300',\n                    'h': '0.08199900',\n                    'L': 287722,\n                    'P': '6.694',\n                    'Q': '0.10000000',\n                    'q': '1202.67106335',\n                    'p': '0.00494900',\n                    'O': 1509536020916,\n                    'a': '0.07887800',\n                    'n': 9113,\n                    'B': '1.00000000',\n                    'c': '0.07887900',\n                    'x': '0.07399600',\n                    'w': '0.07639068',\n                    'A': '2.41900000',\n                    'v': '15743.68900000'\n                }\n            ]\n        \"\"\"\n        return self._get_socket(\"!ticker@arr\")\n\n    def futures_ticker_socket(self):\n        \"\"\"Start a websocket for all ticker data\n\n        By default all markets are included in an array.\n\n        https://binance-docs.github.io/apidocs/futures/en/#all-market-tickers-streams\n\n        :returns: connection key string if successful, False otherwise\n\n        Message Format\n\n        .. code-block:: python\n\n            [\n                {\n                    \"e\": \"24hrTicker\",  // Event type\n                    \"E\": 123456789,     // Event time\n                    \"s\": \"BTCUSDT\",     // Symbol\n                    \"p\": \"0.0015\",      // Price change\n                    \"P\": \"250.00\",      // Price change percent\n                    \"w\": \"0.0018\",      // Weighted average price\n                    \"c\": \"0.0025\",      // Last price\n                    \"Q\": \"10\",          // Last quantity\n                    \"o\": \"0.0010\",      // Open price\n                    \"h\": \"0.0025\",      // High price\n                    \"l\": \"0.0010\",      // Low price\n                    \"v\": \"10000\",       // Total traded base asset volume\n                    \"q\": \"18\",          // Total traded quote asset volume\n                    \"O\": 0,             // Statistics open time\n                    \"C\": 86400000,      // Statistics close time\n                    \"F\": 0,             // First trade ID\n                    \"L\": 18150,         // Last trade Id\n                    \"n\": 18151          // Total number of trades\n                }\n            ]\n        \"\"\"\n        return self._get_futures_socket(\"!ticker@arr\", FuturesType.USD_M)\n\n    def futures_coin_ticker_socket(self):\n        \"\"\"Start a websocket for all ticker data\n\n        By default all markets are included in an array.\n\n        https://binance-docs.github.io/apidocs/delivery/en/#all-market-tickers-streams\n\n        :returns: connection key string if successful, False otherwise\n\n        Message Format\n\n        .. code-block:: python\n\n            [\n                {\n                    \"e\": \"24hrTicker\",  // Event type\n                    \"E\": 123456789,     // Event time\n                    \"s\": \"BTCUSDT\",     // Symbol\n                    \"p\": \"0.0015\",      // Price change\n                    \"P\": \"250.00\",      // Price change percent\n                    \"w\": \"0.0018\",      // Weighted average price\n                    \"c\": \"0.0025\",      // Last price\n                    \"Q\": \"10\",          // Last quantity\n                    \"o\": \"0.0010\",      // Open price\n                    \"h\": \"0.0025\",      // High price\n                    \"l\": \"0.0010\",      // Low price\n                    \"v\": \"10000\",       // Total traded base asset volume\n                    \"q\": \"18\",          // Total traded quote asset volume\n                    \"O\": 0,             // Statistics open time\n                    \"C\": 86400000,      // Statistics close time\n                    \"F\": 0,             // First trade ID\n                    \"L\": 18150,         // Last trade Id\n                    \"n\": 18151          // Total number of trades\n                }\n            ]\n        \"\"\"\n        return self._get_futures_socket(\"!ticker@arr\", FuturesType.COIN_M)\n\n    def index_price_socket(self, symbol: str, fast: bool = True):\n        \"\"\"Start a websocket for a symbol's futures mark price\n        https://binance-docs.github.io/apidocs/delivery/en/#index-price-stream\n        :param symbol: required\n        :param fast: use faster or 1s default\n        :returns: connection key string if successful, False otherwise\n\n        Message Format\n        .. code-block:: python\n            {\n                \"e\": \"indexPriceUpdate\",  // Event type\n                \"E\": 1591261236000,       // Event time\n                \"i\": \"BTCUSD\",            // Pair\n                \"p\": \"9636.57860000\",     // Index Price\n              }\n        \"\"\"\n        stream_name = \"@indexPrice@1s\" if fast else \"@indexPrice\"\n        return self._get_futures_socket(\n            symbol.lower() + stream_name, futures_type=FuturesType.COIN_M\n        )\n\n    def symbol_mark_price_socket(\n        self,\n        symbol: str,\n        fast: bool = True,\n        futures_type: FuturesType = FuturesType.USD_M,\n    ):\n        \"\"\"Start a websocket for a symbol's futures mark price\n        https://binance-docs.github.io/apidocs/futures/en/#mark-price-stream\n        :param symbol: required\n        :param fast: use faster or 1s default\n        :param futures_type: use USD-M or COIN-M futures default USD-M\n        :returns: connection key string if successful, False otherwise\n        Message Format\n        .. code-block:: python\n            {\n                \"e\": \"markPriceUpdate\",  // Event type\n                \"E\": 1562305380000,      // Event time\n                \"s\": \"BTCUSDT\",          // Symbol\n                \"p\": \"11185.87786614\",   // Mark price\n                \"r\": \"0.00030000\",       // Funding rate\n                \"T\": 1562306400000       // Next funding time\n            }\n        \"\"\"\n        stream_name = \"@markPrice@1s\" if fast else \"@markPrice\"\n        return self._get_futures_socket(\n            symbol.lower() + stream_name, futures_type=futures_type\n        )\n\n    def all_mark_price_socket(\n        self, fast: bool = True, futures_type: FuturesType = FuturesType.USD_M\n    ):\n        \"\"\"Start a websocket for all futures mark price data\n        By default all symbols are included in an array.\n        https://binance-docs.github.io/apidocs/futures/en/#mark-price-stream-for-all-market\n        :param fast: use faster or 1s default\n        :param futures_type: use USD-M or COIN-M futures default USD-M\n        :returns: connection key string if successful, False otherwise\n        Message Format\n        .. code-block:: python\n\n            [\n                {\n                    \"e\": \"markPriceUpdate\",  // Event type\n                    \"E\": 1562305380000,      // Event time\n                    \"s\": \"BTCUSDT\",          // Symbol\n                    \"p\": \"11185.87786614\",   // Mark price\n                    \"r\": \"0.00030000\",       // Funding rate\n                    \"T\": 1562306400000       // Next funding time\n                }\n            ]\n        \"\"\"\n        stream_name = \"!markPrice@arr@1s\" if fast else \"!markPrice@arr\"\n        return self._get_futures_socket(stream_name, futures_type=futures_type)\n\n    def symbol_ticker_futures_socket(\n        self, symbol: str, futures_type: FuturesType = FuturesType.USD_M\n    ):\n        \"\"\"Start a websocket for a symbol's ticker data\n        By default all markets are included in an array.\n        https://binance-docs.github.io/apidocs/futures/en/#individual-symbol-book-ticker-streams\n        :param symbol: required\n        :param futures_type: use USD-M or COIN-M futures default USD-M\n        :returns: connection key string if successful, False otherwise\n        .. code-block:: python\n            [\n                {\n                  \"u\":400900217,     // order book updateId\n                  \"s\":\"BNBUSDT\",     // symbol\n                  \"b\":\"25.35190000\", // best bid price\n                  \"B\":\"31.21000000\", // best bid qty\n                  \"a\":\"25.36520000\", // best ask price\n                  \"A\":\"40.66000000\"  // best ask qty\n                }\n            ]\n        \"\"\"\n        return self._get_futures_socket(\n            symbol.lower() + \"@bookTicker\", futures_type=futures_type\n        )\n\n    def individual_symbol_ticker_futures_socket(\n        self, symbol: str, futures_type: FuturesType = FuturesType.USD_M\n    ):\n        \"\"\"Start a futures websocket for a single symbol's ticker data\n        https://binance-docs.github.io/apidocs/futures/en/#individual-symbol-ticker-streams\n        :param symbol: required\n        :type symbol: str\n        :param futures_type: use USD-M or COIN-M futures default USD-M\n        :returns: connection key string if successful, False otherwise\n        .. code-block:: python\n            {\n                \"e\": \"24hrTicker\",  // Event type\n                \"E\": 123456789,     // Event time\n                \"s\": \"BTCUSDT\",     // Symbol\n                \"p\": \"0.0015\",      // Price change\n            }\n        \"\"\"\n        return self._get_futures_socket(\n            symbol.lower() + \"@ticker\", futures_type=futures_type\n        )\n\n    def all_ticker_futures_socket(\n        self,\n        channel: str = \"!bookTicker\",\n        futures_type: FuturesType = FuturesType.USD_M,\n    ):\n        \"\"\"Start a websocket for all ticker data\n        By default all markets are included in an array.\n\n        https://binance-docs.github.io/apidocs/futures/en/#all-book-tickers-stream\n\n        https://binance-docs.github.io/apidocs/futures/en/#all-market-tickers-streams\n\n        :param channel: optional channel type, default '!bookTicker', but '!ticker@arr' is also available\n        :param: futures_type: use USD-M or COIN-M futures default USD-M\n        :returns: connection key string if successful, False otherwise\n        Message Format\n        .. code-block:: python\n            [\n                {\n                  \"u\":400900217,     // order book updateId\n                  \"s\":\"BNBUSDT\",     // symbol\n                  \"b\":\"25.35190000\", // best bid price\n                  \"B\":\"31.21000000\", // best bid qty\n                  \"a\":\"25.36520000\", // best ask price\n                  \"A\":\"40.66000000\"  // best ask qty\n                }\n            ]\n        \"\"\"\n\n        return self._get_futures_socket(channel, futures_type=futures_type)\n\n    def symbol_book_ticker_socket(self, symbol: str):\n        \"\"\"Start a websocket for the best bid or ask's price or quantity for a specified symbol.\n\n        https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#individual-symbol-book-ticker-streams\n\n        :param symbol: required\n        :type symbol: str\n\n        :returns: connection key string if successful, False otherwise\n\n        Message Format\n\n        .. code-block:: python\n\n            {\n                \"u\":400900217,     // order book updateId\n                \"s\":\"BNBUSDT\",     // symbol\n                \"b\":\"25.35190000\", // best bid price\n                \"B\":\"31.21000000\", // best bid qty\n                \"a\":\"25.36520000\", // best ask price\n                \"A\":\"40.66000000\"  // best ask qty\n            }\n\n        \"\"\"\n        return self._get_socket(symbol.lower() + \"@bookTicker\")\n\n    def book_ticker_socket(self):\n        \"\"\"Start a websocket for the best bid or ask's price or quantity for all symbols.\n\n        https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#all-book-tickers-stream\n\n        :returns: connection key string if successful, False otherwise\n\n        Message Format\n\n        .. code-block:: python\n\n            {\n                // Same as <symbol>@bookTicker payload\n            }\n\n        \"\"\"\n        return self._get_socket(\"!bookTicker\")\n\n    def multiplex_socket(self, streams: List[str]):\n        \"\"\"Start a multiplexed socket using a list of socket names.\n        User stream sockets can not be included.\n\n        Symbols in socket name must be lowercase i.e bnbbtc@aggTrade, neobtc@ticker\n\n        Combined stream events are wrapped as follows: {\"stream\":\"<streamName>\",\"data\":<rawPayload>}\n\n        https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md\n\n        :param streams: list of stream names in lower case\n        :type streams: list\n\n        :returns: connection key string if successful, False otherwise\n\n        Message Format - see Binance API docs for all types\n\n        \"\"\"\n        path = f\"streams={'/'.join(streams)}\"\n        return self._get_socket(path, prefix=\"stream?\")\n\n    def options_multiplex_socket(self, streams: List[str]):\n        \"\"\"Start a multiplexed socket using a list of socket names.\n\n        https://developers.binance.com/docs/derivatives/option/websocket-market-streams\n\n        \"\"\"\n        stream_name = \"/\".join([s for s in streams])\n        stream_path = f\"streams={stream_name}\"\n        return self._get_options_socket(stream_path, prefix=\"stream?\")\n\n    def futures_multiplex_socket(\n        self, streams: List[str], futures_type: FuturesType = FuturesType.USD_M\n    ):\n        \"\"\"Start a multiplexed socket using a list of socket names.\n        User stream sockets can not be included.\n\n        Symbols in socket name must be lowercase i.e bnbbtc@aggTrade, neobtc@ticker\n\n        Combined stream events are wrapped as follows: {\"stream\":\"<streamName>\",\"data\":<rawPayload>}\n\n        https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md\n\n        :param streams: list of stream names in lower case\n        :param futures_type: use USD-M or COIN-M futures default USD-M\n\n        :returns: connection key string if successful, False otherwise\n\n        Message Format - see Binance API docs for all types\n\n        \"\"\"\n        path = f\"streams={'/'.join(streams)}\"\n        return self._get_futures_socket(\n            path, prefix=\"stream?\", futures_type=futures_type\n        )\n\n    def user_socket(self):\n        \"\"\"Start a websocket for user data\n\n        https://github.com/binance-exchange/binance-official-api-docs/blob/master/user-data-stream.md\n        https://binance-docs.github.io/apidocs/spot/en/#listen-key-spot\n\n        :returns: connection key string if successful, False otherwise\n\n        Message Format - see Binance API docs for all types\n        \"\"\"\n        stream_url = self.STREAM_URL\n        if self.testnet:\n            stream_url = self.STREAM_TESTNET_URL\n        elif self.demo:\n            stream_url = self.STREAM_DEMO_URL\n        return self._get_account_socket(\"user\", stream_url=stream_url)\n\n    def futures_user_socket(self):\n        \"\"\"Start a websocket for futures user data\n\n        https://binance-docs.github.io/apidocs/futures/en/#user-data-streams\n\n        :returns: connection key string if successful, False otherwise\n\n        Message Format - see Binanace API docs for all types\n        \"\"\"\n\n        stream_url = self.FSTREAM_URL\n        if self.testnet:\n            stream_url = self.FSTREAM_TESTNET_URL\n        elif self.demo:\n            stream_url = self.FSTREAM_DEMO_URL\n        return self._get_account_socket(\"futures\", stream_url=stream_url)\n\n    def coin_futures_user_socket(self):\n        \"\"\"Start a websocket for coin futures user data\n\n        https://binance-docs.github.io/apidocs/delivery/en/#user-data-streams\n\n        :returns: connection key string if successful, False otherwise\n\n        Message Format - see Binanace API docs for all types\n        \"\"\"\n\n        return self._get_account_socket(\"coin_futures\", stream_url=self.DSTREAM_URL)\n\n    def margin_socket(self):\n        \"\"\"Start a websocket for cross-margin data\n\n        https://binance-docs.github.io/apidocs/spot/en/#listen-key-margin\n\n        :returns: connection key string if successful, False otherwise\n\n        Message Format - see Binance API docs for all types\n        \"\"\"\n        stream_url = self.STREAM_URL\n        if self.testnet:\n            stream_url = self.STREAM_TESTNET_URL\n        elif self.demo:\n            stream_url = self.STREAM_DEMO_URL\n        return self._get_account_socket(\"margin\", stream_url=stream_url)\n\n    def futures_socket(self):\n        \"\"\"Start a websocket for futures data\n\n            https://binance-docs.github.io/apidocs/futures/en/#websocket-market-streams\n\n        :returns: connection key string if successful, False otherwise\n\n        Message Format - see Binance API docs for all types\n        \"\"\"\n        stream_url = self.FSTREAM_URL\n        if self.testnet:\n            stream_url = self.FSTREAM_TESTNET_URL\n        elif self.demo:\n            stream_url = self.FSTREAM_DEMO_URL\n        return self._get_account_socket(\"futures\", stream_url=stream_url)\n\n    def coin_futures_socket(self):\n        \"\"\"Start a websocket for coin futures data\n\n            https://binance-docs.github.io/apidocs/delivery/en/#websocket-market-streams\n\n        :returns: connection key string if successful, False otherwise\n\n        Message Format - see Binance API docs for all types\n        \"\"\"\n        stream_url = self.DSTREAM_URL\n        if self.testnet:\n            stream_url = self.DSTREAM_TESTNET_URL\n        elif self.demo:\n            stream_url = self.DSTREAM_DEMO_URL\n        return self._get_account_socket(\"coin_futures\", stream_url=stream_url)\n\n    def portfolio_margin_socket(self):\n        \"\"\"Start a websocket for portfolio margin user data\n\n            https://developers.binance.com/docs/derivatives/portfolio-margin/user-data-streams\n\n        :returns: connection key string if successful, False otherwise\n\n        Message Format - see Binance API docs for all types\n        \"\"\"\n        stream_url = self.FSTREAM_URL\n        if self.testnet:\n            stream_url = self.FSTREAM_TESTNET_URL\n        elif self.demo:\n            stream_url = self.FSTREAM_DEMO_URL\n        stream_url += \"pm/\"\n        return self._get_account_socket(\"portfolio_margin\", stream_url=stream_url)\n\n    def isolated_margin_socket(self, symbol: str):\n        \"\"\"Start a websocket for isolated margin data\n\n        https://binance-docs.github.io/apidocs/spot/en/#listen-key-isolated-margin\n\n        :param symbol: required - symbol for the isolated margin account\n        :type symbol: str\n\n        :returns: connection key string if successful, False otherwise\n\n        Message Format - see Binance API docs for all types\n        \"\"\"\n        stream_url = self.STREAM_URL\n        if self.testnet:\n            stream_url = self.STREAM_TESTNET_URL\n        elif self.demo:\n            stream_url = self.STREAM_DEMO_URL\n        return self._get_account_socket(symbol, stream_url=stream_url)\n\n    def options_ticker_socket(self, symbol: str):\n        \"\"\"Subscribe to a 24-hour ticker info stream for options trading.\n\n        API Reference: https://developers.binance.com/docs/derivatives/option/websocket-market-streams/24-hour-TICKER\n\n        Stream provides real-time 24hr ticker information for all symbols. Only symbols whose ticker info\n        changed will be sent. Updates every 1000ms.\n\n        :param symbol: The option symbol to subscribe to (e.g. \"BTC-220930-18000-C\")\n        :type symbol: str\n        \"\"\"\n        return self._get_options_socket(symbol.upper() + \"@ticker\")\n\n    def options_ticker_by_expiration_socket(self, symbol: str, expiration_date: str):\n        \"\"\"Subscribe to a 24-hour ticker info stream by underlying asset and expiration date.\n\n        API Reference: https://developers.binance.com/docs/derivatives/option/websocket-market-streams/24-hour-TICKER-by-underlying-asset-and-expiration-data\n\n        Stream provides real-time 24hr ticker information grouped by underlying asset and expiration date.\n        Updates every 1000ms.\n\n        :param symbol: The underlying asset (e.g., \"ETH\")\n        :type symbol: str\n        :param expiration_date: The expiration date (e.g., \"220930\" for Sept 30, 2022)\n        :type expiration_date: str\n        \"\"\"\n        return self._get_options_socket(symbol.upper() + \"@ticker@\" + expiration_date)\n\n    def options_recent_trades_socket(self, symbol: str):\n        \"\"\"Subscribe to a real-time trade information stream.\n\n        API Reference: https://developers.binance.com/docs/derivatives/option/websocket-market-streams/Trade-Streams\n\n        Stream pushes raw trade information for a specific symbol or underlying asset.\n        Updates every 50ms.\n\n        :param symbol: The option symbol or underlying asset (e.g., \"BTC-200630-9000-P\" or \"BTC\")\n        :type symbol: str\n        \"\"\"\n        return self._get_options_socket(symbol.upper() + \"@trade\")\n\n    def options_kline_socket(\n        self, symbol: str, interval=AsyncClient.KLINE_INTERVAL_1MINUTE\n    ):\n        \"\"\"Subscribe to a Kline/Candlestick data stream.\n\n        API Reference: https://developers.binance.com/docs/derivatives/option/websocket-market-streams/Kline-Candlestick-Streams\n\n        Stream pushes updates to the current klines/candlestick every 1000ms (if existing).\n\n        Available intervals:\n        - Minutes: \"1m\", \"3m\", \"5m\", \"15m\", \"30m\"\n        - Hours: \"1h\", \"2h\", \"4h\", \"6h\", \"12h\"\n        - Days: \"1d\", \"3d\"\n        - Weeks: \"1w\"\n\n        :param symbol: The option symbol (e.g., \"BTC-200630-9000-P\")\n        :type symbol: str\n        :param interval: Kline interval, default KLINE_INTERVAL_1MINUTE\n        :type interval: str\n        \"\"\"\n        return self._get_options_socket(symbol.upper() + \"@kline_\" + interval)\n\n    def options_depth_socket(self, symbol: str, depth: str = \"10\"):\n        \"\"\"Subscribe to partial book depth stream for options trading.\n\n        API Reference: https://developers.binance.com/docs/derivatives/option/websocket-market-streams/Partial-Book-Depth-Streams\n\n        Stream provides top N bids and asks from the order book.\n        Default update speed is 500ms if not specified in the stream name.\n\n        :param symbol: The option symbol (e.g., \"BTC-200630-9000-P\")\n        :type symbol: str\n        :param depth: Number of price levels. Valid values: \"10\", \"20\", \"50\", \"100\"\n        :type depth: str\n        \"\"\"\n        return self._get_options_socket(symbol.upper() + \"@depth\" + str(depth))\n\n    def futures_depth_socket(self, symbol: str, depth: str = \"10\", futures_type=FuturesType.USD_M):\n        \"\"\"Subscribe to a futures depth data stream\n\n        https://binance-docs.github.io/apidocs/futures/en/#partial-book-depth-streams\n\n        :param symbol: required\n        :type symbol: str\n        :param depth: optional Number of depth entries to return, default 10.\n        :type depth: str\n        :param futures_type: use USD-M or COIN-M futures default USD-M\n        \"\"\"\n        return self._get_futures_socket(\n            symbol.lower() + \"@depth\" + str(depth), futures_type=futures_type\n        )\n\n    def futures_rpi_depth_socket(self, symbol: str, futures_type=FuturesType.USD_M):\n        \"\"\"Subscribe to a futures RPI (Retail Price Improvement) depth data stream\n\n        RPI orders are included and aggregated in the stream. Crossed price levels are hidden.\n        Updates every 500ms.\n\n        https://developers.binance.com/docs/derivatives/usds-margined-futures/market-data/websocket-market-streams/RPI-Order-Book\n\n        :param symbol: required\n        :type symbol: str\n        :param futures_type: use USD-M or COIN-M futures default USD-M\n        \"\"\"\n        return self._get_futures_socket(\n            symbol.lower() + \"@rpiDepth@500ms\", futures_type=futures_type\n        )\n\n    def options_new_symbol_socket(self):\n        \"\"\"Subscribe to a new symbol listing information stream.\n\n        Stream provides real-time notifications when new option symbols are listed.\n        Updates every 50ms.\n\n        Stream name: option_pair\n\n        API Reference: https://developers.binance.com/docs/derivatives/option/websocket-market-streams/New-Symbol-Info\n\n        Response fields include:\n        - Event type and timestamps\n        - Underlying index (e.g., 'BTCUSDT')\n        - Quotation asset (e.g., 'USDT')\n        - Trading pair name (e.g., 'BTC-221116-21000-C')\n        - Conversion ratio and minimum trade volume\n        - Option type (CALL/PUT)\n        - Strike price and expiration time\n        \"\"\"\n        return self._get_options_socket(\"option_pair\")\n\n    def options_open_interest_socket(self, symbol: str, expiration_date: str):\n        \"\"\"Subscribe to an options open interest stream.\n\n        Stream provides open interest information for specific underlying asset on specific expiration date.\n        Updates every 60 seconds.\n\n        Stream name format: <underlyingAsset>@openInterest@<expirationDate>\n\n        API Reference: https://developers.binance.com/docs/derivatives/option/websocket-market-streams/Open-Interest\n\n        Response fields include:\n        - Event type and timestamps\n        - Option symbol (e.g., 'ETH-221125-2700-C')\n        - Open interest in contracts\n        - Open interest in USDT\n\n        :param symbol: The underlying asset (e.g., \"ETH\")\n        :type symbol: str\n        :param expiration_date: The expiration date (e.g., \"221125\" for Nov 25, 2022)\n        :type expiration_date: str\n        \"\"\"\n        return self._get_options_socket(symbol.upper() + \"@openInterest@\" + expiration_date)\n\n    def options_mark_price_socket(self, symbol: str):\n        \"\"\"Subscribe to an options mark price stream.\n\n        Stream provides mark price information for all option symbols on specific underlying asset.\n        Updates every 1000ms.\n\n        Stream name format: <underlyingAsset>@markPrice\n\n        API Reference: https://developers.binance.com/docs/derivatives/option/websocket-market-streams/Mark-Price\n\n        Response fields include:\n        - Event type and timestamps\n        - Option symbol (e.g., 'ETH-220930-1500-C')\n        - Option mark price\n\n        :param symbol: The underlying asset (e.g., \"ETH\")\n        :type symbol: str\n        \"\"\"\n        return self._get_options_socket(symbol.upper() + \"@markPrice\")\n\n    def options_index_price_socket(self, symbol: str):\n        \"\"\"Subscribe to an options index price stream.\n\n        API Reference: https://developers.binance.com/docs/derivatives/option/websocket-market-streams/Index-Price-Streams\n\n        Stream provides index price information for underlying assets (e.g., ETHUSDT).\n        Updates every 1000ms.\n\n        Response fields include:\n        - Event type and timestamps\n        - Underlying symbol (e.g., 'ETHUSDT')\n        - Index price\n\n        :param symbol: The underlying symbol (e.g., \"ETHUSDT\")\n        :type symbol: str\n        \"\"\"\n        return self._get_options_socket(symbol.upper() + \"@index\")\n\n    async def _stop_socket(self, conn_key):\n        \"\"\"Stop a websocket given the connection key\n\n        :param conn_key: Socket connection key\n        :type conn_key: string\n\n        :returns: None\n        \"\"\"\n        if conn_key not in self._conns:\n            return\n\n        del self._conns[conn_key]\n\n\nclass ThreadedWebsocketManager(ThreadedApiManager):\n    def __init__(\n        self,\n        api_key: Optional[str] = None,\n        api_secret: Optional[str] = None,\n        requests_params: Optional[Dict[str, Any]] = None,\n        tld: str = \"com\",\n        testnet: bool = False,\n        session_params: Optional[Dict[str, Any]] = None,\n        https_proxy: Optional[str] = None,\n        loop: Optional[asyncio.AbstractEventLoop] = None,\n        max_queue_size: int = 100,\n    ):\n        super().__init__(\n            api_key,\n            api_secret,\n            requests_params,\n            tld,\n            testnet,\n            session_params,\n            https_proxy,\n            loop,\n        )\n        self._bsm: Optional[BinanceSocketManager] = None\n        self._max_queue_size = max_queue_size\n\n    async def _before_socket_listener_start(self):\n        assert self._client\n        self._bsm = BinanceSocketManager(\n            client=self._client,\n            max_queue_size=self._max_queue_size\n        )\n\n    def _start_async_socket(\n        self,\n        callback: Callable,\n        socket_name: str,\n        params: Dict[str, Any],\n        path: Optional[str] = None,\n    ) -> str:\n        start_time = time.time()\n        while not self._bsm:\n            if time.time() - start_time > 5:\n                raise RuntimeError(\"Binance Socket Manager failed to initialize after 5 seconds\")\n            time.sleep(0.1)\n        socket = getattr(self._bsm, socket_name)(**params)\n        socket_path: str = path or socket._path  # noqa\n        self._socket_running[socket_path] = True\n        self._loop.call_soon_threadsafe(\n            asyncio.create_task, self.start_listener(socket, socket_path, callback)\n        )\n        return socket_path\n\n    def start_depth_socket(\n        self,\n        callback: Callable,\n        symbol: str,\n        depth: Optional[str] = None,\n        interval: Optional[int] = None,\n    ) -> str:\n        return self._start_async_socket(\n            callback=callback,\n            socket_name=\"depth_socket\",\n            params={\n                \"symbol\": symbol,\n                \"depth\": depth,\n                \"interval\": interval,\n            },\n        )\n\n    def start_kline_socket(\n        self,\n        callback: Callable,\n        symbol: str,\n        interval=AsyncClient.KLINE_INTERVAL_1MINUTE,\n    ) -> str:\n        return self._start_async_socket(\n            callback=callback,\n            socket_name=\"kline_socket\",\n            params={\n                \"symbol\": symbol,\n                \"interval\": interval,\n            },\n        )\n\n    def start_kline_futures_socket(\n        self,\n        callback: Callable,\n        symbol: str,\n        interval=AsyncClient.KLINE_INTERVAL_1MINUTE,\n        futures_type: FuturesType = FuturesType.USD_M,\n        contract_type: ContractType = ContractType.PERPETUAL,\n    ) -> str:\n        return self._start_async_socket(\n            callback=callback,\n            socket_name=\"kline_futures_socket\",\n            params={\n                \"symbol\": symbol,\n                \"interval\": interval,\n                \"futures_type\": futures_type,\n                \"contract_type\": contract_type,\n            },\n        )\n\n    def start_miniticker_socket(\n        self, callback: Callable, update_time: int = 1000\n    ) -> str:\n        return self._start_async_socket(\n            callback=callback,\n            socket_name=\"miniticker_socket\",\n            params={\n                \"update_time\": update_time,\n            },\n        )\n\n    def start_trade_socket(self, callback: Callable, symbol: str) -> str:\n        return self._start_async_socket(\n            callback=callback,\n            socket_name=\"trade_socket\",\n            params={\n                \"symbol\": symbol,\n            },\n        )\n\n    def start_aggtrade_socket(self, callback: Callable, symbol: str) -> str:\n        return self._start_async_socket(\n            callback=callback,\n            socket_name=\"aggtrade_socket\",\n            params={\n                \"symbol\": symbol,\n            },\n        )\n\n    def start_aggtrade_futures_socket(\n        self,\n        callback: Callable,\n        symbol: str,\n        futures_type: FuturesType = FuturesType.USD_M,\n    ) -> str:\n        return self._start_async_socket(\n            callback=callback,\n            socket_name=\"aggtrade_futures_socket\",\n            params={\n                \"symbol\": symbol,\n                \"futures_type\": futures_type,\n            },\n        )\n\n    def start_symbol_miniticker_socket(self, callback: Callable, symbol: str) -> str:\n        return self._start_async_socket(\n            callback=callback,\n            socket_name=\"symbol_miniticker_socket\",\n            params={\n                \"symbol\": symbol,\n            },\n        )\n\n    def start_symbol_ticker_socket(self, callback: Callable, symbol: str) -> str:\n        return self._start_async_socket(\n            callback=callback,\n            socket_name=\"symbol_ticker_socket\",\n            params={\n                \"symbol\": symbol,\n            },\n        )\n\n    def start_ticker_socket(self, callback: Callable) -> str:\n        return self._start_async_socket(\n            callback=callback, socket_name=\"ticker_socket\", params={}\n        )\n\n    def start_index_price_socket(\n        self, callback: Callable, symbol: str, fast: bool = True\n    ) -> str:\n        return self._start_async_socket(\n            callback=callback,\n            socket_name=\"index_price_socket\",\n            params={\"symbol\": symbol, \"fast\": fast},\n        )\n\n    def start_symbol_mark_price_socket(\n        self,\n        callback: Callable,\n        symbol: str,\n        fast: bool = True,\n        futures_type: FuturesType = FuturesType.USD_M,\n    ) -> str:\n        return self._start_async_socket(\n            callback=callback,\n            socket_name=\"symbol_mark_price_socket\",\n            params={\"symbol\": symbol, \"fast\": fast, \"futures_type\": futures_type},\n        )\n\n    def start_all_mark_price_socket(\n        self,\n        callback: Callable,\n        fast: bool = True,\n        futures_type: FuturesType = FuturesType.USD_M,\n    ) -> str:\n        return self._start_async_socket(\n            callback=callback,\n            socket_name=\"all_mark_price_socket\",\n            params={\"fast\": fast, \"futures_type\": futures_type},\n        )\n\n    def start_symbol_ticker_futures_socket(\n        self,\n        callback: Callable,\n        symbol: str,\n        futures_type: FuturesType = FuturesType.USD_M,\n    ) -> str:\n        return self._start_async_socket(\n            callback=callback,\n            socket_name=\"symbol_ticker_futures_socket\",\n            params={\"symbol\": symbol, \"futures_type\": futures_type},\n        )\n\n    def start_individual_symbol_ticker_futures_socket(\n        self,\n        callback: Callable,\n        symbol: str,\n        futures_type: FuturesType = FuturesType.USD_M,\n    ) -> str:\n        return self._start_async_socket(\n            callback=callback,\n            socket_name=\"individual_symbol_ticker_futures_socket\",\n            params={\"symbol\": symbol, \"futures_type\": futures_type},\n        )\n\n    def start_all_ticker_futures_socket(\n        self, callback: Callable, futures_type: FuturesType = FuturesType.USD_M\n    ) -> str:\n        return self._start_async_socket(\n            callback=callback,\n            socket_name=\"all_ticker_futures_socket\",\n            params={\"futures_type\": futures_type},\n        )\n\n    def start_symbol_book_ticker_socket(self, callback: Callable, symbol: str) -> str:\n        return self._start_async_socket(\n            callback=callback,\n            socket_name=\"symbol_book_ticker_socket\",\n            params={\"symbol\": symbol},\n        )\n\n    def start_book_ticker_socket(self, callback: Callable) -> str:\n        return self._start_async_socket(\n            callback=callback, socket_name=\"book_ticker_socket\", params={}\n        )\n\n    def start_multiplex_socket(self, callback: Callable, streams: List[str]) -> str:\n        return self._start_async_socket(\n            callback=callback,\n            socket_name=\"multiplex_socket\",\n            params={\"streams\": streams},\n        )\n\n    def start_options_multiplex_socket(\n        self, callback: Callable, streams: List[str]\n    ) -> str:\n        return self._start_async_socket(\n            callback=callback,\n            socket_name=\"options_multiplex_socket\",\n            params={\"streams\": streams},\n        )\n\n    def start_futures_multiplex_socket(\n        self,\n        callback: Callable,\n        streams: List[str],\n        futures_type: FuturesType = FuturesType.USD_M,\n    ) -> str:\n        return self._start_async_socket(\n            callback=callback,\n            socket_name=\"futures_multiplex_socket\",\n            params={\"streams\": streams, \"futures_type\": futures_type},\n        )\n\n    def start_user_socket(self, callback: Callable) -> str:\n        return self._start_async_socket(\n            callback=callback, socket_name=\"user_socket\", params={}\n        )\n\n    def start_futures_user_socket(self, callback: Callable) -> str:\n        return self._start_async_socket(\n            callback=callback, socket_name=\"futures_user_socket\", params={}\n        )\n\n    def start_coin_futures_user_socket(self, callback: Callable) -> str:\n        return self._start_async_socket(\n            callback=callback, socket_name=\"coin_futures_user_socket\", params={}\n        )\n\n    def start_margin_socket(self, callback: Callable) -> str:\n        return self._start_async_socket(\n            callback=callback, socket_name=\"margin_socket\", params={}\n        )\n\n    def start_futures_socket(self, callback: Callable) -> str:\n        return self._start_async_socket(\n            callback=callback, socket_name=\"futures_socket\", params={}\n        )\n\n    def start_coin_futures_socket(self, callback: Callable) -> str:\n        return self._start_async_socket(\n            callback=callback, socket_name=\"coin_futures_socket\", params={}\n        )\n\n    def start_isolated_margin_socket(self, callback: Callable, symbol: str) -> str:\n        return self._start_async_socket(\n            callback=callback,\n            socket_name=\"isolated_margin_socket\",\n            params={\"symbol\": symbol},\n        )\n\n    def start_options_ticker_socket(self, callback: Callable, symbol: str) -> str:\n        return self._start_async_socket(\n            callback=callback,\n            socket_name=\"options_ticker_socket\",\n            params={\"symbol\": symbol},\n        )\n\n    def start_options_ticker_by_expiration_socket(\n        self, callback: Callable, symbol: str, expiration_date: str\n    ) -> str:\n        return self._start_async_socket(\n            callback=callback,\n            socket_name=\"options_ticker_by_expiration_socket\",\n            params={\"symbol\": symbol, \"expiration_date\": expiration_date},\n        )\n\n    def start_options_recent_trades_socket(\n        self, callback: Callable, symbol: str\n    ) -> str:\n        return self._start_async_socket(\n            callback=callback,\n            socket_name=\"options_recent_trades_socket\",\n            params={\"symbol\": symbol},\n        )\n\n    def start_options_kline_socket(\n        self,\n        callback: Callable,\n        symbol: str,\n        interval=AsyncClient.KLINE_INTERVAL_1MINUTE,\n    ) -> str:\n        return self._start_async_socket(\n            callback=callback,\n            socket_name=\"options_kline_socket\",\n            params={\"symbol\": symbol, \"interval\": interval},\n        )\n\n    def start_options_depth_socket(\n        self, callback: Callable, symbol: str, depth: str = \"10\"\n    ) -> str:\n        return self._start_async_socket(\n            callback=callback,\n            socket_name=\"options_depth_socket\",\n            params={\"symbol\": symbol, \"depth\": depth},\n        )\n\n    def start_futures_depth_socket(\n        self,\n        callback: Callable,\n        symbol: str,\n        depth: str = \"10\",\n        futures_type=FuturesType.USD_M,\n    ) -> str:\n        return self._start_async_socket(\n            callback=callback,\n            socket_name=\"futures_depth_socket\",\n            params={\"symbol\": symbol, \"depth\": depth, \"futures_type\": futures_type},\n        )\n"
  },
  {
    "path": "binance/ws/threaded_stream.py",
    "content": "import asyncio\nimport logging\nimport threading\nfrom typing import Optional, Dict, Any\n\nfrom binance.async_client import AsyncClient\nfrom binance.helpers import get_loop\n\n\nclass ThreadedApiManager(threading.Thread):\n    def __init__(\n        self,\n        api_key: Optional[str] = None,\n        api_secret: Optional[str] = None,\n        requests_params: Optional[Dict[str, Any]] = None,\n        tld: str = \"com\",\n        testnet: bool = False,\n        session_params: Optional[Dict[str, Any]] = None,\n        https_proxy: Optional[str] = None,\n        _loop: Optional[asyncio.AbstractEventLoop] = None,\n        verbose: bool = False,\n    ):\n        \"\"\"Initialise the ThreadedApiManager\n\n        :param api_key: Binance API key\n        :param api_secret: Binance API secret\n        :param requests_params: optional - Dictionary of requests params\n        :param tld: optional - Top level domain, default is 'com'\n        :param testnet: optional - Use testnet endpoint\n        :param session_params: optional - Session params for aiohttp\n        :param https_proxy: optional - Proxy URL\n        :param _loop: optional - Event loop\n        :param verbose: Enable verbose logging for WebSocket connections\n        :type verbose: bool\n        \"\"\"\n        super().__init__()\n        self._loop: asyncio.AbstractEventLoop = get_loop() if _loop is None else _loop\n        self._client: Optional[AsyncClient] = None\n        self._running: bool = True\n        self._socket_running: Dict[str, bool] = {}\n        self._log = logging.getLogger(__name__)\n        self.verbose = verbose\n        self._client_params = {\n            \"api_key\": api_key,\n            \"api_secret\": api_secret,\n            \"requests_params\": requests_params,\n            \"tld\": tld,\n            \"testnet\": testnet,\n            \"session_params\": session_params,\n            \"https_proxy\": https_proxy,\n            \"verbose\": verbose,\n        }\n\n        if verbose:\n            logging.getLogger('binance.ws').setLevel(logging.DEBUG)\n\n    async def _before_socket_listener_start(self): ...\n\n    async def socket_listener(self):\n        try:\n            self._client = await AsyncClient.create(loop=self._loop, **self._client_params)\n            await self._before_socket_listener_start()\n        except Exception as e:\n            self._log.error(f\"Failed to create client: {e}\")\n            self.stop()\n        while self._running:\n            await asyncio.sleep(0.2)\n        while self._socket_running:\n            await asyncio.sleep(0.2)\n        self._log.info(\"Socket listener stopped\")\n\n    async def start_listener(self, socket, path: str, callback):\n        async with socket as s:\n            while self._socket_running[path]:\n                try:\n                    msg = await asyncio.wait_for(s.recv(), 3)\n                except asyncio.TimeoutError:\n                    ...\n                    continue\n                except Exception as e:\n                    self._log.error(f\"Error receiving message: {e}\")\n                    msg = {\n                        \"e\": \"error\",\n                        \"type\": e.__class__.__name__,\n                        \"m\": f\"{e}\",\n                    }\n                if not msg:\n                    continue  # Handle both async and sync callbacks\n                if asyncio.iscoroutinefunction(callback):\n                    asyncio.create_task(callback(msg))\n                else:\n                    callback(msg)\n        del self._socket_running[path]\n\n    def run(self):\n        self._loop.run_until_complete(self.socket_listener())\n\n    def stop_socket(self, socket_name):\n        if socket_name in self._socket_running:\n            self._socket_running[socket_name] = False\n\n    async def stop_client(self):\n        if not self._client:\n            return\n        await self._client.close_connection()\n\n    def stop(self):\n        self._log.debug(\"Stopping ThreadedApiManager\")\n        if not self._running:\n            return\n        self._running = False\n        if self._client and self._loop and not self._loop.is_closed():\n            try:\n                future = asyncio.run_coroutine_threadsafe(\n                    self.stop_client(), self._loop\n                )\n                future.result(timeout=5)  # Add timeout to prevent hanging\n            except Exception as e:\n                # Log the error but don't raise it\n                self._log.error(f\"Error stopping client: {e}\")\n        for socket_name in self._socket_running.keys():\n            self._socket_running[socket_name] = False\n"
  },
  {
    "path": "binance/ws/websocket_api.py",
    "content": "from typing import Dict, Optional\nimport asyncio\n\nfrom websockets import WebSocketClientProtocol  # type: ignore\n\nfrom .constants import WSListenerState\nfrom .reconnecting_websocket import ReconnectingWebsocket\nfrom binance.exceptions import BinanceAPIException, BinanceWebsocketUnableToConnect\n\n\nclass WebsocketAPI(ReconnectingWebsocket):\n    def __init__(self, url: str, tld: str = \"com\", testnet: bool = False, https_proxy: Optional[str] = None):\n        self._tld = tld\n        self._testnet = testnet\n        self._responses: Dict[str, asyncio.Future] = {}\n        self._connection_lock: Optional[asyncio.Lock] = None\n        # Subscription queues for routing user data stream events\n        self._subscription_queues: Dict[str, asyncio.Queue] = {}\n        super().__init__(url=url, prefix=\"\", path=\"\", is_binary=False, https_proxy=https_proxy)\n\n    def register_subscription_queue(self, subscription_id: str, queue: asyncio.Queue) -> None:\n        \"\"\"Register a queue to receive events for a specific subscription.\"\"\"\n        self._subscription_queues[subscription_id] = queue\n\n    def unregister_subscription_queue(self, subscription_id: str) -> None:\n        \"\"\"Unregister a subscription queue.\"\"\"\n        self._subscription_queues.pop(subscription_id, None)\n\n    @property\n    def connection_lock(self) -> asyncio.Lock:\n        if self._connection_lock is None:\n            loop = asyncio.get_event_loop()\n            self._connection_lock = asyncio.Lock()\n        return self._connection_lock\n\n    def _handle_message(self, msg):\n        \"\"\"Override message handling to support request-response\"\"\"\n        parsed_msg = super()._handle_message(msg)\n        self._log.debug(f\"Received message: {parsed_msg}\")\n        if parsed_msg is None:\n            return None\n\n        # Check if this is a subscription event (user data stream, etc.)\n        # These have 'subscriptionId' and 'event' fields instead of 'id'\n        if \"subscriptionId\" in parsed_msg and \"event\" in parsed_msg:\n            subscription_id = parsed_msg[\"subscriptionId\"]\n            event = parsed_msg[\"event\"]\n            # Route to the registered subscription queue if one exists\n            if subscription_id in self._subscription_queues:\n                queue = self._subscription_queues[subscription_id]\n                try:\n                    queue.put_nowait(event)\n                except asyncio.QueueFull:\n                    self._log.error(f\"Subscription queue full for {subscription_id}, dropping event\")\n                except Exception as e:\n                    self._log.error(f\"Error putting event in subscription queue for {subscription_id}: {e}\")\n                return None  # Don't put in main queue\n            else:\n                # No registered queue, return event for main queue (backward compat)\n                return event\n\n        req_id, exception = None, None\n        if \"id\" in parsed_msg:\n            req_id = parsed_msg[\"id\"]\n        if \"status\" in parsed_msg:\n            if parsed_msg[\"status\"] != 200:\n                exception = BinanceAPIException(\n                    parsed_msg, parsed_msg[\"status\"], self.json_dumps(parsed_msg[\"error\"])\n                )\n        if req_id is not None and req_id in self._responses:\n            if exception is not None:\n                self._responses[req_id].set_exception(exception)\n            else:\n                self._responses[req_id].set_result(parsed_msg)\n            return None  # Don't queue request-response messages\n        elif exception is not None:\n            raise exception\n        else:\n            self._log.warning(f\"WS api receieved unknown message: {parsed_msg}\")\n            return None\n\n    async def _ensure_ws_connection(self) -> None:\n        \"\"\"Ensure WebSocket connection is established and ready\n\n        This function will:\n        1. Check if connection exists and is streaming\n        2. Attempt to connect if not\n        3. Wait for connection to be ready\n        4. Handle reconnection if needed\n        \"\"\"\n        async with self.connection_lock:\n            try:\n                if (\n                    self.ws is None\n                    or (isinstance(self.ws, WebSocketClientProtocol) and self.ws.closed)\n                    or self.ws_state != WSListenerState.STREAMING\n                ):\n                    await self.connect()\n\n                    # Wait for connection to be ready\n                    retries = 0\n                    while (\n                        self.ws_state != WSListenerState.STREAMING\n                        and retries < self.MAX_RECONNECTS\n                    ):\n                        if self.ws_state == WSListenerState.RECONNECTING:\n                            self._log.info(\"Connection is reconnecting, waiting...\")\n                            await self._wait_for_reconnect()\n\n                        elif self.ws is None or self.ws.closed:\n                            self._log.info(\"Connection lost, reconnecting...\")\n                            await self.connect()\n\n                        retries += 1\n                        await asyncio.sleep(self.MIN_RECONNECT_WAIT)\n\n                    if self.ws_state != WSListenerState.STREAMING:\n                        raise BinanceWebsocketUnableToConnect(\n                            f\"Failed to establish connection after {retries} attempts\"\n                        )\n\n                    self._log.debug(\"WebSocket connection established\")\n\n            except Exception as e:\n                self._log.error(f\"Error ensuring WebSocket connection: {e}\")\n                raise BinanceWebsocketUnableToConnect(f\"Connection failed: {str(e)}\")\n\n    async def request(self, id: str, payload: dict) -> dict:\n        \"\"\"Send request and wait for response\"\"\"\n        await self._ensure_ws_connection()\n\n        # Create future for response\n        future = asyncio.Future()\n        self._responses[id] = future\n\n        try:\n            # Send request\n            if self.ws is None:\n                raise BinanceWebsocketUnableToConnect(\n                    \"Trying to send request while WebSocket is not connected\"\n                )\n            await self.ws.send(self.json_dumps(payload))\n\n            # Wait for response\n            response = await asyncio.wait_for(future, timeout=self.TIMEOUT)\n\n            # Check for errors\n            if \"error\" in response:\n                raise BinanceWebsocketUnableToConnect(response[\"error\"])\n\n            return response.get(\"result\", response)\n\n        except asyncio.TimeoutError:\n            raise BinanceWebsocketUnableToConnect(\"Request timed out\")\n        except Exception as e:\n            raise e\n        finally:\n            self._responses.pop(id, None)\n\n    async def __aexit__(self, exc_type, exc_val, exc_tb):\n        \"\"\"Clean up responses before closing\"\"\"\n        response_ids = list(self._responses.keys())  # Create a copy of keys\n        for req_id in response_ids:\n            future = self._responses.pop(req_id)  # Remove and get the future\n            if not future.done():\n                future.set_exception(\n                    BinanceWebsocketUnableToConnect(\"WebSocket closing\")\n                )\n        await super().__aexit__(exc_type, exc_val, exc_tb)\n"
  },
  {
    "path": "code-generator.py",
    "content": "import re\nimport requests\nfrom bs4 import BeautifulSoup\nimport os\n\nfrom binance.client import Client\nfrom binance.exceptions import BinanceAPIException\n\nURLS = [\n    'https://developers.binance.com/docs/binance-spot-api-docs',\n    'https://developers.binance.com/docs/derivatives/change-log',\n    'https://developers.binance.com/docs/margin_trading/change-log',\n    'https://developers.binance.com/docs/algo/change-log',\n    'https://developers.binance.com/docs/wallet/change-log',\n    'https://developers.binance.com/docs/copy_trading/change-log',\n    'https://developers.binance.com/docs/convert/change-log',\n    'https://developers.binance.com/docs/sub_account/change-log',\n    'https://developers.binance.com/docs/binance_link/change-log',\n    'https://developers.binance.com/docs/auto_invest/change-log',\n    'https://developers.binance.com/docs/staking/change-log',\n    'https://developers.binance.com/docs/dual_investment/change-log',\n    'https://developers.binance.com/docs/mining/change-log',\n    'https://developers.binance.com/docs/crypto_loan/change-log',\n    'https://developers.binance.com/docs/vip_loan/change-log',\n    'https://developers.binance.com/docs/c2c/change-log',\n    'https://developers.binance.com/docs/fiat/change-log',\n    'https://developers.binance.com/docs/nft/change-log',\n    'https://developers.binance.com/docs/gift_card/change-log',\n    'https://developers.binance.com/docs/rebate/change-log',\n    'https://developers.binance.com/docs/simple_earn/change-log',\n    'https://developers.binance.com/docs/pay/change-log'\n]\n\n# Map endpoint prefixes to client.py's request methods\nPREFIX_MAP = {\n    '/api': '_request_api',\n    '/sapi': '_request_margin_api',\n    '/papi': '_request_papi_api',\n    '/fapi': '_request_futures_api',\n    '/dapi': '_request_futures_coin_api',\n    '/eapi': '_request_options_api',\n    '/wapi': '_request_website'\n}\n\nDEPRECATED_PREFIXES = [\n    '/wapi',\n]\n\nDEPRECATED_ENDPOINTS = [\n    ('GET', '/fapi/v1/ticker/price'),\n    ('GET', '/fapi/v1/pmExchangeInfo'),\n    ('POST', '/api/v3/order/oco'),\n    ('POST', '/sapi/v1/eth-staking/eth/stake'),\n    ('GET', '/sapi/v1/eth-staking/account'),\n    ('GET', '/sapi/v1/portfolio/interest-rate'),\n    ('GET', '/api/v1/order'),\n    ('GET', '/api/v1/openOrders'),\n    ('POST', '/api/v1/order'),\n    ('DELETE', '/api/v1/order'),\n    ('GET', '/api/v1/allOrders'),\n    ('GET', '/api/v1/account'),\n    ('GET', '/api/v1/myTrades'),\n    ('POST', '/sapi/v1/loan/flexible/borrow'),\n    ('GET', '/sapi/v1/loan/flexible/ongoing/orders'),\n    ('GET', '/sapi/v1/loan/flexible/borrow/history'),\n    ('POST', '/sapi/v1/loan/flexible/repay'),\n    ('GET', '/sapi/v1/loan/flexible/repay/history'),\n    ('POST', '/sapi/v1/loan/flexible/adjust/ltv'),\n    ('GET', '/sapi/v1/loan/flexible/ltv/adjustment/history'),\n    ('GET', '/sapi/v1/loan/flexible/loanable/data'),\n    ('GET', '/sapi/v1/loan/flexible/collateral/data')\n]\n\n# Some request methods do not require a version argument\nNO_VERSION_FUNCTIONS = [\n    '_request_options_api',\n    '_request_futures_data_api'\n]\n\ndef fetch_endpoints():\n    \"\"\"Fetch endpoints from the provided Binance doc URLs, filtering duplicates.\"\"\"\n    endpoints = set()\n    deprecated_endpoints = set()\n    for url in URLS:\n        print(f'Fetching {url}')\n        page = requests.get(url)\n        soup = BeautifulSoup(page.content, 'html.parser')\n        all_code_blocks = soup.find_all('code')\n\n        for code in all_code_blocks:\n            code_text = code.get_text().strip()\n            parts = code_text.split(' ')\n            \n            if len(parts) >=2:\n                parts[0] = parts[0].strip()\n                parts[1] = parts[1].strip().split('?')[0]\n            # Basic check for lines that look like: GET /path or POST /path etc.\n            if len(parts) >= 2 and parts[0] in ['GET', 'POST', 'PUT', 'DELETE'] and parts[1] is not None and parts[1] != '':\n                method = parts[0]\n                endpoint = parts[1]\n                # Ensure endpoint starts with /\n                if not endpoint.startswith('/'):\n                    endpoint = '/' + endpoint\n                \n                # Check both deprecated prefixes and specific endpoints\n                if any(endpoint.startswith(prefix) for prefix in DEPRECATED_PREFIXES) or (method, endpoint) in DEPRECATED_ENDPOINTS:\n                    deprecated_endpoints.add((method, endpoint))\n                    continue  # Skip adding to main endpoints set\n                \n                # Use a tuple of (method, endpoint) for uniqueness\n                endpoints.add((method, endpoint))\n    print(f'Found {len(deprecated_endpoints)} deprecated endpoints in the docs.')\n    print(f'Found {len(endpoints)} unique endpoints in the docs.')\n    \n    # Filter endpoints that don't start with any known prefix\n    valid_endpoints = {\n        (method, endpoint) for method, endpoint in endpoints \n        if any(endpoint.startswith(prefix) for prefix in PREFIX_MAP.keys())\n    }\n    \n    filtered_count = len(endpoints) - len(valid_endpoints)\n    print(f'Filtered out {filtered_count} endpoints that don\\'t match known prefixes')\n    print(f'Remaining endpoints: {len(valid_endpoints)}')\n    \n    return valid_endpoints\n\ndef get_request_function_and_path(endpoint: str) -> tuple[str | None, str | None, int | None]:\n    \"\"\"\n    Given an endpoint (e.g. '/sapi/v1/userInfo'), determine which _request_*_api\n    function is appropriate in the client, remove the recognized prefix plus any\n    version segments (e.g. /v1/), parse out any version (v1, v2, etc.), \n    and return (request_function, stripped_path, version).\n\n    Example:\n        endpoint = '/sapi/v1/exchangeInfo'\n        -> returns ('_request_margin_api', 'exchangeInfo', 1)\n\n    If no recognized prefix is found, return (None, None, None).\n    If no version is found, version will be None.\n    \"\"\"\n    # Sort prefixes by length descending to match the longest prefix first\n    sorted_prefixes = sorted(PREFIX_MAP.keys(), key=len, reverse=True)\n    request_func = None\n    stripped = None\n\n    # Identify which prefix is present, if any\n    matched_prefix = None\n    for prefix in sorted_prefixes:\n        if endpoint.startswith(prefix):\n            request_func = PREFIX_MAP[prefix]\n            matched_prefix = prefix\n            break\n\n    # If no recognized prefix, return null\n    if not request_func or matched_prefix is None:\n        return None, None, None\n\n    stripped = endpoint[len(matched_prefix):]\n\n    # Attempt to parse out the version, e.g. '/v1/', '/v2/'\n    version_match = re.search(r'/v(\\d+)/', stripped)\n    version = None\n    if version_match:\n        # Convert the matched text into an integer\n        version = int(version_match.group(1))\n\n    # Remove version segments like /v1/, /v2/\n    if stripped:\n        stripped = re.sub(r'/v\\d+/', '/', stripped)\n        # Strip leading/trailing slashes\n        stripped = stripped.strip('/')\n\n    return request_func, stripped, version\n\ndef check_method_in_file(method, endpoint, file_name):\n    \"\"\"\n    Return True if a function for this endpoint likely exists in client.py.\n    \"\"\"\n    if not os.path.isfile(file_name):\n        print(f'{file_name} does not exist')\n        return False\n\n    func_name, stripped_path, version = get_request_function_and_path(endpoint)\n    \n    # If no known request function is found, we consider it not found.\n    if not func_name or not stripped_path:\n        print(f'No known request function for endpoint: {endpoint}')\n        return False\n\n    with open(file_name, 'r', encoding='utf-8') as f:\n        content = f.read()\n\n    # Remove any leftover version tokens from the path\n    stripped_path = re.sub(r'^v\\d+/', '', stripped_path)\n    stripped_path = re.sub(r'/v\\d+/', '/', stripped_path)\n\n    patterns = []\n    \n    if func_name == \"_request_api\":\n        if version == 3:\n            # v3 endpoints use PRIVATE_API_VERSION or \"v3\"\n            patterns.extend([\n                # Direct request with PRIVATE_API_VERSION\n                rf'{re.escape(func_name)}\\s*\\(\\s*\"{re.escape(method.lower())}\"\\s*,\\s*\"{re.escape(stripped_path)}\"[\\s\\S]*?version\\s*=\\s*self\\.PRIVATE_API_VERSION[\\s\\S]*?\\)',\n                # Direct request with \"v3\"\n                rf'{re.escape(func_name)}\\s*\\(\\s*\"{re.escape(method.lower())}\"\\s*,\\s*\"{re.escape(stripped_path)}\"[\\s\\S]*?version\\s*=\\s*[\"\\']v3[\"\\'][\\s\\S]*?\\)',\n                # Helper method with PRIVATE_API_VERSION\n                rf'_{method.lower()}\\s*\\(\\s*\"{re.escape(stripped_path)}\"(?:\\s*,\\s*(?:True|False))?[\\s\\S]*?version\\s*=\\s*self\\.PRIVATE_API_VERSION[\\s\\S]*?\\)',\n                # Helper method with \"v3\"\n                rf'_{method.lower()}\\s*\\(\\s*\"{re.escape(stripped_path)}\"(?:\\s*,\\s*(?:True|False))?[\\s\\S]*?version\\s*=\\s*[\"\\']v3[\"\\'][\\s\\S]*?\\)'\n            ])\n        elif version == 1:\n            # v1 endpoints can use either no version arg, PUBLIC_API_VERSION, or \"v1\"\n            patterns.extend([\n                # Direct request with no version\n                rf'{re.escape(func_name)}\\s*\\(\\s*\"{re.escape(method.lower())}\"\\s*,\\s*\"{re.escape(stripped_path)}\"[\\s\\S]*?\\)',\n                # Direct request with PUBLIC_API_VERSION\n                rf'{re.escape(func_name)}\\s*\\(\\s*\"{re.escape(method.lower())}\"\\s*,\\s*\"{re.escape(stripped_path)}\"[\\s\\S]*?version\\s*=\\s*self\\.PUBLIC_API_VERSION[\\s\\S]*?\\)',\n                # Direct request with \"v1\"\n                rf'{re.escape(func_name)}\\s*\\(\\s*\"{re.escape(method.lower())}\"\\s*,\\s*\"{re.escape(stripped_path)}\"[\\s\\S]*?version\\s*=\\s*[\"\\']v1[\"\\'][\\s\\S]*?\\)',\n                # Helper method with no version\n                rf'_{method.lower()}\\s*\\(\\s*\"{re.escape(stripped_path)}\"(?:\\s*,\\s*(?:True|False))?[\\s\\S]*?\\)',\n                # Helper method with PUBLIC_API_VERSION\n                rf'_{method.lower()}\\s*\\(\\s*\"{re.escape(stripped_path)}\"(?:\\s*,\\s*(?:True|False))?[\\s\\S]*?version\\s*=\\s*self\\.PUBLIC_API_VERSION[\\s\\S]*?\\)',\n                # Helper method with \"v1\"\n                rf'_{method.lower()}\\s*\\(\\s*\"{re.escape(stripped_path)}\"(?:\\s*,\\s*(?:True|False))?[\\s\\S]*?version\\s*=\\s*[\"\\']v1[\"\\'][\\s\\S]*?\\)'\n            ])\n    else:\n        # Non-API requests (margin, futures, etc.)\n        patterns.append(\n            rf'{re.escape(func_name)}\\s*\\(\\s*\"{re.escape(method.lower())}\"\\s*,\\s*\"{re.escape(stripped_path)}\"'\n        )\n\n    # Check all patterns\n    for pattern in patterns:\n        if re.search(pattern, content, re.DOTALL):\n            return True\n\n    return False\n\ndef convert_to_function_name(method: str, endpoint: str) -> str:\n    \"\"\"\n    Convert an endpoint path to a consistent function name format with appropriate prefix and version.\n    Examples:\n        GET, /api/v3/ticker/tradingDay -> v3_get_ticker_trading_day\n        GET, /sapi/v1/margin/order -> margin_v1_get_order\n        GET, /fapi/v1/ticker/price -> futures_v1_get_ticker_price\n        GET, /dapi/v1/ticker/price -> futures_coin_v1_get_ticker_price\n        GET, /vapi/v1/ticker -> options_v1_get_ticker\n    \"\"\"\n    # Get the request function and path info\n    request_function, cleaned_endpoint, version = get_request_function_and_path(endpoint)\n    \n    # Map request functions to their prefix in the function name\n    PREFIX_NAME_MAP = {\n        '_request_margin_api': 'margin',\n        '_request_papi_api': 'papi',\n        '_request_futures_api': 'futures',\n        '_request_futures_coin_api': 'futures_coin',\n        '_request_options_api': 'options'\n    }\n    \n    # Remove known prefixes and version segments first\n    cleaned_endpoint = endpoint\n    sorted_prefixes = sorted(PREFIX_MAP.keys(), key=len, reverse=True)\n    for prefix in sorted_prefixes:\n        if cleaned_endpoint.startswith(prefix):\n            cleaned_endpoint = cleaned_endpoint[len(prefix):]\n            break\n\n    # Remove version segments and leading/trailing slashes\n    cleaned_endpoint = re.sub(r'/v\\d+/', '/', cleaned_endpoint)\n    cleaned_endpoint = cleaned_endpoint.strip('/')\n\n    # Split on slashes and process each part\n    parts = cleaned_endpoint.split('/')\n    processed_parts = []\n    \n    for part in parts:\n        # Replace hyphens with underscores\n        part = part.replace('-', '_')\n        part = part.replace('.', '_')\n        \n        # Insert underscore before capital letters in camelCase\n        part = re.sub(r'([a-z0-9])([A-Z])', r'\\1_\\2', part)\n        \n        # Convert to lowercase\n        part = part.lower()\n        \n        # Remove any duplicate underscores\n        part = re.sub(r'_+', '_', part)\n        \n        processed_parts.append(part)\n\n    # Join all parts with underscores\n    base_name = '_'.join(processed_parts)\n    base_name = re.sub(r'_+', '_', base_name)  # Remove any duplicate underscores\n\n    # Add version to the name (default to v1 if no version found)\n    version_str = f\"v{version if version else ''}\"\n\n    # Prepend the appropriate prefix if this is a special endpoint\n    if request_function in PREFIX_NAME_MAP:\n        prefix = PREFIX_NAME_MAP[request_function]\n        return f\"{prefix}_{version_str}_{method.lower()}_{base_name}\"\n    \n    # Default case (for _request_api)\n    return f\"{version_str}_{method.lower()}_{base_name}\"\n\ndef check_function(method, request_function, cleaned_endpoint, version_arg, params={}):\n    \"\"\"\n    Check if the function is signed based on the endpoint. If not found or deprecated, return None.\n    For GET requests, call the endpoint and check if it returns an error indicating a signature is required.\n    \"\"\"\n    if method != \"GET\":\n        return True\n    else:\n        try:\n            client = Client(\"\", \"\")\n            client_function = getattr(client, request_function)\n            version = {\"version\": version_arg} if version_arg else {}\n            client_function(\n                method.lower(), \n                cleaned_endpoint, \n                signed=False, \n                **version,\n                **params\n            )\n            return False\n        except BinanceAPIException as e:\n            if e.status_code == 400 and \"symbol\" in e.message:\n               return check_function(method, request_function, cleaned_endpoint, version_arg, {'data': {'symbol': 'BTCUSDT'}})\n            if 'signature' in e.message or 'API-key' in e.message:\n                return True\n            if 'The endpoint has been out of maintenance' in e.message or \\\n                'This endpoint has been deprecated, please remove as soon as possible.' in e.message or \\\n                e.status_code == 404:\n                    return None\n            else:\n                print(f\"Error calling endpoint {request_function} - {cleaned_endpoint} - {version_arg} - {params}\")\n                return None\n        except Exception as e:\n            print(f\"Error calling endpoint {request_function} - {cleaned_endpoint} - {version_arg} - {params}\")\n            return None\n\ndef generate_function_code(method, endpoint, type=\"sync\", file_name=\"./binance/client.py\"):\n    \"\"\"\n    Determines which _request_*_api function, path, and version to call based on the endpoint,\n    generates a placeholder function to handle the specified method/endpoint.\n    If the chosen request function is in NO_VERSION_FUNCTIONS, the code does not pass a 'version' argument.\n    If no recognized prefix is found, returns an empty string.\n    If GET function will test if the endpoint is public or not\n    \"\"\"\n    request_function, cleaned_endpoint, version = get_request_function_and_path(endpoint)\n\n    # If no recognized prefix, skip generating\n    if not request_function:\n        return \"\"\n\n    func_name = convert_to_function_name(method, endpoint)\n    \n    # Build version argument if needed\n    version_string = \"\"\n    if request_function in NO_VERSION_FUNCTIONS or version is None:\n        # No version arg is needed\n        version_arg = None\n    elif request_function == \"_request_api\":\n        version_arg = f\"v{version}\"\n    else:\n        # If a version was found, pass version= the integer, else default to 1\n        version_arg = version if version else 1\n\n    if version_arg is not None:\n        if isinstance(version_arg, str):\n            version_string = f', version=\"{version_arg}\"'\n        else:\n            version_string = f\", version={version_arg}\"\n\n    is_signed = check_function(method, request_function, cleaned_endpoint, version_arg)\n    if is_signed is None:\n        return\n\n    code_snippet = \"\"\n    if type == \"sync\":\n        code_snippet = f\"\"\"\n    def {func_name}(self, **params):\n        \\\"\\\"\\\"\n        Placeholder function for {method.upper()} {endpoint}.\n        Note: This function was auto-generated. Any issue please open an issue on GitHub.\n\n        :param params: parameters required by the endpoint\n        :type params: dict\n\n        :returns: API response\n        \\\"\\\"\\\"\n        return self.{request_function}(\"{method.lower()}\", \"{cleaned_endpoint}\", signed={is_signed}, data=params{version_string})\n        \"\"\"\n    elif type == \"async\":\n        code_snippet = f\"\"\"\n    async def {func_name}(self, **params):\n        return await self.{request_function}(\"{method.lower()}\", \"{cleaned_endpoint}\", signed={is_signed}, data=params{version_string})\n        \"\"\"\n        with open('./binance/client.py', 'r', encoding='utf-8') as f:\n            content = f.read()\n        if f\"def {func_name}(\"in content:\n            code_snippet += f\"\"\"\n    {func_name}.__doc__ = Client.{func_name}.__doc__\n            \"\"\"\n    \n    with open(file_name, 'a', encoding='utf-8') as f:\n        f.write(code_snippet)\n\ndef write_function_to_endpoints_md(method, endpoint):\n    \"\"\"\n    Append a brief reference entry to Endpoints.md, showing the usage example.\n    First checks if the entry already exists to avoid duplicates.\n    \"\"\"\n    function_name = convert_to_function_name(method, endpoint)\n    \n    \n    # Check if the entry already exists\n    with open('Endpoints.md', 'r', encoding='utf-8') as f:\n        content = f.read()\n        # Look for the exact method and endpoint\n        if f\"**{method.upper()} {endpoint}\" in content:\n            return False\n    \n    # Create the entry we want to add\n    md_entry = (\n        f\"\\t- **{method} {endpoint}**\\n\"\n        f\"    ```python\\n\"\n        f\"    client.{function_name}(**params)\\n\"\n        f\"    ```\\n\\n\"\n    )\n\n    # If we get here, the entry doesn't exist, so append it\n    with open('Endpoints.md', 'a', encoding='utf-8') as f:\n        f.write(md_entry)\n    \n    return True\n    \ndef main():\n    endpoints = fetch_endpoints()\n\n    # Write to Endpoints.md\n    endpoints_md_created = 0\n    for method, endpoint in endpoints:\n        success = write_function_to_endpoints_md(method, endpoint)\n        if success:\n            endpoints_md_created += 1\n    print(f\"Added {endpoints_md_created} endpoints to Endpoints.md\")\n\n    # Filter out endpoints already in client.py\n    new_endpoints = []\n    for method, endpoint in endpoints:\n        if not check_method_in_file(method, endpoint, './binance/client.py'):\n            new_endpoints.append((method, endpoint))\n\n    print(f\"{len(new_endpoints)} endpoints were added out of {len(endpoints)} scrapped in client.py\")\n\n    # Generate placeholder code for these endpoints\n    for method, endpoint in new_endpoints:\n        generate_function_code(method, endpoint, type=\"sync\", file_name=\"./binance/client.py\")\n\n    # Generate async functions\n    new_endpoints_async = []\n    for method, endpoint in endpoints:\n        if not check_method_in_file(method, endpoint, './binance/async_client.py'):\n            new_endpoints_async.append((method, endpoint))\n\n    for method, endpoint in new_endpoints_async:\n        generate_function_code(method, endpoint, type=\"async\", file_name=\"./binance/async_client.py\")\n\n    print(f\"{len(new_endpoints_async)} endpoints were added out of {len(endpoints)} scrapped in async_client.py\")\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "docs/Makefile",
    "content": "# Minimal makefile for Sphinx documentation\n#\n\n# You can set these variables from the command line.\nSPHINXOPTS    =\nSPHINXBUILD   = python -msphinx\nSPHINXPROJ    = python-binance\nSOURCEDIR     = .\nBUILDDIR      = _build\n\n# Put it first so that \"make\" without argument is like \"make help\".\nhelp:\n\t@$(SPHINXBUILD) -M help \"$(SOURCEDIR)\" \"$(BUILDDIR)\" $(SPHINXOPTS) $(O)\n\n.PHONY: help Makefile\n\n# Catch-all target: route all unknown targets to Sphinx using the new\n# \"make mode\" option.  $(O) is meant as a shortcut for $(SPHINXOPTS).\n%: Makefile\n\t@$(SPHINXBUILD) -M $@ \"$(SOURCEDIR)\" \"$(BUILDDIR)\" $(SPHINXOPTS) $(O)\n\nrst:\n\tsphinx-apidoc -f -o ./ ../\n"
  },
  {
    "path": "docs/account.rst",
    "content": "Account Endpoints\n=================\n\nOrders\n------\n\nOrder Validation\n^^^^^^^^^^^^^^^^\n\nBinance has a number of rules around symbol pair orders with validation on minimum price, quantity and total order value.\n\nRead more about their specifics in the `Filters <https://binance-docs.github.io/apidocs/spot/en/#filters>`_\nsection of the official API.\n\nRead `Understanding Binance Order Filters <https://sammchardy.github.io/binance/2021/05/03/binance-order-filters.html>`_\nfor more information about price and quantity filters on `Binance <https://www.binance.com/?ref=10099792>`_.\n\nIt can be helpful to format the output using formatting\n\n.. code:: python\n\n    amount = 0.000234234\n    precision = 5\n    amt_str = \"{:0.0{}f}\".format(amount, precision)\n\nOr if you have the tickSize or stepSize then use the helper to round to step size\n\n.. code:: python\n\n    from binance.helpers import round_step_size\n\n    amount = 0.000234234\n    tick_size = 0.00001\n    rounded_amount = round_step_size(amount, tick_size)\n\n\n`Fetch all orders <binance.html#binance.client.Client.get_all_orders>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    orders = client.get_all_orders(symbol='BNBBTC', limit=10)\n\n\n`Place an order <binance.html#binance.client.Client.create_order>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n**Place an order**\n\nUse the `create_order` function to have full control over creating an order\n\n.. code:: python\n\n    from binance.enums import *\n    order = client.create_order(\n        symbol='BNBBTC',\n        side=SIDE_BUY,\n        type=ORDER_TYPE_LIMIT,\n        timeInForce=TIME_IN_FORCE_GTC,\n        quantity=100,\n        price='0.00001')\n\n**Place a limit order**\n\nUse the helper functions to easily place a limit buy or sell order\n\n.. code:: python\n\n    order = client.order_limit_buy(\n        symbol='BNBBTC',\n        quantity=100,\n        price='0.00001')\n\n    order = client.order_limit_sell(\n        symbol='BNBBTC',\n        quantity=100,\n        price='0.00001')\n\n\n**Place a market order**\n\nUse the helper functions to easily place a market buy or sell order\n\n.. code:: python\n\n    order = client.order_market_buy(\n        symbol='BNBBTC',\n        quantity=100)\n\n    order = client.order_market_sell(\n        symbol='BNBBTC',\n        quantity=100)\n\n**Place an OCO order**\n\nUse the `create_oco_order` function to have full control over creating an OCO order\n\n.. code:: python\n\n    from binance.enums import *\n    order = client.create_oco_order(\n        symbol='BNBBTC',\n        side=SIDE_SELL,\n        stopLimitTimeInForce=TIME_IN_FORCE_GTC,\n        quantity=100,\n        stopPrice='0.00001',\n        price='0.00002')\n\n\n`Place a test order <binance.html#binance.client.Client.create_test_order>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nCreates and validates a new order but does not send it into the exchange.\n\n.. code:: python\n\n    from binance.enums import *\n    order = client.create_test_order(\n        symbol='BNBBTC',\n        side=SIDE_BUY,\n        type=ORDER_TYPE_LIMIT,\n        timeInForce=TIME_IN_FORCE_GTC,\n        quantity=100,\n        price='0.00001')\n\n`Check order status <binance.html#binance.client.Client.get_order>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    order = client.get_order(\n        symbol='BNBBTC',\n        orderId='orderId')\n\n\n`Cancel an order <binance.html#binance.client.Client.cancel_order>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    result = client.cancel_order(\n        symbol='BNBBTC',\n        orderId='orderId')\n\n\n`Get all open orders <binance.html#binance.client.Client.get_open_orders>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    orders = client.get_open_orders(symbol='BNBBTC')\n\n`Get all orders <binance.html#binance.client.Client.get_all_orders>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    orders = client.get_all_orders(symbol='BNBBTC')\n\n\nAccount\n-------\n\n`Get account info <binance.html#binance.client.Client.get_account>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    info = client.get_account()\n\n`Get asset balance <binance.html#binance.client.Client.get_asset_balance>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    balance = client.get_asset_balance(asset='BTC')\n\n`Get account status <binance.html#binance.client.Client.get_account_status>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    status = client.get_account_status()\n\n`Get account API trading status <binance.html#binance.client.Client.get_account_api_trading_status>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    status = client.get_account_api_trading_status()\n\n`Get trades <binance.html#binance.client.Client.get_my_trades>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    trades = client.get_my_trades(symbol='BNBBTC')\n\n`Get trade fees <binance.html#binance.client.Client.get_trade_fee>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    # get fees for all symbols\n    fees = client.get_trade_fee()\n\n    # get fee for one symbol\n    fees = client.get_trade_fee(symbol='BNBBTC')\n\n`Get asset details <binance.html#binance.client.Client.get_asset_details>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    details = client.get_asset_details()\n\n`Get dust log <binance.html#binance.client.Client.get_dust_log>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    log = client.get_dust_log()\n\n`Transfer dust <binance.html#binance.client.Client.transfer_dust>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    transfer = client.transfer_dust(asset='BNZ')\n\n\n`Get Asset Dividend History <binance.html#binance.client.Client.get_asset_dividend_history>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    history = client.get_asset_dividend_history()\n\n\n`Disable Fast Withdraw Switch <binance.html#binance.client.Client.disable_fast_withdraw_switch>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    client.disable_fast_withdraw_switch()\n\n\n`Enable Fast Withdraw Switch <binance.html#binance.client.Client.enable_fast_withdraw_switch>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    client.enable_fast_withdraw_switch()\n"
  },
  {
    "path": "docs/binance.rst",
    "content": "Binance API\n===========\n\nClient module\n-------------\n\n.. automodule:: binance.client\n    :members:\n    :undoc-members:\n    :show-inheritance:\n\nAsync client module\n-------------------\n\n.. automodule:: binance.async_client\n    :members:\n    :undoc-members:\n    :show-inheritance:\n\nWebsockets module\n-----------------\n\n.. automodule:: binance.ws.streams\n    :members:\n    :undoc-members:\n    :show-inheritance:\n\nThreaded streams module\n-----------------------\n\n.. automodule:: binance.ws.threaded_stream\n    :members:\n    :undoc-members:\n    :show-inheritance:\n\ndepthcache module\n-----------------\n\n.. automodule:: binance.ws.depthcache\n    :members:\n    :undoc-members:\n    :show-inheritance:\n\nexceptions module\n-----------------\n\n.. automodule:: binance.exceptions\n    :members:\n    :undoc-members:\n    :show-inheritance:\n\nhelpers module\n--------------\n\n.. automodule:: binance.helpers\n    :members:\n    :undoc-members:\n    :show-inheritance:\n"
  },
  {
    "path": "docs/changelog.rst",
    "content": "Changelog\n\nv1.0.35 - 2026-02-16\n^^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- chore: normalize package name by @carlosmiei in https://github.com/sammchardy/python-binance/pull/1653\n- feat: upgrade margin socket to use websocket api by @pcriadoperez in https://github.com/sammchardy/python-binance/pull/1670\n- feat: Update futures algo order API with new TP/SL parameters by @paul-lestyo in https://github.com/sammchardy/python-binance/pull/1672\n\n**Fixed**\n- fix: reconnects for websocket connection closed ok and ws-api by @pcriadoperez in https://github.com/sammchardy/python-binance/pull/1655\n\nv1.0.34 - 2025-12-16\n^^^^^^^^^^^^^^^^^^^^\n\n**Added**\n- verbose mode for inspecting requests (verbose=True) (#1642)\n- feat: add support for rpi orders (#1644)\n- feat: update futures ticker endpoint to v2 (#1650)\n- feat: add support for websocket algo orders (#1646)\n- docs: add missing doc references from async client (#1651)\n\n**Fixed**\n\n- fix: remove duplicate import and replace type() with isinstance() (#1623)\n- fix(client): use proper exception instead of assert for US endpoints (#1641)\n\nv1.0.33 - 2025-12-06\n^^^^^^^^^^^^^^^^^^^^\n\n**Fixed**\n\n- fix: reconnect keep alive (#1637)\n\n**Added**\n\n- moved conditional orders to the new futures algo serivce (#1639)\n\nv1.0.32 - 2025-11-03\n^^^^^^^^^^^^^^^^^^^^\n\n**Fixed**\n\n-  signature encoding for non-ascii symbols in both private and public endpoints (#1619)\n\n\nv1.0.30 - 2025-10-14\n^^^^^^^^^^^^^^^^^^^^\n=========\n\nv1.0.31 - 2025-10-29\n^^^^^^^^^^^^^^^^^^^^\n\n**Fixed**\n\n- fix signature encoding for non-ascii symbols (#1612), eg: 币安人生USDT\n\n\nv1.0.30 - 2025-10-14\n^^^^^^^^^^^^^^^^^^^^\n\n**Fixed**\n\n- Set default limit=None for futures_historical_klines* (fetch full range by default) (#1607)\n- fixed a typo in a method name (#1605)\n- all links updated (#1600)\n- throw readloopclosed error if trying to connect once read loop is already closed (#1593)\n- ensure spot v3 version (#1587\n\n\n**Added**\n- Demo trading\n- websocket userdatastream.signature support, deprecate listenkey for spot market\n\n\nv1.0.28 - 2025-02-27\n^^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- Add `papi_get_rate_limit`\n- Add docs for `create_oco_order`\n- Add `uiKlines` support\n- Add options websocket market streams\n- Add dozens of missing endpoints\n\nv1.0.29 - 2025-05-19\n^^^^^^^^^^^^^^^^^^^^\n\n**Fixed**\n\n- Ws tesnet spot URLs update\n\n\nv1.0.28 - 2025-02-27\n^^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- Add `papi_get_rate_limit`\n- Add docs for `create_oco_order`\n- Add `uiKlines` support\n- Add options websocket market streams\n- Add dozens of missing endpoints\n\n\n**Fixed**\n\n- Ws API not allowing more than 100 requests\n- Return empty json instead of throwing error on empty response\n- Json_dumps when using orjson\n\n\nv1.0.27 - 2024-12-31\n^^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- Add futures_taker_long_short_ratio endpoint, thanks to @ngoclam9415\n- Add portfolio margin user data streams\n\n\n**Fixed**\n\n- Close read loop before closing websocket\n- Fix threaded_stream\n- Closing keepAliveWebsocker fix\n\nv1.0.26 - 2024-12-23\n^^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- Websockets docs\n- support for microseconds time unit\n- futures data link endpoints\n- return type to _get_account_socket  thanks to @zhen1007\n- futures_index_price_constituents endpoint\n\n\n**Fixed**\n\n- FuturesDepthCacheManager and OptionsDepthCacheManager to __init__\n- EDDSA random error\n\n\nv1.0.25 - 2024-12-05\n^^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- borrow-repay endpoints (margin_interest_rate_history/margin_get_borrow_repay_records/margin_borrow_repay/etc)\n- futures_mark_price_klines thanks to @zhen1007\n- futures_index_price_klines and futures_premium_index_klines\n- HistoricalKlinesType enum enhanced\n- block trades endpoints (options_create_block_trade_order, options_cancel_block_trade_order, etc)\n- dapi asyn endpoints (futures_coin_account_order_history_download, futures_coin_account_order_history_download_link, etc)\n\n\n**Fixed**\n\n- Removed unnecessary logs with `error` level\n- Remove CANCEL read_loop error log\n- Fix error type for when message queue is full\n- Fixes that if first connect fails it would not throw and let the user wait indefinitely\n- Improves error handling passing to user error type for different scenarios\n\n\nv1.0.24 - 2024-11-28\n^^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- Exposed internal classes for easier subclassing\n\n\n**Fixed**\n\n- Fixed package outdated structure causing import errors\n\nv1.0.23 - 2024-11-27\n^^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- CRUD over Websockets (create/fetch/edit/cancel) through Websockets\n- orjson support\n- overridable `headers` per request\n- added default recvWindow parameter\n- Proxy support for Websockets\n- Gift card API\n- `cancel_replace_order`, `cancel_all_open_orders`  and `cancel_all_open_margin_orders` thanks to @m-HD\n- missing `futures_modify_order` from async client\n- ruff format\n- missing endpoint for `futures_edit_order`\n\n**Fixed**\n\n- updated `create_oco_order` endpoint\n- batch orders signature issue\n- `fail_connection` issue related to the `websockets` upgrade\n- `eddsa` signature issue\n\n\nv1.0.22 - 2024-10-29\n^^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- futures all tickers stream\n- futures coin-m all tickers stream\n\n**Fixed**\n\n- hang in the ThreadedApiManager\n\n\nv1.0.21 - 2024-10-23\n^^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- Some new endpoints\n\n**Fixed**\n\n- url encoding for coin-m post endpoints\n- batch order endpoint\n- Some minor bug fixes\n\nv1.0.20 - 2024-10-22\n^^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- EDDSA authentication\n- Portfolio Margin endpoints\n- Some new futures endpoints\n- Proxy support for the AsyncClient\n- Version override is possible now through `params`\n\n**Fixed**\n\n- Migrated `positionRisk` to v3\n- Fixed the error `AttributeError(\"'Connect' object has no attribute 'protocol'\")`\n- Some minor bug fixes\n\nv1.0.19 - 2023-08-11\n^^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- some new futures and margin endpoints\n- pass session_params to streams for AsyncClient\n\n**Fixed**\n\n- removed debug statements\n- options testnet URL\n- accessing msg variable before assignment\n\nv1.0.18 - 2023-08-09\n^^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- TRAILING_STOP_MARKET option for orders\n\n**Fixed**\n\n- futures api endpoint versions\n- margin endpoint request methods\n\n\nv1.0.17 - 2023-02-21\n^^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- RSA key authentication\n- Support for api1, api2, api3, api4 base endpoints\n- binance.us staking endpoints\n- Options ticker by expiration socket\n- Staking endpoints\n- Pay and Convert endpoints\n- Futures index info endpoint\n- Open OCO Orders endpoint\n- Param to pass session params to aiohttp.ClientSession\n\n**Updated**\n\n- Some margin endpoint versions\n- Support testnet for more streams\n\n**Fixed**\n\n- Indefinite websocket reconnect loop\n- Crash on parsing code from some errors\n\nv1.0.16 - 2022-04-09\n^^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- pass limit param to all kline functions\n- increase default for kline functions from 500 to 1000\n- add HistoricalKlinesType.FUTURES_COIN as option for kline functions\n- testnet URL for coin_futures_socket\n\n**Updated**\n\n- round_step_size more accurate\n\n**Fixed**\n\n- remove deprecated loop param\n- websockets unpinned\n- hanging websockets in exiting state\n- check start_ts after end_ts for klines\n- multi assets margin params\n\n\nv1.0.15 - 2021-09-27\n^^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- Enable/disable margin account for symbol endpoints\n- Top trader long/short positions endpoint\n- Global long/short ratio endpoint\n\n**Fixed**\n\n- fix websockets to 9.1\n- websocket reconnect updates\n- fix futures kline sockets\n\n\nv1.0.14 - 2021-09-08\n^^^^^^^^^^^^^^^^^^^^\n\n**Fixed**\n\n- websocket reconnecting\n\nv1.0.13 - 2021-09-08\n^^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- Futures Depth Cache Manager\n- Futures kline websocket stream\n- Coin Futures User websocket stream\n- New Margin endpoints\n- Margin OCO order endpoints\n- Fiat endpoints\n- C2C endpoints\n- Account API permissions endpoint\n\n**Fixed**\n\n- changed `asset` to `coin` in withdraw endpoint\n\n\nv1.0.12 - 2021-06-03\n^^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- coin futures batch order function\n\n**Fixed**\n\n- threaded websockets on python3.9\n- filter out None params in request kwargs\n- deconflict streams with same name on different websocket urls\n- reduce close timeout on websocket close to short time to reduce waiting\n\n\nv1.0.10 - 2021-05-13\n^^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- futures multi-asset margin mode endpoints\n- optional symbol param to get_all_tickers\n\n**Fixed**\n\n- start_multiplex_socket remove lower case filter on stream names\n\nv1.0.9 - 2021-05-12\n^^^^^^^^^^^^^^^^^^^\n\n**Fixed**\n\n- start_book_ticker_socket and start_multiplex_socket to call correct async function\n\nv1.0.8 - 2021-05-11\n^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- old style websocket and depth cache managers as option without interacting with asyncio\n\n**Fixed**\n\n- fixed issue with get_historical_klines in Client\n- remove print debug line\n\nv1.0.7\n^^^^^^\n\n**Fixed**\n\n- remove version param from get_sub_account_assets\n\nv1.0.6\n^^^^^^\n\n**Fixed**\n\n- fix time for authenticated stream keepalive\n\nv1.0.5\n^^^^^^\n\n**Fixed**\n\n- Restored access to last response on client\n\nv1.0.4\n^^^^^^\n\n**Added**\n\n- Futures Testnet support\n- Kline type for fetching historical klines\n\n**Fixed**\n\n- Spot Testnet websocket URL\n\nv1.0.3\n^^^^^^\n\n**Added**\n\n- Spot Testnet support\n\nv1.0.2\n^^^^^^\n\n**Added**\n\n- start of typing to client and websockets\n\n**Fixed**\n\n- end_str, limit, spot params in kline fetching\n- drop None values in params passed\n\n**Updated**\n\n- more examples in docs\n\nv1.0.1\n^^^^^^\n\n**Fixed**\n\n- restored params for Client and AsyncClient classes\n\nv1.0.0\n^^^^^^\n\n**Added**\n\n- Async support for all REST endpoints\n- USDⓈ-M and Coin-M Futures websocket streams\n- Websockets use same tld as Client\n- convert type option for DepthCache\n\n**Breaking Changes**\n\n- Supports only py3.6+\n- All wapi calls changed to sapi\n- Websockets have changed to use Asynchronous context managers\n\n**Fixed**\n\n- get_historical_klines params\n\nv0.7.11\n^^^^^^^\n\n**Added**\n- Vanilla Options REST endpoints\n- Vanilla Options websockets\n- Futures order type enums\n\n**Updated**\n\n- websocket keep-alive functions for different socket types\n- dependencies\n\n**Fixed**\n\n- change to User-Agent to avoid connection issues\n\nv0.7.5.dev\n^^^^^^^^^^\n**Changed**\n- Stock json lib to ujson (https://github.com/sammchardy/python-binance/pull/383)\n\nv0.7.5 - 2020-02-06\n^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- Futures REST endpoints\n- Lending REST endpoints\n- OCO Orders function `create_oco_order`, `order_oco_buy`, `order_oco_sell`\n- Average Price function `get_avg_price`\n- Support for other domains (.us, .jp, etc)\n\n**Updated**\n\n- dependencies\n\n**Fixed**\n\n- websocket keepalive callback not found\n\nv0.7.4 - 2019-09-22\n^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- symbol book ticker websocket streams\n- margin websocket stream\n\n**Updated**\n\n- can call Client without any params\n- make response a property of the Client class so you can access response properties after a request\n\n**Fixed**\n\n- issue with None value params causing errors\n\nv0.7.3 - 2019-08-12\n^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- sub account endpoints\n- dust transfer endpoint\n- asset divident history endpoint\n\n**Removed**\n\n- deprecated withdraw fee endpoint\n\nv0.7.2 - 2019-08-01\n^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- margin trading endpoints\n\n**Fixed**\n\n- depth cache clearing bug\n\nv0.7.1 - 2019-01-23\n^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- limit param to DepthCacheManager\n- limit param to get_historical_klines\n- update_time to DepthCache class\n\n**Updated**\n\n- test coverage\n\n**Fixed**\n\n- super init in Websocket class\n- removal of request params from signature\n- empty set issue in aggregate_trade_iter\n\n\nv0.7.0 - 2018-08-08\n^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- get_asset_details endpoint\n- get_dust_log endpoint\n- get_trade_fee endpoint\n- ability for multiple DepthCacheManagers to share a BinanceSocketManager\n- get_historial_klines_generator function\n- custom socket timeout param for BinanceSocketManager\n\n**Updated**\n\n- general dependency version\n- removed support for python3.3\n\n**Fixed**\n\n- add a super init on BinanceClientProtocol\n\nv0.6.9 - 2018-04-27\n^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- timestamp in milliseconds to `get_historical_klines` function\n- timestamp in milliseconds to `aggregate_trade_iter` function\n\n**Fixed**\n\n- Don't close user stream listen key on socket close\n\nv0.6.8 - 2018-03-29\n^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- `get_withdraw_fee` function\n\n**Fixed**\n\n- Remove unused LISTENKEY_NOT_EXISTS\n- Optimise the historical klines function to reduce requests\n- Issue with end_time in aggregate trade iterator\n\nv0.6.7 - 2018-03-14\n^^^^^^^^^^^^^^^^^^^\n\n**Fixed**\n\n- Issue with `get_historical_klines` when response had exactly 500 results\n- Changed BinanceResponseException to BinanceRequestException\n- Set default code value in BinanceApiException properly\n\nv0.6.6 - 2018-02-17\n^^^^^^^^^^^^^^^^^^^\n\n**Fixed**\n\n- User stream websocket keep alive strategy updated\n\nv0.6.5 - 2018-02-13\n^^^^^^^^^^^^^^^^^^^\n\n**Fixed**\n\n- `get_historical_klines` response for month interval\n\nv0.6.4 - 2018-02-09\n^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- system status endpoint `get_system_status`\n\nv0.6.3 - 2018-01-29\n^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- mini ticker socket function `start_miniticker_socket`\n- aggregate trade iterator `aggregate_trade_iter`\n\n**Fixes**\n\n- clean up `interval_to_milliseconds` logic\n- general doc and file cleanups\n\nv0.6.2 - 2018-01-12\n^^^^^^^^^^^^^^^^^^^\n\n**Fixes**\n\n- fixed handling Binance errors that aren't JSON objects\n\nv0.6.1 - 2018-01-10\n^^^^^^^^^^^^^^^^^^^\n\n**Fixes**\n\n- added missing dateparser dependency to setup.py\n- documentation fixes\n\nv0.6.0 - 2018-01-09\n^^^^^^^^^^^^^^^^^^^\n\nNew version because why not.\n\n**Added**\n\n- get_historical_klines function to fetch klines for any date range\n- ability to override requests parameters globally\n- error on websocket disconnect\n- example related to blog post\n\n**Fixes**\n\n- documentation fixes\n\nv0.5.17 - 2018-01-08\n^^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- check for name parameter in withdraw, set to asset parameter if not passed\n\n**Update**\n\n- Windows install error documentation\n\n**Removed**\n\n- reference to disable_validation in documentation\n\nv0.5.16 - 2018-01-06\n^^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- addressTag documentation to withdraw function\n- documentation about requests proxy environment variables\n\n**Update**\n\n- FAQ for signature error with solution to regenerate API key\n- change create_order to create_test_order in example\n\n**Fixed**\n\n- reference to BinanceAPIException in documentation\n\nv0.5.15 - 2018-01-03\n^^^^^^^^^^^^^^^^^^^^\n\n**Fixed**\n\n- removed all references to WEBSOCKET_DEPTH_1 enum\n\nv0.5.14 - 2018-01-02\n^^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- Wait for depth cache socket to start\n- check for sequential depth cache messages\n\n**Updated**\n\n- documentation around depth websocket and diff and partial responses\n\n**Removed**\n\n- Removed unused WEBSOCKET_DEPTH_1 enum\n- removed unused libraries and imports\n\nv0.5.13 - 2018-01-01\n^^^^^^^^^^^^^^^^^^^^\n\n**Fixed**\n\n- Signature invalid error\n\nv0.5.12 - 2017-12-29\n^^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- get_asset_balance helper function to fetch an individual asset's balance\n\n**Fixed**\n\n- added timeout to requests call to prevent hanging\n- changed variable type to str for price parameter when creating an order\n- documentation fixes\n\nv0.5.11 - 2017-12-28\n^^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- refresh interval parameter to depth cache to keep it fresh, set default at 30 minutes\n\n**Fixed**\n\n- watch depth cache socket before fetching order book to replay any messages\n\nv0.5.10 - 2017-12-28\n^^^^^^^^^^^^^^^^^^^^\n\n**Updated**\n\n- updated dependencies certifi and cryptography to help resolve signature error\n\nv0.5.9 - 2017-12-26\n^^^^^^^^^^^^^^^^^^^\n\n**Fixed**\n\n- fixed websocket reconnecting, was no distinction between manual close or network error\n\nv0.5.8 - 2017-12-25\n^^^^^^^^^^^^^^^^^^^\n\n**Changed**\n\n- change symbol parameter to optional for get_open_orders function\n- added listenKey parameter to stream_close function\n\n**Added**\n\n- get_account_status function that was missed\n\nv0.5.7 - 2017-12-24\n^^^^^^^^^^^^^^^^^^^\n\n**Changed**\n\n- change depth cache callback parameter to optional\n\n**Added**\n\n- note about stopping Twisted reactor loop to exit program\n\nv0.5.6 - 2017-12-20\n^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- get_symbol_info function to simplify getting info about a particular symbol\n\nv0.5.5 - 2017-12-19\n^^^^^^^^^^^^^^^^^^^\n\n**Changed**\n\n- Increased default limit for order book on depth cache from 10 to 500\n\nv0.5.4 - 2017-12-14\n^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- symbol property made public on DepthCache class\n\n**Changed**\n\n- Enums now also accessible from binance.client.Client and binance.websockets.BinanceSocketManager\n\nv0.5.3 - 2017-12-09\n^^^^^^^^^^^^^^^^^^^\n\n**Changed**\n\n- User stream refresh timeout from 50 minutes to 30 minutes\n- User stream socket listen key change check simplified\n\nv0.5.2 - 2017-12-08\n^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- start_multiplex_socket function to BinanceSocketManager to create multiplexed streams\n\nv0.5.1 - 2017-12-06\n^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- Close method for DepthCacheManager\n\n**Fixes**\n\n- Fixed modifying array error message when closing the BinanceSocketManager\n\nv0.5.0 - 2017-12-05\n^^^^^^^^^^^^^^^^^^^\n\nUpdating to match new API documentation\n\n**Added**\n\n- Recent trades endpoint\n- Historical trades endpoint\n- Order response type option\n- Check for invalid user stream listen key in socket to keep connected\n\n**Fixes**\n\n- Fixed exchange info endpoint as it was renamed slightly\n\nv0.4.3 - 2017-12-04\n^^^^^^^^^^^^^^^^^^^\n\n**Fixes**\n\n- Fixed stopping sockets where they were reconnecting\n- Fixed websockets unable to be restarted after close\n- Exception in parsing non-JSON websocket message\n\nv0.4.2 - 2017-11-30\n^^^^^^^^^^^^^^^^^^^\n\n**Removed**\n\n- Removed websocket update time as 0ms option is not available\n\nv0.4.1 - 2017-11-24\n^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- Reconnecting websockets, automatic retry on disconnect\n\nv0.4.0 - 2017-11-19\n^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- Get deposit address endpoint\n- Upgraded withdraw endpoints to v3\n- New exchange info endpoint with rate limits and full symbol info\n\n**Removed**\n\n- Order validation to return at a later date\n\nv0.3.8 - 2017-11-17\n^^^^^^^^^^^^^^^^^^^\n\n**Fixes**\n\n- Fix order validation for market orders\n- WEBSOCKET_DEPTH_20 value, 20 instead of 5\n- General tidy up\n\nv0.3.7 - 2017-11-16\n^^^^^^^^^^^^^^^^^^^\n\n**Fixes**\n\n- Fix multiple depth caches sharing a cache by initialising bid and ask objects each time\n\nv0.3.6 - 2017-11-15\n^^^^^^^^^^^^^^^^^^^\n\n**Fixes**\n\n- check if Reactor is already running\n\nv0.3.5 - 2017-11-06\n^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- support for BNB market\n\n**Fixes**\n\n- fixed error if new market type is created that we don't know about\n\nv0.3.4 - 2017-10-31\n^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- depth parameter to depth socket\n- interval parameter to kline socket\n- update time parameter for compatible sockets\n- new enums for socket depth and update time values\n- better websocket documentation\n\n**Changed**\n\n- Depth Cache Manager uses 0ms socket update time\n- connection key returned when creating socket, this key is then used to stop it\n\n**Fixes**\n\n- General fixes\n\nv0.3.3 - 2017-10-31\n^^^^^^^^^^^^^^^^^^^\n\n**Fixes**\n\n- Fixes for broken tests\n\nv0.3.2 - 2017-10-30\n^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- More test coverage of requests\n\n**Fixes**\n\n- Order quantity validation fix\n\nv0.3.1 - 2017-10-29\n^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- Withdraw exception handler with translation of obscure error\n\n**Fixes**\n\n- Validation fixes\n\nv0.3.0 - 2017-10-29\n^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- Withdraw endpoints\n- Order helper functions\n\nv0.2.0 - 2017-10-27\n^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- Symbol Depth Cache\n\nv0.1.6 - 2017-10-25\n^^^^^^^^^^^^^^^^^^^\n\n**Changes**\n\n- Upgrade to v3 signed endpoints\n- Update function documentation\n\n\nv0.1.5 - 2017-09-12\n^^^^^^^^^^^^^^^^^^^\n\n**Changes**\n\n- Added get_all_tickers call\n- Added get_orderbook_tickers call\n- Added some FAQs\n\n**Fixes**\n\n- Fix error in enum value\n\nv0.1.4 - 2017-09-06\n^^^^^^^^^^^^^^^^^^^\n\n**Changes**\n\n- Added parameter to disable client side order validation\n\nv0.1.3 - 2017-08-26\n^^^^^^^^^^^^^^^^^^^\n\n**Changes**\n\n- Updated documentation\n\n**Fixes**\n\n- Small bugfix\n\nv0.1.2 - 2017-08-25\n^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- Travis.CI and Coveralls support\n\n**Changes**\n\n- Validation for pairs using public endpoint\n\nv0.1.1 - 2017-08-17\n^^^^^^^^^^^^^^^^^^^\n\n**Added**\n\n- Validation for HSR/BTC pair\n\nv0.1.0 - 2017-08-16\n^^^^^^^^^^^^^^^^^^^\n\nWebsocket release\n\n**Added**\n\n- Websocket manager\n- Order parameter validation\n- Order and Symbol enums\n- API Endpoints for Data Streams\n\nv0.0.2 - 2017-08-14\n^^^^^^^^^^^^^^^^^^^\n\nInitial version\n\n**Added**\n\n- General, Market Data and Account endpoints\n"
  },
  {
    "path": "docs/conf.py",
    "content": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# python-binance documentation build configuration file, created by\n# sphinx-quickstart on Thu Sep 21 20:24:54 2017.\n#\n# This file is execfile()d with the current directory set to its\n# containing dir.\n#\n# Note that not all possible configuration values are present in this\n# autogenerated file.\n#\n# All configuration values have a default; values that are commented out\n# serve to show the default.\n\n# If extensions (or modules to document with autodoc) are in another directory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\n#\nimport os\nimport sys\n\nsys.path.insert(0, os.path.abspath(\"..\"))\n\n\n# -- General configuration ------------------------------------------------\n\n# If your documentation needs a minimal Sphinx version, state it here.\n#\n# needs_sphinx = '1.0'\n\n# Add any Sphinx extension module names here, as strings. They can be\n# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom\n# ones.\nextensions = [\n    \"sphinx.ext.autodoc\",\n    \"sphinx.ext.imgmath\",\n    \"sphinx.ext.viewcode\",\n    \"sphinx.ext.githubpages\",\n    \"sphinx_copybutton\",\n]\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = [\"_templates\"]\n\n# The suffix(es) of source filenames.\n# You can specify multiple suffix as a list of string:\n#\n# source_suffix = ['.rst', '.md']\nsource_suffix = \".rst\"\n\n# The master toctree document.\nmaster_doc = \"index\"\n\n# General information about the project.\nproject = \"python-binance\"\ncopyright = \"2017, Sam McHardy\"\nauthor = \"Sam McHardy\"\n\n# The version info for the project you're documenting, acts as replacement for\n# |version| and |release|, also used in various other places throughout the\n# built documents.\n#\n# The short X.Y version.\nversion = \"0.2.0\"\n# The full version, including alpha/beta/rc tags.\nrelease = \"0.2.0\"\n\n# The language for content autogenerated by Sphinx. Refer to documentation\n# for a list of supported languages.\n#\n# This is also used if you do content translation via gettext catalogs.\n# Usually you set \"language\" from the command line for these cases.\nlanguage = \"en\"\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\n# This patterns also effect to html_static_path and html_extra_path\nexclude_patterns = [\"_build\", \"Thumbs.db\", \".DS_Store\"]\n\n# The name of the Pygments (syntax highlighting) style to use.\npygments_style = \"sphinx\"\n\n# If true, `todo` and `todoList` produce output, else they produce nothing.\ntodo_include_todos = False\n\n\n# -- Options for HTML output ----------------------------------------------\n\n# The theme to use for HTML and HTML Help pages.  See the documentation for\n# a list of builtin themes.\n#\n# html_theme = 'alabaster'\nhtml_theme = \"sphinx_rtd_theme\"\n\n# Theme options are theme-specific and customize the look and feel of a theme\n# further.  For a list of options available for each theme, see the\n# documentation.\n#\n# html_theme_options = {}\n\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\nhtml_static_path = [\"_static\"]\n\n# Custom sidebar templates, must be a dictionary that maps document names\n# to template names.\n#\n# This is required for the alabaster theme\n# refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars\nhtml_sidebars = {\n    \"**\": [\n        \"about.html\",\n        \"navigation.html\",\n        \"relations.html\",  # needs 'show_related': True theme option to display\n        \"searchbox.html\",\n        \"donate.html\",\n    ]\n}\n\n\n# -- Options for HTMLHelp output ------------------------------------------\n\n# Output file base name for HTML help builder.\nhtmlhelp_basename = \"python-binancedoc\"\n\n\n# -- Options for LaTeX output ---------------------------------------------\n\nlatex_elements = {\n    # The paper size ('letterpaper' or 'a4paper').\n    #\n    # 'papersize': 'letterpaper',\n    # The font size ('10pt', '11pt' or '12pt').\n    #\n    # 'pointsize': '10pt',\n    # Additional stuff for the LaTeX preamble.\n    #\n    # 'preamble': '',\n    # Latex figure (float) alignment\n    #\n    # 'figure_align': 'htbp',\n}\n\n# Grouping the document tree into LaTeX files. List of tuples\n# (source start file, target name, title,\n#  author, documentclass [howto, manual, or own class]).\nlatex_documents = [\n    (\n        master_doc,\n        \"python-binance.tex\",\n        \"python-binance Documentation\",\n        \"Sam McHardy\",\n        \"manual\",\n    ),\n]\n\n\n# -- Options for manual page output ---------------------------------------\n\n# One entry per manual page. List of tuples\n# (source start file, name, description, authors, manual section).\nman_pages = [\n    (master_doc, \"python-binance\", \"python-binance Documentation\", [author], 1)\n]\n\n\n# -- Options for Texinfo output -------------------------------------------\n\n# Grouping the document tree into Texinfo files. List of tuples\n# (source start file, target name, title, author,\n#  dir menu entry, description, category)\ntexinfo_documents = [\n    (\n        master_doc,\n        \"python-binance\",\n        \"python-binance Documentation\",\n        author,\n        \"python-binance\",\n        \"One line description of project.\",\n        \"Miscellaneous\",\n    ),\n]\n\n\ndef skip(app, what, name, obj, skip, options):\n    # Ensure that the __init__ method gets documented.\n    if name == \"__init__\":\n        return False\n    return skip\n\n\ndef setup(app):\n    app.connect(\"autodoc-skip-member\", skip)\n"
  },
  {
    "path": "docs/constants.rst",
    "content": "Binance Constants\n=================\n\nBinance requires specific string constants for Order Types, Order Side, Time in Force, Order response and Kline intervals these are found on `binance.client.Client`.\n\n.. code:: python\n\n    SYMBOL_TYPE_SPOT = 'SPOT'\n\n    ORDER_STATUS_NEW = 'NEW'\n    ORDER_STATUS_PARTIALLY_FILLED = 'PARTIALLY_FILLED'\n    ORDER_STATUS_FILLED = 'FILLED'\n    ORDER_STATUS_CANCELED = 'CANCELED'\n    ORDER_STATUS_PENDING_CANCEL = 'PENDING_CANCEL'\n    ORDER_STATUS_REJECTED = 'REJECTED'\n    ORDER_STATUS_EXPIRED = 'EXPIRED'\n\n    KLINE_INTERVAL_1SECOND = '1s'\n    KLINE_INTERVAL_1MINUTE = '1m'\n    KLINE_INTERVAL_3MINUTE = '3m'\n    KLINE_INTERVAL_5MINUTE = '5m'\n    KLINE_INTERVAL_15MINUTE = '15m'\n    KLINE_INTERVAL_30MINUTE = '30m'\n    KLINE_INTERVAL_1HOUR = '1h'\n    KLINE_INTERVAL_2HOUR = '2h'\n    KLINE_INTERVAL_4HOUR = '4h'\n    KLINE_INTERVAL_6HOUR = '6h'\n    KLINE_INTERVAL_8HOUR = '8h'\n    KLINE_INTERVAL_12HOUR = '12h'\n    KLINE_INTERVAL_1DAY = '1d'\n    KLINE_INTERVAL_3DAY = '3d'\n    KLINE_INTERVAL_1WEEK = '1w'\n    KLINE_INTERVAL_1MONTH = '1M'\n\n    SIDE_BUY = 'BUY'\n    SIDE_SELL = 'SELL'\n\n    ORDER_TYPE_LIMIT = 'LIMIT'\n    ORDER_TYPE_MARKET = 'MARKET'\n    ORDER_TYPE_STOP_LOSS = 'STOP_LOSS'\n    ORDER_TYPE_STOP_LOSS_LIMIT = 'STOP_LOSS_LIMIT'\n    ORDER_TYPE_TAKE_PROFIT = 'TAKE_PROFIT'\n    ORDER_TYPE_TAKE_PROFIT_LIMIT = 'TAKE_PROFIT_LIMIT'\n    ORDER_TYPE_LIMIT_MAKER = 'LIMIT_MAKER'\n\n    TIME_IN_FORCE_GTC = 'GTC'\n    TIME_IN_FORCE_IOC = 'IOC'\n    TIME_IN_FORCE_FOK = 'FOK'\n\n    ORDER_RESP_TYPE_ACK = 'ACK'\n    ORDER_RESP_TYPE_RESULT = 'RESULT'\n    ORDER_RESP_TYPE_FULL = 'FULL'\n\n    # For accessing the data returned by Client.aggregate_trades().\n    AGG_ID             = 'a'\n    AGG_PRICE          = 'p'\n    AGG_QUANTITY       = 'q'\n    AGG_FIRST_TRADE_ID = 'f'\n    AGG_LAST_TRADE_ID  = 'l'\n    AGG_TIME           = 'T'\n    AGG_BUYER_MAKES    = 'm'\n    AGG_BEST_MATCH     = 'M'\n\n\nFor Websocket Depth these are found on `binance.websockets.BinanceSocketManager`\n\n.. code:: python\n\n    WEBSOCKET_DEPTH_5 = '5'\n    WEBSOCKET_DEPTH_10 = '10'\n    WEBSOCKET_DEPTH_20 = '20'\n\nTo use in your code reference either binance.client.Client or binance.websockets.BinanceSocketManager\n\n.. code:: python\n\n    from binance.client import Client\n    from binance.websockets import BinanceSocketManager\n\n    side = Client.SIDE_BUY\n"
  },
  {
    "path": "docs/depth_cache.rst",
    "content": "Depth Cache\n===========\n\nTo follow the depth cache updates for a symbol there are 2 options similar to websockets.\n\nUse the `DepthCacheManager <binance.html#binance.depth_cache.DepthCacheManager>`_\n(or `OptionsDepthCacheManager <binance.html#binance.depth_cache.OptionsDepthCacheManager>`_ for vanilla options) or\nuse the `ThreadedDepthCacheManager <binance.html#binance.depth_cache.ThreadedDepthCacheManager>`_\nif you don't want to interact with asyncio.\n\nThreadedDepthCacheManager Websocket Usage\n-----------------------------------------\n\nStarting sockets on the ThreadedDepthCacheManager requires a callback parameter, similar to old implementations of\ndepth cache on python-binance pre v1\n\nThreadedDepthCacheManager takes similar parameters to the `Client <binance.html#binance.client.Client>`_ class\nas it creates an AsyncClient internally.\n\nAs these use threads `start()` is required to be called before starting any depth cache streams.\n\nTo keep the ThreadedDepthCacheManager running using `join()` to join it to the main thread.\n\n.. code:: python\n\n    from binance import ThreadedDepthCacheManager\n\n    def main():\n\n        dcm = ThreadedDepthCacheManager()\n        # start is required to initialise its internal loop\n        dcm.start()\n\n        def handle_depth_cache(depth_cache):\n            print(f\"symbol {depth_cache.symbol}\")\n            print(\"top 5 bids\")\n            print(depth_cache.get_bids()[:5])\n            print(\"top 5 asks\")\n            print(depth_cache.get_asks()[:5])\n            print(\"last update time {}\".format(depth_cache.update_time))\n\n        dcm_name = dcm.start_depth_cache(handle_depth_cache, symbol='BNBBTC')\n\n        # multiple depth caches can be started\n        dcm_name = dcm.start_depth_cache(handle_depth_cache, symbol='ETHBTC')\n\n        dcm.join()\n\n\n    if __name__ == \"__main__\":\n       main()\n\n\n**Stop Individual Depth Cache**\n\nWhen starting a stream, a name for that stream will be returned. This can be used to stop that individual stream\n\n.. code:: python\n\n    from binance import ThreadedDepthCacheManager\n\n    symbol = 'BNBBTC'\n\n    dcm = ThreadedDepthCacheManager()\n    dcm.start()\n\n    def handle_depth_cache(depth_cache):\n        print(f\"message type: {msg['e']}\")\n        print(msg)\n\n    dcm_name = dcm.start_depth_cache(handle_depth_cache, symbol='BNBBTC')\n\n    # some time later\n\n    dcm.stop_socket(dcm_name)\n\n**Stop All Depth Cache streams**\n\n.. code:: python\n\n    from binance import ThreadedDepthCacheManager\n\n    symbol = 'BNBBTC'\n\n    dcm = ThreadedDepthCacheManager()\n    dcm.start()\n\n    def handle_depth_cache(depth_cache):\n        print(f\"message type: {msg['e']}\")\n        print(msg)\n\n    dcm_name = dcm.start_depth_cache(handle_depth_cache, symbol='BNBBTC')\n\n    # some time later\n\n    dcm.stop()\n\nAttempting to start a stream after `stop` is called will not work.\n\n\nDepthCacheManager or OptionsDepthCacheManager Usage\n---------------------------------------------------\n\nCreate the manager like so, passing the async api client, symbol and an optional callback function.\n\n.. code:: python\n\n    import asyncio\n\n    from binance import AsyncClient, DepthCacheManager\n\n\n    async def main():\n        client = await AsyncClient.create()\n        dcm = DepthCacheManager(client, 'BNBBTC')\n\n        async with dcm as dcm_socket:\n            while True:\n                depth_cache = await dcm_socket.recv()\n                print(\"symbol {}\".format(depth_cache.symbol))\n                print(\"top 5 bids\")\n                print(depth_cache.get_bids()[:5])\n                print(\"top 5 asks\")\n                print(depth_cache.get_asks()[:5])\n                print(\"last update time {}\".format(depth_cache.update_time))\n\n    if __name__ == \"__main__\":\n\n        loop = asyncio.get_event_loop()\n        loop.run_until_complete(main())\n\nThe `DepthCacheManager` returns an Asynchronous Context Manager which can be used with `async for`\nor by interacting with the `__aenter__` and `__aexit__` functions\n\nBy default the depth cache will fetch the order book via REST request every 30 minutes.\nThis duration can be changed by using the `refresh_interval` parameter. To disable the refresh pass 0 or None.\nThe socket connection will stay open receiving updates to be replayed once the full order book is received.\n\nShare a Socket Manager\n----------------------\n\nHere dcm1 and dcm2 share the same instance of BinanceSocketManager\n\n.. code:: python\n\n    from binance.websockets import BinanceSocketManager\n    from binance.depthcache import DepthCacheManager\n    bm = BinanceSocketManager(client)\n    dcm1 = DepthCacheManager(client, 'BNBBTC', bm=bm)\n    dcm2 = DepthCacheManager(client, 'ETHBTC', bm=bm)\n\nWebsocket Errors\n----------------\n\nIf the underlying websocket is disconnected and is unable to reconnect None is returned for the depth_cache parameter.\nIf the underlying websocket is disconnected an error msg is passed to the callback and to recv() containing the error message.\nIn the case the BinanceWebsocketClosed is returned, the websocket will attempt to reconnect 5 times before returning a BinanceUnableToConnect error.\nExample:\n\n.. code:: python\n\n            depth_cache = await dcm.recv()\n            if isinstance(depth_cache, dict) and depth_cache.get('e') == 'error':\n                logger.error(f\"Received depth cache error in callback: {depth_cache}\")\n                if type == 'BinanceWebsocketClosed':\n                    # ignore as attempts to reconnect\n                    continue\n                break\n\n.. code:: python\n            def handle_depth_cache(depth_cache):\n                if isinstance(depth_cache, dict) and depth_cache.get('e') == 'error':\n                    logger.error(f\"Received depth cache error in callback: {depth_cache}\")\n                    type = depth_cache.get('type')\n                    if type == 'BinanceWebsocketClosed':\n                        # Automatically attempts to reconnect\n                        return\n                    dcm.stop()\n                    return\n                # handle non error cases here\n\nExamples\n--------\n\n.. code:: python\n\n    # 1 hour interval refresh\n    dcm = DepthCacheManager(client, 'BNBBTC', refresh_interval=60*60)\n\n    # disable refreshing\n    dcm = DepthCacheManager(client, 'BNBBTC', refresh_interval=0)\n\n.. code:: python\n\n    async with dcm as dcm_socket:\n        while True:\n            depth_cache = await dcm_socket.recv()\n            print(\"symbol {}\".format(depth_cache.symbol))\n            print(\"top 5 bids\")\n            print(depth_cache.get_bids()[:5])\n            print(\"top 5 asks\")\n            print(depth_cache.get_asks()[:5])\n            print(\"last update time {}\".format(depth_cache.update_time))\n\nTo use the magic `__aenter__` and `__aexit__` functions to use this class without the `async with`\n\n.. code:: python\n\n    dcm = DepthCacheManager(client, 'BNBBTC')\n\n    await dcm.__aenter__()\n    depth_cache = await dcm.recv()\n    print(\"symbol {}\".format(depth_cache.symbol))\n    print(\"top 5 bids\")\n    print(depth_cache.get_bids()[:5])\n    print(\"top 5 asks\")\n    print(depth_cache.get_asks()[:5])\n    print(\"last update time {}\".format(depth_cache.update_time))\n\n    # exit the context manager\n    await dcm.__aexit__(None, None, None)\n"
  },
  {
    "path": "docs/exceptions.rst",
    "content": "Exceptions\n==========\n\nBinanceRequestException\n------------------------\n\nRaised if a non JSON response is returned\n\nBinanceAPIException\n-------------------\n\nOn an API call error a binance.exceptions.BinanceAPIException will be raised.\n\nThe exception provides access to the\n\n- `status_code` - response status code\n- `response` - response object\n- `code` - Binance error code\n- `message` - Binance error message\n- `request` - request object if available\n\n.. code:: python\n\n    try:\n        client.get_all_orders()\n    except BinanceAPIException as e:\n        print e.status_code\n        print e.message\n"
  },
  {
    "path": "docs/faqs.rst",
    "content": "FAQ\n=======\n\n*Q: Why do I get \"Timestamp for this request is not valid\"*\n\n*A*: This occurs in 2 different cases.\n\nThe timestamp sent is outside of the serverTime - recvWindow value\nThe timestamp sent is more than 1000ms ahead of the server time\n\nCheck that your system time is in sync. See `this issue <https://github.com/sammchardy/python-binance/issues/2#issuecomment-324878152>`_ for some sample code to check the difference between your local\ntime and the Binance server time.\n\n*Q: Why do I get \"Signature for this request is not valid\"*\n\n*A1*: One of your parameters may not be in the correct format.\n\nCheck recvWindow is an integer and not a string.\n\n*A2*: You may need to regenerate your API Key and Secret\n\n*A3*: You may be attempting to access the API from a Chinese IP address, these are now restricted by Binance.\n\n*Q: How can I debug API issues?*\n\n*A*: Enable verbose mode to see detailed request and response information:\n\n.. code:: python\n\n    client = Client(api_key, api_secret, verbose=True)\n\nThis will log all HTTP requests and responses, including headers, body, and status codes. This is particularly helpful for debugging authentication issues, understanding API behavior, and troubleshooting network problems.\n\nSee the Logging section in the `Getting Started guide <overview.html#verbose-mode>`_ for more details.\n"
  },
  {
    "path": "docs/general.rst",
    "content": "General Endpoints\n=================\n\n`Ping the server <binance.html#binance.client.Client.ping>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    client.ping()\n\n`Get the server time <binance.html#binance.client.Client.get_server_time>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    time_res = client.get_server_time()\n\n`Get system status <binance.html#binance.client.Client.get_system_status>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    status = client.get_system_status()\n\nReturns\n\n.. code-block:: python\n\n    {\n        \"status\": 0,        # 0: normal，1：system maintenance\n        \"msg\": \"normal\"     # normal or System maintenance.\n    }\n\n`Get Exchange Info <binance.html#binance.client.Client.get_exchange_info>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    info = client.get_exchange_info()\n\n`Get Symbol Info <binance.html#binance.client.Client.get_symbol_info>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nGet the exchange info for a particular symbol\n\n.. code:: python\n\n    info = client.get_symbol_info('BNBBTC')\n\n`Get All Coins Info <binance.html#binance.client.Client.get_all_tickers>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nGet information of coins (available for deposit and withdraw) for user\n\n.. code:: python\n\n    info = client.get_all_tickers()\n\n`Get Get Daily Account Snapshot <binance.html#binance.client.Client.get_account_snapshot>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nGet daily account snapshot of specific type. Valid types: SPOT/MARGIN/FUTURES.\n\n.. code:: python\n\n    info = client.get_account_snapshot(type='SPOT')\n\n`Get Current Products <binance.html#binance.client.Client.get_products>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nThis call is deprecated, use the above Exchange Info call\n\n.. code:: python\n\n    products = client.get_products()\n"
  },
  {
    "path": "docs/helpers.rst",
    "content": "Helper Functions\n================\n\n.. autoclass:: binance.helpers\n    :members: date_to_milliseconds, interval_to_milliseconds, round_step_size\n    :noindex:\n"
  },
  {
    "path": "docs/index.rst",
    "content": ".. python-binance documentation master file, created by\n   sphinx-quickstart on Thu Sep 21 20:24:54 2017.\n\n.. include:: ../README.rst\n\nContents\n========\n\n.. toctree::\n   :maxdepth: 2\n\n   overview\n   constants\n   general\n   market_data\n   account\n   sub_accounts\n   margin\n   websockets\n   depth_cache\n   withdraw\n   helpers\n   exceptions\n   faqs\n   changelog\n\n   binance\n\nIndex\n==================\n\n* :ref:`genindex`\n"
  },
  {
    "path": "docs/margin.rst",
    "content": "Margin Trading Endpoints\n========================\n\n.. note ::  \n\n    **Cross-margin vs isolated margin trading**\n\n    Binance offers both *cross-margin* trading (where all margin is in one account) and *isolated margin* trading (where each pair is a separate margin account).  Make sure you are interacting with the right one.\n\n    Some of the API endpoints apply to the cross-margin or isolated margin accounts only.  Other endpoints, such as the trade execution endpoints, are used for the cross-margin account trades by default, but you can use your isolated margin accounts by using the ``isIsolated`` or ``isolatedSymbol`` parameters.  See the documentation below.\n\nMarket Data\n-----------\n\n`Get cross-margin asset info <binance.html#binance.client.Client.get_margin_asset>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    info = client.get_margin_asset(asset='BNB')\n\n`Get cross-margin symbol info <binance.html#binance.client.Client.get_margin_symbol>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    info = client.get_margin_symbol(symbol='BTCUSDT')\n\n`Get isolated margin symbol info <binance.html#binance.client.Client.get_isolated_margin_symbol>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    info = client.get_isolated_margin_symbol(symbol='BTCUSDT')\n\n`Get all isolated margin symbols <binance.html#binance.client.Client.get_all_isolated_margin_symbols>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    info = client.get_all_isolated_margin_symbols()\n\n`Get margin price index <binance.html#binance.client.Client.get_margin_price_index>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    info = client.get_margin_price_index(symbol='BTCUSDT')\n\nOrders\n------\n\nCross-margin vs isolated margin orders\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nBy default, these trade execution endpoints will create an order using the *cross-margin* account. \n\nTo use the *isolated margin* account for the ``symbol`` you have specified, simply add the ``isIsolated='TRUE'`` parameter to the API calls below in this 'Orders' section.\n\nOrder Validation\n^^^^^^^^^^^^^^^^\n\nBinance has a number of rules around symbol pair orders with validation on minimum price, quantity and total order value.\n\nRead more about their specifics in the `Filters <https://binance-docs.github.io/apidocs/spot/en/#filters>`_\nsection of the official API.\n\nIt can be helpful to format the output using the following snippet\n\n.. code:: python\n\n    amount = 0.000234234\n    precision = 5\n    amt_str = \"{:0.0{}f}\".format(amount, precision)\n\n\n`Fetch all margin_orders <binance.html#binance.client.Client.get_all_margin_orders>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    orders = client.get_all_margin_orders(symbol='BNBBTC', limit=10)\n\n\n`Place a margin order <binance.html#binance.client.Client.create_margin_order>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nUse the `create_margin_order` function to have full control over creating an order\n\n.. code:: python\n\n    from binance.enums import *\n    order = client.create_margin_order(\n        symbol='BNBBTC',\n        side=SIDE_BUY,\n        type=ORDER_TYPE_LIMIT,\n        timeInForce=TIME_IN_FORCE_GTC,\n        quantity=100,\n        price='0.00001')\n\n\n`Check order status <binance.html#binance.client.Client.get_margin_order>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    order = client.get_margin_order(\n        symbol='BNBBTC',\n        orderId='orderId')\n\n\n`Cancel a margin order <binance.html#binance.client.Client.cancel_margin_order>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    result = client.cancel_margin_order(\n        symbol='BNBBTC',\n        orderId='orderId')\n\n\n`Get all open margin orders <binance.html#binance.client.Client.get_open_margin_orders>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    orders = client.get_open_margin_orders(symbol='BNBBTC')\n\nFor isolated margin, add the ``isIsolated='TRUE'`` parameter.\n\n`Get all margin orders <binance.html#binance.client.Client.get_all_margin_orders>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    orders = client.get_all_margin_orders(symbol='BNBBTC')\n\nFor isolated margin, add the ``isIsolated='TRUE'`` parameter.\n\nAccount\n-------\n\n`Get cross-margin account info <binance.html#binance.client.Client.get_margin_account>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    info = client.get_margin_account()\n\n`Create isolated margin account <binance.html#binance.client.Client.create_isolated_margin_account>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    account = client.create_isolated_margin_account(base='BTC', quote='ETH')\n\n`Get isolated margin account info <binance.html#binance.client.Client.get_isolated_margin_account>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    info = client.get_isolated_margin_account()\n\n`Transfer spot to cross-margin account <binance.html#binance.client.Client.transfer_spot_to_margin>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    transaction = client.transfer_spot_to_margin(asset='BTC', amount='1.1')\n\n`Transfer cross-margin account to spot <binance.html#binance.client.Client.transfer_margin_to_spot>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    transaction = client.transfer_margin_to_spot(asset='BTC', amount='1.1')\n\n`Transfer spot to isolated margin account <binance.html#binance.client.Client.transfer_spot_to_isolated_margin>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    transaction = client.transfer_spot_to_isolated_margin(asset='BTC', \n                                                            symbol='ETHBTC', amount='1.1')\n\n`Transfer isolated margin account to spot <binance.html#binance.client.Client.transfer_isolated_margin_to_spot>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    transaction = client.transfer_isolated_margin_to_spot(asset='BTC', \n                                                            symbol='ETHBTC', amount='1.1')\n\n`Get max transfer amount <binance.html#binance.client.Client.get_max_margin_transfer>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    details = client.get_max_margin_transfer(asset='BTC')\n\nThis max transfer is for the cross-margin account by default.  For isolated margin records, add the ``isolatedSymbol=symbol_name`` parameter.\n\nTrades\n-----\n\n`Get all margin trades <binance.html#binance.client.Client.get_margin_trades>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    trades = client.get_margin_trades(symbol='BNBBTC')\n\nFor isolated margin trades, add the ``isIsolated='TRUE'`` parameter.\n\n\nLoans\n-----\n\n`Create loan <binance.html#binance.client.Client.create_margin_loan>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    transaction = client.create_margin_loan(asset='BTC', amount='1.1')\n\nThis for the cross-margin account by default.  For isolated margin, add the ``isIsolated='TRUE'`` and the ``symbol=symbol_name`` parameters.\n\n`Repay loan <binance.html#binance.client.Client.repay_margin_loan>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    transaction = client.repay_margin_loan(asset='BTC', amount='1.1')\n\nThis for the cross-margin account by default.  For isolated margin, add the ``isIsolated='TRUE'`` and the ``symbol=symbol_name`` parameters.\n\n`Get loan details <binance.html#binance.client.Client.get_margin_loan_details>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    details = client.get_margin_loan_details(asset='BTC', txId='100001')\n\nThis for the cross-margin account by default.  For isolated margin records, add the ``isolatedSymbol=symbol_name`` parameter.\n\n`Get repay details <binance.html#binance.client.Client.get_margin_repay_details>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    details = client.get_margin_repay_details(asset='BTC', txId='100001')\n\nThis for the cross-margin account by default.  For isolated margin records, add the ``isolatedSymbol=symbol_name`` parameter.\n\n`Get max loan amount <binance.html#binance.client.Client.get_max_margin_loan>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    details = client.get_max_margin_loan(asset='BTC')\n\nThe max loan is for the cross-margin account by default.  For isolated margin records, add the ``isolatedSymbol=symbol_name`` parameter.\n"
  },
  {
    "path": "docs/market_data.rst",
    "content": "Market Data Endpoints\n=====================\n\n\n`Get Market Depth <binance.html#binance.client.Client.get_order_book>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    depth = client.get_order_book(symbol='BNBBTC')\n\n`Get Recent Trades <binance.html#binance.client.Client.get_recent_trades>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    trades = client.get_recent_trades(symbol='BNBBTC')\n\n`Get Historical Trades <binance.html#binance.client.Client.get_historical_trades>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    trades = client.get_historical_trades(symbol='BNBBTC')\n\n`Get Aggregate Trades <binance.html#binance.client.Client.get_aggregate_trades>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    trades = client.get_aggregate_trades(symbol='BNBBTC')\n\n`Aggregate Trade Iterator <binance.html#binance.client.Client.aggregate_trade_iter>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nIterate over aggregate trades for a symbol from a given date or a given order id.\n\n.. code:: python\n\n    agg_trades = client.aggregate_trade_iter(symbol='ETHBTC', start_str='30 minutes ago UTC')\n\n    # iterate over the trade iterator\n    for trade in agg_trades:\n        print(trade)\n        # do something with the trade data\n\n    # convert the iterator to a list\n    # note: generators can only be iterated over once so we need to call it again\n    agg_trades = client.aggregate_trade_iter(symbol='ETHBTC', '30 minutes ago UTC')\n    agg_trade_list = list(agg_trades)\n\n    # example using last_id value\n    agg_trades = client.aggregate_trade_iter(symbol='ETHBTC', last_id=23380478)\n    agg_trade_list = list(agg_trades)\n\n\n`Get Kline/Candlesticks <binance.html#binance.client.Client.get_klines>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    candles = client.get_klines(symbol='BNBBTC', interval=Client.KLINE_INTERVAL_30MINUTE)\n\n`Get Historical Kline/Candlesticks <binance.html#binance.client.Client.get_historical_klines>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nFetch klines for any date range and interval\n\n.. code:: python\n\n    # fetch 1 minute klines for the last day up until now\n    klines = client.get_historical_klines(\"BNBBTC\", Client.KLINE_INTERVAL_1MINUTE, \"1 day ago UTC\")\n\n    # fetch 30 minute klines for the last month of 2017\n    klines = client.get_historical_klines(\"ETHBTC\", Client.KLINE_INTERVAL_30MINUTE, \"1 Dec, 2017\", \"1 Jan, 2018\")\n\n    # fetch weekly klines since it listed\n    klines = client.get_historical_klines(\"NEOBTC\", Client.KLINE_INTERVAL_1WEEK, \"1 Jan, 2017\")\n\n\n`Get Historical Kline/Candlesticks using a generator <binance.html#binance.client.Client.get_historical_klines_generator>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nFetch klines using a generator\n\n.. code:: python\n\n    for kline in client.get_historical_klines_generator(\"BNBBTC\", Client.KLINE_INTERVAL_1MINUTE, \"1 day ago UTC\"):\n        print(kline)\n        # do something with the kline\n\n`Get average price for a symbol <binance.html#binance.client.Client.get_avg_price>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    avg_price = client.get_avg_price(symbol='BNBBTC')\n\n`Get 24hr Ticker <binance.html#binance.client.Client.get_ticker>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    tickers = client.get_ticker()\n\n`Get All Prices <binance.html#binance.client.Client.get_all_tickers>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nGet last price for all markets.\n\n.. code:: python\n\n    prices = client.get_all_tickers()\n\n`Get Orderbook Tickers <binance.html#binance.client.Client.get_orderbook_tickers>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nGet first bid and ask entry in the order book for all markets.\n\n.. code:: python\n\n    tickers = client.get_orderbook_tickers()\n"
  },
  {
    "path": "docs/overview.rst",
    "content": "Getting Started\n===============\n\nInstallation\n------------\n\n``python-binance`` is available on `PYPI <https://pypi.python.org/pypi/python-binance/>`_.\nInstall with ``pip``:\n\n.. code:: bash\n\n    pip install python-binance\n\nRegister on Binance\n-------------------\n\nFirstly `register an account with Binance <https://accounts.binance.com/en/register?ref=10099792>`_.\n\nGenerate an API Key\n-------------------\n\nTo use signed account methods you are required to `create an API Key  <https://www.binance.com/en/support/faq/360002502072>`_.\n\nInitialise the client\n---------------------\n\nPass your API Key and Secret\n\n.. code:: python\n\n    from binance.client import Client\n    client = Client(api_key, api_secret)\n\nor for Asynchronous client\n\n.. code:: python\n\n    async def main():\n\n        # initialise the client\n        client = await AsyncClient.create(api_key, api_secret)\n\n    if __name__ == \"__main__\":\n\n        loop = asyncio.get_event_loop()\n        loop.run_until_complete(main())\n\nUsing the Spot, Futures or Vanilla Options Testnet\n--------------------------------------------------\n\nBinance offers a `Spot <https://testnet.binance.vision/>`_,\n`Futures <https://testnet.binancefuture.com/>`_\nand `Vanilla Options <https://testnet.binanceops.com/>`_ Testnet,\nto test interacting with the exchange.\n\nTo enable this set the `testnet` parameter passed to the Client to True.\n\nThe testnet parameter will also be used by any websocket streams when the client is passed to the BinanceSocketManager.\n\n.. code:: python\n\n    client = Client(api_key, api_secret, testnet=True)\n\nor for Asynchronous client\n\n.. code:: python\n\n    client = await AsyncClient.create(api_key, api_secret, testnet=True)\n\nUsing a different TLD\n---------------------\n\nIf you are interacting with a regional version of Binance which has a different TLD such as `.us` or `.jp' then you\nwill need to pass this when creating the client, see examples below.\n\nThis tld will also be used by any websocket streams when the client is passed to the BinanceSocketManager.\n\n.. code:: python\n\n    client = Client(api_key, api_secret, tld='us')\n\nor for Asynchronous client\n\n.. code:: python\n\n    client = await AsyncClient.create(api_key, api_secret, tld='us')\n\n\nMaking API Calls\n----------------\n\nEvery method supports the passing of arbitrary parameters via keyword matching those in the `Binance API documentation <https://github.com/binance-exchange/binance-official-api-docs>`_.\nThese keyword arguments will be sent directly to the relevant endpoint.\n\nEach API method returns a dictionary of the JSON response as per the `Binance API documentation <https://github.com/binance-exchange/binance-official-api-docs>`_.\nThe docstring of each method in the code references the endpoint it implements.\n\nThe Binance API documentation references a `timestamp` parameter, this is generated for you where required.\n\nSome methods have a `recvWindow` parameter for `timing security, see Binance documentation <https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#timing-security>`_.\n\nAPI Endpoints are rate limited by Binance at 20 requests per second, ask them if you require more.\n\nAsync API Calls\n---------------\n\naiohttp is used to handle asyncio REST requests.\n\nEach function available in the normal client is available in the AsyncClient class.\n\nThe only difference is to run within an asyncio event loop and await the function like below.\n\n.. code:: python\n\n    import asyncio\n    from binance import AsyncClient\n\n    async def main():\n        client = await AsyncClient.create()\n\n        # fetch exchange info\n        res = await client.get_exchange_info()\n        print(json.dumps(res, indent=2))\n\n        await client.close_connection()\n\n    if __name__ == \"__main__\":\n\n        loop = asyncio.get_event_loop()\n        loop.run_until_complete(main())\n\nRead `Async basics for Binance <https://sammchardy.github.io/binance/2021/05/01/async-binance-basics.html>`_\nfor more information about asynchronous patterns.\n\nAPI Rate Limit\n--------------\n\nCheck the `get_exchange_info() <binance.html#binance.client.Client.get_exchange_info>`_ call for up to date rate limits.\n\nAt the current time Binance rate limits are:\n\n- 1200 weights per minute\n- 10 orders per second\n- 100,000 orders per 24hrs\n\nSome calls have a higher weight than others especially if a call returns information about all symbols.\nRead the `official Binance documentation <https://github.com/binance-exchange/binance-official-api-docs>`_ for specific information.\n\nOn each request Binance returns `X-MBX-USED-WEIGHT-(intervalNum)(intervalLetter)` and `X-MBX-ORDER-COUNT-(intervalNum)`\nheaders.\n\nHere are examples to access these\n\nAsynchronous example\n\n.. code:: python\n\n    import asyncio\n    from binance import AsyncClient\n\n    api_key = '<api_key>'\n    api_secret = '<api_secret>'\n\n    async def main():\n        client = await AsyncClient.create(api_key, api_secret)\n\n        res = await client.get_exchange_info()\n        print(client.response.headers)\n\n        await client.close_connection()\n\n    if __name__ == \"__main__\":\n\n        loop = asyncio.get_event_loop()\n        loop.run_until_complete(main())\n\nSynchronous example\n\n\n.. code:: python\n\n    from binance import Client\n\n    api_key = '<api_key>'\n    api_secret = '<api_secret>'\n\n    def main():\n        client = Client(api_key, api_secret)\n\n        res = client.get_exchange_info()\n        print(client.response.headers)\n\n    if __name__ == \"__main__\":\n        main()\nRequests Settings\n-----------------\n\n`python-binance` uses the `requests <http://docs.python-requests.org/en/master/>`_ library.\n\nYou can set custom requests parameters for all API calls when creating the client.\n\n.. code:: python\n\n    client = Client(\"api-key\", \"api-secret\", {\"verify\": False, \"timeout\": 20})\n\nYou may also pass custom requests parameters through any API call to override default settings or the above settings specify new ones like the example below.\n\n.. code:: python\n\n    # this would result in verify: False and timeout: 5 for the get_all_orders call\n    client = Client(\"api-key\", \"api-secret\", {\"verify\": False, \"timeout\": 20})\n    client.get_all_orders(symbol='BNBBTC', requests_params={'timeout': 5})\n\nCheck out the `requests documentation <http://docs.python-requests.org/en/master/>`_ for all options.\n\n**Proxy Settings**\n\nYou can use the Requests Settings method above. For websockets python 3.8+ is required\n\n.. code:: python\n\n    proxies = {\n        'http': 'http://10.10.1.10:3128',\n        'https': 'http://10.10.1.10:1080'\n    }\n\n    # in the Client instantiation\n    client = Client(\"api-key\", \"api-secret\", {'proxies': proxies})\n\n    # or on an individual call\n    client.get_all_orders(symbol='BNBBTC', requests_params={'proxies': proxies})\n\nOr set an environment variable for your proxy if required to work across all requests.\n\nAn example for Linux environments from the `requests Proxies documentation <http://docs.python-requests.org/en/master/user/advanced/#proxies>`_ is as follows.\n\n.. code-block:: bash\n\n    $ export HTTP_PROXY=\"http://10.10.1.10:3128\"\n    $ export HTTPS_PROXY=\"http://10.10.1.10:1080\"\n\nFor Windows environments\n\n.. code-block:: bash\n\n    C:\\>set HTTP_PROXY=http://10.10.1.10:3128\n    C:\\>set HTTPS_PROXY=http://10.10.1.10:1080\n\nLogging\n-------\n\npython-binance uses the Python logging module. You can enable logging to help debug issues and monitor your application.\n\nBasic Logging Setup\n~~~~~~~~~~~~~~~~~~\n\nTo enable debug logging, add this at the start of your script:\n\n.. code:: python\n\n    import logging\n    logging.basicConfig(level=logging.DEBUG)\n\nAdvanced Logging Setup\n~~~~~~~~~~~~~~~~~~~~~\n\nFor more detailed logging with timestamps and log levels:\n\n.. code:: python\n\n    import logging\n\n    # Configure logging\n    logging.basicConfig(\n        level=logging.DEBUG,\n        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n    )\n\nVerbose Mode\n~~~~~~~~~~~~\n\nVerbose mode provides detailed logging of all HTTP requests and responses, which is particularly useful for debugging API issues, understanding request/response formats, and troubleshooting authentication or network problems.\n\nMethod 1: Using the verbose Parameter (Recommended for Quick Debugging)\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nEnable verbose mode by passing ``verbose=True`` when creating the client:\n\n.. code:: python\n\n    from binance.client import Client\n    import logging\n\n    # Configure logging (optional - for seeing the output)\n    logging.basicConfig(level=logging.DEBUG)\n\n    # Enable verbose mode\n    client = Client(api_key, api_secret, verbose=True)\n\n    # All API calls will now log detailed information\n    server_time = client.get_server_time()\n\nFor AsyncClient:\n\n.. code:: python\n\n    import asyncio\n    import logging\n    from binance.async_client import AsyncClient\n\n    logging.basicConfig(level=logging.DEBUG)\n\n    async def main():\n        # Enable verbose mode\n        client = await AsyncClient.create(api_key, api_secret, verbose=True)\n\n        # All API calls will now log detailed information\n        server_time = await client.get_server_time()\n\n        await client.close_connection()\n\n    if __name__ == \"__main__\":\n        asyncio.run(main())\n\nMethod 2: Using Python's Logging Module (Recommended for Production)\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nFor more control over logging configuration, use Python's standard logging module:\n\n.. code:: python\n\n    import logging\n    from binance.client import Client\n\n    # Configure logging for binance module\n    logging.basicConfig(\n        level=logging.INFO,  # Set root level\n        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'\n    )\n\n    # Enable debug logging for binance specifically\n    logging.getLogger('binance.base_client').setLevel(logging.DEBUG)\n\n    # Create client (verbose parameter not needed)\n    client = Client(api_key, api_secret)\n\nThis approach gives you fine-grained control and integrates with your application's existing logging infrastructure.\n\nWhat Gets Logged\n^^^^^^^^^^^^^^^^\n\nWhen verbose mode is enabled, you'll see detailed logs for each request including:\n\n- HTTP method and URL\n- Request headers and body\n- Response status code\n- Response headers and body (truncated to 1000 characters)\n\nExample output:\n\n.. code-block:: text\n\n    2025-11-30 22:01:26,957 - binance.base_client - DEBUG -\n    Request: GET https://api.binance.com/api/v3/time\n    RequestHeaders: {'Accept': 'application/json', 'Content-Type': 'application/json'}\n    RequestBody: None\n    Response: 200\n    ResponseHeaders: {'Content-Type': 'application/json;charset=UTF-8', ...}\n    ResponseBody: {\"serverTime\":1764536487218}\n\n**Note:** Verbose mode should typically be disabled in production environments to minimize overhead and log volume. Use the logging module approach for production with appropriate log levels.\n\nWebSocket Verbose Logging\n^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nWebSocket connections support verbose mode just like REST API calls.\n\nMethod 1: Using the verbose Parameter (Recommended for Quick Debugging)\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\n.. code:: python\n\n    import logging\n    from binance import AsyncClient, BinanceSocketManager\n\n    # Configure logging to see output\n    logging.basicConfig(level=logging.DEBUG)\n\n    async def main():\n        client = await AsyncClient.create()\n\n        # Enable verbose mode for WebSocket connections\n        bm = BinanceSocketManager(client, verbose=True)\n\n        # WebSocket messages will be logged at DEBUG level\n        ts = bm.trade_socket('BTCUSDT')\n        async with ts as tscm:\n            msg = await tscm.recv()\n            print(msg)\n\n        await client.close_connection()\n\nMethod 2: Using Python's Logging Module (Recommended for Production)\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\n.. code:: python\n\n    import logging\n    from binance import AsyncClient, BinanceSocketManager\n\n    # Configure logging\n    logging.basicConfig(level=logging.DEBUG)\n\n    # Enable debug logging for all WebSocket connections\n    logging.getLogger('binance.ws').setLevel(logging.DEBUG)\n\n    async def main():\n        client = await AsyncClient.create()\n        bm = BinanceSocketManager(client)\n\n        # WebSocket messages will be logged at DEBUG level\n        ts = bm.trade_socket('BTCUSDT')\n        async with ts as tscm:\n            msg = await tscm.recv()\n            print(msg)\n\n        await client.close_connection()\n\nYou can also enable logging for specific WebSocket components:\n\n.. code:: python\n\n    # Log only WebSocket API messages\n    logging.getLogger('binance.ws.websocket_api').setLevel(logging.DEBUG)\n\n    # Log reconnection events\n    logging.getLogger('binance.ws.reconnecting_websocket').setLevel(logging.DEBUG)\n\n    # Log stream events\n    logging.getLogger('binance.ws.streams').setLevel(logging.DEBUG)\n\nWebSocket debug logs include:\n\n- Raw received messages\n- Connection state changes\n- Reconnection attempts\n- Subscription events\n- Error messages\n\n**Tip:** For comprehensive debugging, enable verbose mode for both REST API and WebSocket connections:\n\n.. code:: python\n\n    import logging\n    from binance import AsyncClient, BinanceSocketManager\n\n    logging.basicConfig(level=logging.DEBUG)\n\n    # Enable verbose for both REST API and WebSocket\n    client = await AsyncClient.create(verbose=True)\n    bm = BinanceSocketManager(client, verbose=True)\n\nFor Threaded WebSocket Manager:\n\n.. code:: python\n\n    import logging\n    from binance.ws.threaded_stream import ThreadedApiManager\n\n    logging.basicConfig(level=logging.DEBUG)\n\n    # Enable verbose mode for threaded WebSocket manager\n    twm = ThreadedApiManager(api_key='your_key', api_secret='your_secret', verbose=True)\n    twm.start()\n\n.. image:: https://analytics-pixel.appspot.com/UA-111417213-1/github/python-binance/docs/overview?pixel\n"
  },
  {
    "path": "docs/requirements.txt",
    "content": "sphinx==8.1.3\nsphinx_rtd_theme==3.0.1\nsphinx-copybutton>=0.5.0\n"
  },
  {
    "path": "docs/sub_accounts.rst",
    "content": "Sub Account Endpoints\n=====================\n\n\n`Get Sub Account list <binance.html#binance.client.Client.get_sub_account_list>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    accounts = client.get_sub_account_list()\n\n`Get Sub Account Transfer History <binance.html#binance.client.Client.get_sub_account_transfer_history>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    history = client.get_sub_account_transfer_history(fromEmail='blah@gmail.com', toEmail='foo@gmail.com')\n\n`Get Sub Account Assets <binance.html#binance.client.Client.get_sub_account_assets>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    assets = client.get_sub_account_assets(email='blah@gmail.com')\n"
  },
  {
    "path": "docs/websockets.rst",
    "content": "Websockets\n==========\n\nAPI Requests via Websockets\n--------------------------\n\nSome API endpoints can be accessed via websockets. For supported endpoints, you can make requests using either the synchronous or asynchronous client:\n\n* Synchronous client: ``client.ws_<endpoint_name>``\n* Asynchronous client: ``async_client.ws_<endpoint_name>``\n\nExample usage:\n\n.. code:: python\n\n    # Synchronous\n    client.ws_get_order_book(symbol=\"BTCUSDT\")\n\n    # Asynchronous\n    await async_client.ws_get_order_book(symbol=\"BTCUSDT\")\n\nWebsocket Managers for Streaming Data\n-----------------\n\nThere are 2 ways to interact with websockets for streaming data:\n\nwith `ThreadedWebsocketManager <binance.html#binance.websockets.ThreadedWebsocketManager>`_ or `BinanceSocketManager <binance.html#binance.websockets.BinanceSocketManager>`_.\n\nThreadedWebsocketManager does not require asyncio programming, while BinanceSocketManager does.\n\nThreadedWebsocketManager function begin with `start_`, e.g `start_ticker_socket` while BinanceSocketManager is simply `ticker_socket`.\n\nMultiple socket connections can be made through either manager.\n\nOnly one instance of each socket type will be created, i.e. only one BNBBTC Depth socket can be created\nand there can be both a BNBBTC Depth and a BNBBTC Trade socket open at once.\n\nMessages are received as dictionary objects relating to the message formats defined in the `Binance WebSocket API documentation <https://binance-docs.github.io/apidocs/spot/en/#websocket-market-streams>`_.\n\nWebsockets are setup to reconnect with a maximum of 5 retries with an exponential backoff strategy.\n\nThreadedWebsocketManager Websocket Usage\n----------------------------------------\n\nStarting sockets on the ThreadedWebsocketManager requires a callback parameter, similar to the old implementations of websockets on python-binance.\n\nThreadedWebsocketManager takes similar parameters to the `Client <binance.html#binance.client.Client>`_ class as it\ncreates an AsyncClient internally.\n\nFor authenticated streams `api_key` and `api_stream` are required.\n\nAs these use threads `start()` is required to be called before starting any sockets.\n\nTo keep the ThreadedWebsocketManager running, use `join()` to join it to the main thread.\n\n.. code:: python\n\n    import time\n\n    from binance import ThreadedWebsocketManager\n\n    api_key = '<api_key>'\n    api_secret = '<api_secret>'\n\n    def main():\n\n        symbol = 'BNBBTC'\n\n        twm = ThreadedWebsocketManager(api_key=api_key, api_secret=api_secret)\n        # start is required to initialise its internal loop\n        twm.start()\n\n        def handle_socket_message(msg):\n            print(f\"message type: {msg['e']}\")\n            print(msg)\n\n        twm.start_kline_socket(callback=handle_socket_message, symbol=symbol)\n\n        # multiple sockets can be started\n        twm.start_depth_socket(callback=handle_socket_message, symbol=symbol)\n\n        # or a multiplex socket can be started like this\n        # see Binance docs for stream names\n        streams = ['bnbbtc@miniTicker', 'bnbbtc@bookTicker']\n        twm.start_multiplex_socket(callback=handle_socket_message, streams=streams)\n\n        twm.join()\n\n\n    if __name__ == \"__main__\":\n       main()\n\n**Stop Individual Stream**\n\nWhen starting a stream, a name for that stream will be returned. This can be used to stop that individual stream.\n\n.. code:: python\n\n    from binance import ThreadedWebsocketManager\n\n    symbol = 'BNBBTC'\n\n    twm = ThreadedWebsocketManager()\n    # start is required to initialise its internal loop\n    twm.start()\n\n    def handle_socket_message(msg):\n        print(f\"message type: {msg['e']}\")\n        print(msg)\n\n        twm.start_kline_socket(callback=handle_socket_message, symbol=symbol)\n    depth_stream_name = twm.start_depth_socket(callback=handle_socket_message, symbol=symbol)\n\n    # some time later\n\n    twm.stop_socket(depth_stream_name)\n\n**Stop All Streams**\n\n.. code:: python\n\n    from binance import ThreadedWebsocketManager\n\n    twm = ThreadedWebsocketManager()\n    # start is required to initialise its internal loop\n    twm.start()\n\n    def handle_socket_message(msg):\n        print(f\"message type: {msg['e']}\")\n        print(msg)\n\n    depth_stream_name = twm.start_depth_socket(callback=handle_socket_message, symbol=symbol)\n\n    twm.stop()\n\nAttempting to start a stream after `stop` is called will not work.\n\n\nBinanceSocketManager Websocket Usage\n------------------------------------\n\nCreate the manager like so, passing an AsyncClient.\n\n.. code:: python\n\n    import asyncio\n    from binance import AsyncClient, BinanceSocketManager\n\n\n    async def main():\n        client = await AsyncClient.create()\n        bm = BinanceSocketManager(client)\n        # start any sockets here, i.e a trade socket\n        ts = bm.trade_socket('BNBBTC')\n        # then start receiving messages\n        async with ts as tscm:\n            while True:\n                res = await tscm.recv()\n                print(res)\n\n        await client.close_connection()\n\n    if __name__ == \"__main__\":\n\n        loop = asyncio.get_event_loop()\n        loop.run_until_complete(main())\n\nSet a custom timeout for the websocket connections\n\n.. code:: python\n\n    # set a timeout of 60 seconds\n    bm = BinanceSocketManager(client, user_timeout=60)\n\nManually enter and exit the Asynchronous context manager\n\n.. code:: python\n\n    ts = bm.trade_socket('BNBBTC')\n    # enter the context manager\n    await ts.__aenter__()\n    # receive a message\n    msg = await ts.recv()\n    print(msg)\n    # exit the context manager\n    await ts.__aexit__(None, None, None)\n\n\nUsing a different TLD\n---------------------\n\nThe ThreadedWebsocketManager can take the tld when created if required.\n\n.. code:: python\n\n    from binance.streams import ThreadedWebsocketManager\n\n    twm = ThreadedWebsocketManager(tld='us')\n\nThe BinanceSocketManager uses the same tld value as the AsyncClient that is passed in. To use the 'us' tld we\ncan do this.\n\n.. code:: python\n\n    from binance import AsyncClient, BinanceSocketManager\n\n    async def x():\n        client = await AsyncClient.create(tld='us')\n        bm = BinanceSocketManager(client)\n\n        # start a socket...\n\n        await client.close_connection()\n\n\nWebsocket Errors\n----------------\n\nIf an error occurs, a message is sent to the callback to indicate this. The format is:\n\n.. code:: python\n\n    {\n        'e': 'error',\n        'type': '<ErrorType>',\n        'm': '<Error message>'\n    }\n\nWhere:\n- `'e'`: Always `'error'` for error messages.\n- `'type'`: The type of error encountered (see table below).\n- `'m'`: A human-readable error message.\n\n**Possible Error Types:**\n\n+-------------------------------+--------------------------------------------------------------+-------------------------------+\n| Type                          | Description                                                  | Typical Action                |\n+===============================+==============================================================+===============================+\n| BinanceWebsocketUnableToConnect| The websocket could not connect after maximum retries.        | Check network, restart socket |\n+-------------------------------+--------------------------------------------------------------+-------------------------------+\n| BinanceWebsocketClosed         | The websocket connection was closed. The system will attempt | Usually auto-reconnects       |\n|                               | to reconnect automatically.                                  |                               |\n+-------------------------------+--------------------------------------------------------------+-------------------------------+\n| BinanceWebsocketQueueOverflow  | The internal message queue exceeded its maximum size         | Process messages faster, or   |\n|                               | (default 100).                                               | increase queue size           |\n+-------------------------------+--------------------------------------------------------------+-------------------------------+\n| CancelledError                 | The websocket task was cancelled (e.g., on shutdown).        | Usually safe to ignore        |\n+-------------------------------+--------------------------------------------------------------+-------------------------------+\n| IncompleteReadError            | The websocket connection was interrupted during a read.      | Will attempt to reconnect     |\n+-------------------------------+--------------------------------------------------------------+-------------------------------+\n| gaierror                       | Network address-related error (e.g., DNS failure).           | Check network                 |\n+-------------------------------+--------------------------------------------------------------+-------------------------------+\n| ConnectionClosedError          | The websocket connection was closed unexpectedly.            | Will attempt to reconnect     |\n+-------------------------------+--------------------------------------------------------------+-------------------------------+\n| *Other Exception Types*        | Any other unexpected error.                                  | Check error message           |\n+-------------------------------+--------------------------------------------------------------+-------------------------------+\n\n**Example error handling in your callback:**\n\n.. code:: python\n\n    def process_message(msg):\n        if msg.get('e') == 'error':\n            print(f\"WebSocket error: {msg.get('type')} - {msg.get('m')}\")\n            # Optionally close and restart the socket, or handle as needed\n        else:\n            # process message normally\n\n**Notes:**\n- Most connection-related errors will trigger automatic reconnection attempts up to 5 times.\n- If the queue overflows, consider increasing `max_queue_size` or processing messages more quickly.\n- For persistent errors, check your network connection and API credentials.\n\nWebsocket Examples\n----------------\n\n`Multiplex Socket <binance.html#binance.websockets.BinanceSocketManager.multiplex_socket>`_\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\nCreate a socket combining multiple streams.\n\nThese streams can include the depth, kline, ticker and trade streams but not the user stream which requires extra authentication.\n\nSymbols in socket name must be lowercase i.e bnbbtc@aggTrade, neobtc@ticker\n\nSee the `Binance Websocket Streams API documentation <https://binance-docs.github.io/apidocs/spot/en/#websocket-market-streams>`_ for details on socket names.\n\n.. code:: python\n\n    # pass a list of stream names\n    ms = bm.multiplex_socket(['bnbbtc@aggTrade', 'neobtc@ticker'])\n\n`Depth Socket <binance.html#binance.websockets.BinanceSocketManager.depth_socket>`_\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\nDepth sockets have an optional depth parameter to receive partial book rather than a diff response.\nBy default this the diff response is returned.\nValid depth values are 5, 10 and 20 and `defined as enums <enums.html>`_.\n\n.. code:: python\n\n    # depth diff response\n    ds = bm.depth_socket('BNBBTC')\n\n    # partial book response\n    ds = bm.depth_socket('BNBBTC', depth=BinanceSocketManager.WEBSOCKET_DEPTH_5)\n\n\n`Kline Socket <binance.html#binance.websockets.BinanceSocketManager.kline_socket>`_\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\nKline sockets have an optional interval parameter. By default this is set to 1 minute.\nValid interval values are `defined as enums <enums.html>`_.\n\n.. code:: python\n\n    from binance.enums import *\n    ks = bm.kline_socket('BNBBTC', interval=KLINE_INTERVAL_30MINUTE)\n\n\n`Aggregated Trade Socket <binance.html#binance.websockets.BinanceSocketManager.aggtrade_socket>`_\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n.. code:: python\n\n    ats = bm.aggtrade_socket('BNBBTC')\n\n\n`Trade Socket <binance.html#binance.websockets.BinanceSocketManager.trade_socket>`_\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n.. code:: python\n\n    ts = bm.trade_socket('BNBBTC')\n\n`Symbol Ticker Socket <binance.html#binance.websockets.BinanceSocketManager.symbol_ticker_socket>`_\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n.. code:: python\n\n    sts = bm.symbol_ticker_socket('BNBBTC')\n\n`Ticker Socket <binance.html#binance.websockets.BinanceSocketManager.ticker_socket>`_\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n.. code:: python\n\n    ts = bm.ticker_socket(process_message)\n\n`Mini Ticker Socket <binance.html#binance.websockets.BinanceSocketManager.miniticker_socket>`_\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n\n.. code:: python\n\n    # by default updates every second\n    mts = bm.miniticker_socket()\n\n    # this socket can take an update interval parameter\n    # set as 5000 to receive updates every 5 seconds\n    mts = bm.miniticker_socket(5000)\n\nUser Socket\n+++++++++++\n\nThis watches for 3 different user events\n\n- Account Update Event\n- Order Update Event\n- Trade Update Event\n\nThe Manager handles keeping the socket alive.\n\nThere are separate sockets for Spot, Cross-margin and separate Isolated margin accounts.\n\n`Spot trading <binance.html#binance.websockets.BinanceSocketManager.user_socket>`_\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. code:: python\n\n    bm.user_socket()\n\n\n`Cross-margin <binance.html#binance.websockets.BinanceSocketManager.margin_socket>`_\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. code:: python\n\n    bm.margin_socket()\n\n\n`Isolated margin <binance.html#binance.websockets.BinanceSocketManager.isolated_margin_socket>`_\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. code:: python\n\n    bm.isolated_margin_socket(symbol)\n\n"
  },
  {
    "path": "docs/withdraw.rst",
    "content": "Withdraw Endpoints\n==================\n\n`Place a withdrawal <binance.html#binance.client.Client.withdraw>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nMake sure you enable Withdrawal permissions for your API Key to use this call.\n\nYou must have withdrawn to the address through the website and approved the withdrawal via email before you can withdraw using the API.\n\n.. code:: python\n\n    from binance.exceptions import BinanceAPIException\n    try:\n        # name parameter will be set to the asset value by the client if not passed\n        result = client.withdraw(\n            coin='ETH',\n            address='<eth_address>',\n            amount=100)\n    except BinanceAPIException as e:\n        print(e)\n    else:\n        print(\"Success\")\n\n    # passing a name parameter\n    result = client.withdraw(\n        coin='ETH',\n        address='<eth_address>',\n        amount=100,\n        name='Withdraw')\n\n    # if the coin requires a extra tag or name such as XRP or XMR then pass an `addressTag` parameter.\n    result = client.withdraw(\n        coin='XRP',\n        address='<xrp_address>',\n        addressTag='<xrp_address_tag>',\n        amount=10000)\n\n`Fetch deposit history <binance.html#binance.client.Client.get_deposit_history>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    deposits = client.get_deposit_history()\n    btc_deposits = client.get_deposit_history(coin='BTC')\n\n\n`Fetch withdraw history <binance.html#binance.client.Client.get_withdraw_history>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    withdraws = client.get_withdraw_history()\n    btc_withdraws = client.get_withdraw_history(coin='BTC')\n\n`Get deposit address <binance.html#binance.client.Client.get_deposit_address>`_\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n.. code:: python\n\n    address = client.get_deposit_address(coin='BTC')\n"
  },
  {
    "path": "examples/binace_socket_manager.py",
    "content": "import os\nimport sys\nimport asyncio\nimport time\n\nroot = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nsys.path.append(root)\n\nfrom binance import AsyncClient, BinanceSocketManager\n\n\nasync def main():\n    client = await AsyncClient.create()\n    bm = BinanceSocketManager(client)\n    # start any sockets here, i.e a trade socket\n    ts = bm.trade_socket(\"BTCUSDT\")\n    # then start receiving messages\n    async with ts as tscm:\n        start_time = time.time()\n        while time.time() - start_time < 30:\n            try:\n                res = await tscm.recv()\n                print(res)\n            except Exception as e:\n                print(f\"An error occurred: {e}\")\n                break\n\n    await client.close_connection()\n    print(\"WebSocket connection closed after 10 seconds.\")\n\n\nif __name__ == \"__main__\":\n    loop = asyncio.get_event_loop()\n    loop.run_until_complete(main())\n"
  },
  {
    "path": "examples/create_oco_order.py",
    "content": "import os\nimport sys\n\nroot = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nsys.path.append(root)\n\nfrom binance.client import Client\n\n\napi_key = \"\"  # your api_key here\nsecret = \"\"  # your secret here\nclient = Client(api_key, secret, testnet=True)\n\n\n# create oco order\ndef create_oco_order():\n    order = client.create_oco_order(\n        symbol=\"LTCUSDT\",\n        side=\"SELL\",\n        quantity=0.3,\n        aboveType=\"LIMIT_MAKER\",\n        belowType=\"STOP_LOSS\",\n        abovePrice=200,\n        belowStopPrice=120,\n    )\n    print(order)\n    # {\n    #     \"orderListId\": 9365,\n    #     \"contingencyType\": \"OCO\",\n    #     \"listStatusType\": \"EXEC_STARTED\",\n    #     \"listOrderStatus\": \"EXECUTING\",\n    #     \"listClientOrderId\": \"x-HNA2TXFJa9965a63237a3621d3f9df\",\n    #     \"transactionTime\": 1733229295138,\n    #     \"symbol\": \"LTCUSDT\",\n    #     \"orders\": [\n    #         {\n    #             \"symbol\": \"LTCUSDT\",\n    #             \"orderId\": 5836416,\n    #             \"clientOrderId\": \"MxXFhDAC8h13wH8X3rXNKG\",\n    #         },\n    #         {\n    #             \"symbol\": \"LTCUSDT\",\n    #             \"orderId\": 5836417,\n    #             \"clientOrderId\": \"a2UltweB2UB1XOdUTqOrzw\",\n    #         },\n    #     ],\n    #     \"orderReports\": [\n    #         {\n    #             \"symbol\": \"LTCUSDT\",\n    #             \"orderId\": 5836416,\n    #             \"orderListId\": 9365,\n    #             \"clientOrderId\": \"MxXFhDAC8h13wH8X3rXNKG\",\n    #             \"transactTime\": 1733229295138,\n    #             \"price\": \"0.00000000\",\n    #             \"origQty\": \"0.30000000\",\n    #             \"executedQty\": \"0.00000000\",\n    #             \"origQuoteOrderQty\": \"0.00000000\",\n    #             \"cummulativeQuoteQty\": \"0.00000000\",\n    #             \"status\": \"NEW\",\n    #             \"timeInForce\": \"GTC\",\n    #             \"type\": \"STOP_LOSS\",\n    #             \"side\": \"SELL\",\n    #             \"stopPrice\": \"120.00000000\",\n    #             \"workingTime\": -1,\n    #             \"selfTradePreventionMode\": \"EXPIRE_MAKER\",\n    #         },\n    #         {\n    #             \"symbol\": \"LTCUSDT\",\n    #             \"orderId\": 5836417,\n    #             \"orderListId\": 9365,\n    #             \"clientOrderId\": \"a2UltweB2UB1XOdUTqOrzw\",\n    #             \"transactTime\": 1733229295138,\n    #             \"price\": \"200.00000000\",\n    #             \"origQty\": \"0.30000000\",\n    #             \"executedQty\": \"0.00000000\",\n    #             \"origQuoteOrderQty\": \"0.00000000\",\n    #             \"cummulativeQuoteQty\": \"0.00000000\",\n    #             \"status\": \"NEW\",\n    #             \"timeInForce\": \"GTC\",\n    #             \"type\": \"LIMIT_MAKER\",\n    #             \"side\": \"SELL\",\n    #             \"workingTime\": 1733229295138,\n    #             \"selfTradePreventionMode\": \"EXPIRE_MAKER\",\n    #         },\n    #     ],\n    # }\n\n\ndef main():\n    create_oco_order()\n\nmain()\n"
  },
  {
    "path": "examples/create_order.py",
    "content": "import os\nimport sys\n\nroot = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nsys.path.append(root)\n\nfrom binance.client import Client\n\n\napi_key = \"\"  # your api_key here\nsecret = \"\"  # your secret here\nclient = Client(api_key, secret, testnet=True)\n\n\n# create futures order\ndef create_futures_order():\n    order = client.futures_create_order(\n        symbol=\"LTCUSDT\",\n        side=\"BUY\",\n        type=\"MARKET\",\n        quantity=0.1,\n        positionSide=\"LONG\",  # BOTH for One-way Mode ; LONG or SHORT for Hedge Mode\n    )\n    print(order)\n\n\ndef create_spot_order():\n    order = client.create_order(\n        symbol=\"LTCUSDT\", side=\"BUY\", type=\"LIMIT\", price=60, quantity=0.1\n    )\n    print(order)\n\n\ndef main():\n    create_futures_order()\n    create_spot_order()\n\n\nmain()\n"
  },
  {
    "path": "examples/create_order_async.py",
    "content": "import os\nimport sys\nimport asyncio\n\nroot = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nsys.path.append(root)\n\nfrom binance import AsyncClient\n\n\n# create futures order\nasync def main():\n    api_key = \"\"  # your api_key here\n    secret = \"\"  # your secret here\n    client = AsyncClient(api_key, secret, testnet=True)\n    order = await client.futures_create_order(\n        symbol=\"LTCUSDT\",\n        side=\"BUY\",\n        type=\"MARKET\",\n        quantity=0.1,\n        positionSide=\"LONG\",  # BOTH for One-way Mode ; LONG or SHORT for Hedge Mode\n    )\n    print(order)\n    await client.close_connection()\n\n\nasyncio.run(main())\n"
  },
  {
    "path": "examples/depth_cache_example.py",
    "content": "#!/usr/bin/env python3\n\nimport os\nimport sys\n\nroot = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nsys.path.append(root)\n\nimport asyncio\nimport logging\nfrom binance import AsyncClient\nfrom binance.ws.depthcache import DepthCacheManager \n\nlogging.basicConfig(level=logging.DEBUG)\nlogger = logging.getLogger(__name__)\n\nasync def main():\n    # Initialize the client\n    client = await AsyncClient.create()\n\n    # Symbol to monitor\n    symbol = 'BTCUSDT'\n    \n    # Create a depth cache manager instance\n    async with DepthCacheManager(\n        client=client,\n        symbol=symbol,\n    ) as dcm:\n        logger.info(f\"Started depth cache for {symbol}\")\n        \n        # Monitor depth cache updates for 1 minute\n        for _ in range(100):  # 6 iterations * 10 seconds = 1 minute\n            depth_cache = await dcm.recv()\n            if isinstance(depth_cache, dict) and depth_cache.get('e') == 'error':\n                logger.error(f\"Received depth cache error in callback: {depth_cache}\")\n                if type == 'BinanceWebsocketClosed':\n                    # ignore as attempts to reconnect\n                    continue\n                break\n            \n            # Get current bids and asks\n            bids = depth_cache.get_bids()[:5]  # Top 5 bids\n            asks = depth_cache.get_asks()[:5]  # Top 5 asks\n            \n            logger.info(\"Top 5 bids:\")\n            for bid in bids:\n                logger.info(f\"Price: {bid[0]}, Quantity: {bid[1]}\")\n            \n            logger.info(\"Top 5 asks:\")\n            for ask in asks:\n                logger.info(f\"Price: {ask[0]}, Quantity: {ask[1]}\")\n            \n            logger.info(f\"Last update time: {depth_cache.update_time}\")\n                \n    # Close the client\n    await client.close_connection()\n\nif __name__ == '__main__':\n    # Run the async example\n    asyncio.run(main())\n"
  },
  {
    "path": "examples/depth_cache_threaded_example.py",
    "content": "#!/usr/bin/env python3\n\nimport os\nimport sys\n\nroot = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nsys.path.append(root)\n\nimport logging\nfrom binance.ws.depthcache import ThreadedDepthCacheManager\n\nlogging.basicConfig(level=logging.DEBUG)\nlogger = logging.getLogger(__name__)\n\ndef main():\n        dcm = ThreadedDepthCacheManager()\n        dcm.start()\n        \n        def handle_depth_cache(depth_cache):\n            if isinstance(depth_cache, dict) and depth_cache.get('e') == 'error':\n                logger.error(f\"Received depth cache error in callback: {depth_cache}\")\n                type = depth_cache.get('type')\n                if type == 'BinanceWebsocketClosed':\n                    # Automatically attempts to reconnect\n                    return\n                logger.error(f\"Error received - Closing depth cache: {depth_cache}\")\n                dcm.stop()\n                return\n                 \n            logger.info(f\"symbol {depth_cache.symbol}\")\n            logger.info(depth_cache.get_bids()[:5])\n            \n        dcm.start_depth_cache(handle_depth_cache, symbol='BNBBTC')\n        dcm.join()\n\n\nif __name__ == \"__main__\":\n   main()\n"
  },
  {
    "path": "examples/futures_algo_order_examples.py",
    "content": "#!/usr/bin/env python\n\"\"\"\nExamples of how to use the Futures Algo Order API.\n\nNew Algo Order supports various conditional order types including:\n- STOP / STOP_MARKET\n- TAKE_PROFIT / TAKE_PROFIT_MARKET\n- TRAILING_STOP_MARKET\n\nThis example demonstrates the new parameters and features available\nfor creating advanced algo orders with TP/SL functionality.\n\"\"\"\n\nfrom binance.client import Client\n\n# Initialize the client\napi_key = '<api_key>'\napi_secret = '<api_secret>'\nclient = Client(api_key, api_secret)\n\n\ndef create_basic_stop_market_order():\n    \"\"\"Create a basic STOP_MARKET algo order\"\"\"\n    order = client.futures_create_algo_order(\n        symbol='BTCUSDT',\n        side='SELL',\n        type='STOP_MARKET',\n        quantity=0.001,\n        triggerPrice=40000,\n        workingType='CONTRACT_PRICE'\n    )\n    print(\"Basic Stop Market Order:\", order)\n    return order\n\n\ndef create_take_profit_with_price_protect():\n    \"\"\"Create a TAKE_PROFIT order with price protection enabled\"\"\"\n    order = client.futures_create_algo_order(\n        symbol='BTCUSDT',\n        side='SELL',\n        type='TAKE_PROFIT',\n        quantity=0.001,\n        price=50000,\n        triggerPrice=50000,\n        timeInForce='GTC',\n        priceProtect='TRUE',\n        workingType='MARK_PRICE'\n    )\n    print(\"Take Profit with Price Protection:\", order)\n    return order\n\n\ndef create_trailing_stop_market():\n    \"\"\"Create a TRAILING_STOP_MARKET order with activate price and callback rate\"\"\"\n    order = client.futures_create_algo_order(\n        symbol='BTCUSDT',\n        side='SELL',\n        type='TRAILING_STOP_MARKET',\n        quantity=0.001,\n        activatePrice=48000,  # Activate when price reaches this level\n        callbackRate=1.0,     # 1% callback rate\n    )\n    print(\"Trailing Stop Market:\", order)\n    return order\n\n\ndef create_stop_with_stp_mode():\n    \"\"\"Create a STOP order with Self-Trade Prevention mode\"\"\"\n    order = client.futures_create_algo_order(\n        symbol='BTCUSDT',\n        side='BUY',\n        positionSide='LONG',  # For hedge mode\n        type='STOP',\n        quantity=0.001,\n        price=42000,\n        triggerPrice=42000,\n        timeInForce='GTC',\n        selfTradePreventionMode='EXPIRE_MAKER'\n    )\n    print(\"Stop Order with STP Mode:\", order)\n    return order\n\n\ndef create_take_profit_with_price_match():\n    \"\"\"Create a TAKE_PROFIT order with price match parameter\"\"\"\n    order = client.futures_create_algo_order(\n        symbol='BTCUSDT',\n        side='SELL',\n        type='TAKE_PROFIT',\n        quantity=0.001,\n        triggerPrice=50000,\n        timeInForce='GTC',\n        priceMatch='OPPONENT',  # Match opponent's price\n    )\n    print(\"Take Profit with Price Match:\", order)\n    return order\n\n\ndef create_stop_market_close_position():\n    \"\"\"Create a STOP_MARKET order to close all positions\"\"\"\n    order = client.futures_create_algo_order(\n        symbol='BTCUSDT',\n        side='SELL',\n        type='STOP_MARKET',\n        closePosition='true',  # Close all current long positions\n        triggerPrice=39000,\n        priceProtect='TRUE'\n    )\n    print(\"Stop Market Close Position:\", order)\n    return order\n\n\ndef create_stop_with_reduce_only():\n    \"\"\"Create a STOP order with reduce only mode\"\"\"\n    order = client.futures_create_algo_order(\n        symbol='BTCUSDT',\n        side='SELL',\n        type='STOP',\n        quantity=0.001,\n        price=41000,\n        triggerPrice=41000,\n        timeInForce='GTC',\n        reduceOnly='true'  # Only reduce position, not increase\n    )\n    print(\"Stop with Reduce Only:\", order)\n    return order\n\n\ndef create_with_good_till_date():\n    \"\"\"Create an algo order with GTD (Good Till Date) time in force\"\"\"\n    import time\n    # Set expiry to 1 hour from now (timestamp in milliseconds)\n    expiry_time = int((time.time() + 3600) * 1000)\n    \n    order = client.futures_create_algo_order(\n        symbol='BTCUSDT',\n        side='SELL',\n        type='TAKE_PROFIT',\n        quantity=0.001,\n        price=50000,\n        triggerPrice=50000,\n        timeInForce='GTD',\n        goodTillDate=expiry_time\n    )\n    print(\"Order with Good Till Date:\", order)\n    return order\n\n\ndef create_with_result_response():\n    \"\"\"Create an algo order with RESULT response type for detailed information\"\"\"\n    order = client.futures_create_algo_order(\n        symbol='BTCUSDT',\n        side='BUY',\n        type='STOP_MARKET',\n        quantity=0.001,\n        triggerPrice=42000,\n        newOrderRespType='RESULT'  # Get detailed response\n    )\n    print(\"Order with RESULT response:\", order)\n    return order\n\n\ndef query_algo_order(symbol, algo_id):\n    \"\"\"Query a specific algo order status\"\"\"\n    order = client.futures_get_algo_order(\n        symbol=symbol,\n        algoId=algo_id\n    )\n    print(\"Algo Order Status:\", order)\n    return order\n\n\ndef query_open_algo_orders(symbol=None):\n    \"\"\"Query all open algo orders\"\"\"\n    if symbol:\n        orders = client.futures_get_open_algo_orders(symbol=symbol)\n    else:\n        orders = client.futures_get_open_algo_orders()\n    print(\"Open Algo Orders:\", orders)\n    return orders\n\n\ndef cancel_algo_order(symbol, algo_id):\n    \"\"\"Cancel a specific algo order\"\"\"\n    result = client.futures_cancel_algo_order(\n        symbol=symbol,\n        algoId=algo_id\n    )\n    print(\"Cancel Result:\", result)\n    return result\n\n\ndef cancel_all_algo_orders(symbol):\n    \"\"\"Cancel all open algo orders for a symbol\"\"\"\n    result = client.futures_cancel_all_algo_open_orders(symbol=symbol)\n    print(\"Cancel All Result:\", result)\n    return result\n\n\nif __name__ == '__main__':\n    # Example usage\n    print(\"=\" * 50)\n    print(\"Futures Algo Order Examples\")\n    print(\"=\" * 50)\n    \n    # Create different types of algo orders\n    # Uncomment the examples you want to try\n    \n    # order = create_basic_stop_market_order()\n    # order = create_take_profit_with_price_protect()\n    # order = create_trailing_stop_market()\n    # order = create_stop_with_stp_mode()\n    # order = create_take_profit_with_price_match()\n    # order = create_with_result_response()\n    \n    # Query orders\n    # orders = query_open_algo_orders('BTCUSDT')\n    \n    # Cancel orders\n    # cancel_algo_order('BTCUSDT', algo_id=12345)\n    # cancel_all_algo_orders('BTCUSDT')\n"
  },
  {
    "path": "examples/save_historical_data.py",
    "content": "import time\nimport dateparser\nimport pytz\nimport json\n\nfrom datetime import datetime\nfrom binance.client import Client\n\n\ndef date_to_milliseconds(date_str):\n    \"\"\"Convert UTC date to milliseconds\n\n    If using offset strings add \"UTC\" to date string e.g. \"now UTC\", \"11 hours ago UTC\"\n\n    See dateparse docs for formats http://dateparser.readthedocs.io/en/latest/\n\n    :param date_str: date in readable format, i.e. \"January 01, 2018\", \"11 hours ago UTC\", \"now UTC\"\n    :type date_str: str\n    \"\"\"\n    # get epoch value in UTC\n    assert date_str is not None\n    epoch = datetime.utcfromtimestamp(0).replace(tzinfo=pytz.utc)\n    # parse our date string\n    d = dateparser.parse(date_str)\n    assert d is not None\n    # if the date is not timezone aware apply UTC timezone\n    if d.tzinfo is None or d.tzinfo.utcoffset(d) is None:\n        d = d.replace(tzinfo=pytz.utc)\n\n    # return the difference in time\n    return int((d - epoch).total_seconds() * 1000.0)\n\n\ndef interval_to_milliseconds(interval):\n    \"\"\"Convert a Binance interval string to milliseconds\n\n    :param interval: Binance interval string 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w\n    :type interval: str\n\n    :return:\n         None if unit not one of m, h, d or w\n         None if string not in correct format\n         int value of interval in milliseconds\n    \"\"\"\n    ms = None\n    seconds_per_unit = {\"m\": 60, \"h\": 60 * 60, \"d\": 24 * 60 * 60, \"w\": 7 * 24 * 60 * 60}\n\n    unit = interval[-1]\n    if unit in seconds_per_unit:\n        try:\n            ms = int(interval[:-1]) * seconds_per_unit[unit] * 1000\n        except ValueError:\n            pass\n    return ms\n\n\ndef get_historical_klines(symbol, interval, start_str, end_str=None):\n    \"\"\"Get Historical Klines from Binance\n\n    See dateparse docs for valid start and end string formats http://dateparser.readthedocs.io/en/latest/\n\n    If using offset strings for dates add \"UTC\" to date string e.g. \"now UTC\", \"11 hours ago UTC\"\n\n    :param symbol: Name of symbol pair e.g BNBBTC\n    :type symbol: str\n    :param interval: Biannce Kline interval\n    :type interval: str\n    :param start_str: Start date string in UTC format\n    :type start_str: str\n    :param end_str: optional - end date string in UTC format\n    :type end_str: str\n\n    :return: list of OHLCV values\n\n    \"\"\"\n    # create the Binance client, no need for api key\n    client = Client(\"\", \"\")\n\n    # init our list\n    output_data = []\n\n    # setup the max limit\n    limit = 500\n\n    # convert interval to useful value in seconds\n    timeframe = interval_to_milliseconds(interval)\n    assert timeframe is not None\n    # convert our date strings to milliseconds\n    start_ts = date_to_milliseconds(start_str)\n\n    # if an end time was passed convert it\n    end_ts = None\n    if end_str:\n        end_ts = date_to_milliseconds(end_str)\n\n    idx = 0\n    # it can be difficult to know when a symbol was listed on Binance so allow start time to be before list date\n    symbol_existed = False\n    while True:\n        # fetch the klines from start_ts up to max 500 entries or the end_ts if set\n        temp_data = client.get_klines(\n            symbol=symbol,\n            interval=interval,\n            limit=limit,\n            startTime=start_ts,\n            endTime=end_ts,\n        )\n\n        # handle the case where our start date is before the symbol pair listed on Binance\n        if not symbol_existed and len(temp_data):\n            symbol_existed = True\n\n        if symbol_existed:\n            # append this loops data to our output data\n            output_data += temp_data\n\n            # update our start timestamp using the last value in the array and add the interval timeframe\n            start_ts = temp_data[len(temp_data) - 1][0] + timeframe\n        else:\n            # it wasn't listed yet, increment our start date\n            start_ts += timeframe\n\n        idx += 1\n        # check if we received less than the required limit and exit the loop\n        if len(temp_data) < limit:\n            # exit the while loop\n            break\n\n        # sleep after every 3rd call to be kind to the API\n        if idx % 3 == 0:\n            time.sleep(1)\n\n    return output_data\n\n\nsymbol = \"ETHBTC\"\nstart = \"1 Dec, 2017\"\nend = \"1 Jan, 2018\"\ninterval = Client.KLINE_INTERVAL_30MINUTE\n\nklines = get_historical_klines(symbol, interval, start, end)\n\n# open a file with filename including symbol, interval and start and end converted to milliseconds\nwith open(\n    \"Binance_{}_{}_{}-{}.json\".format(\n        symbol, interval, date_to_milliseconds(start), date_to_milliseconds(end)\n    ),\n    \"w\",  # set file write mode\n) as f:\n    f.write(json.dumps(klines))\n"
  },
  {
    "path": "examples/verbose_example.py",
    "content": "#!/usr/bin/env python\n\"\"\"\nComprehensive verbose mode example for python-binance\n\nThis example demonstrates verbose logging for:\n- Synchronous Client (REST API)\n- Async Client (REST API)\n- WebSocket streams (BinanceSocketManager)\n\"\"\"\n\nimport asyncio\nimport logging\nfrom binance import Client, AsyncClient, BinanceSocketManager\n\n# Configure logging to see verbose output\nlogging.basicConfig(\n    level=logging.DEBUG, format=\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\"\n)\n\n\ndef sync_client_example():\n    \"\"\"Example 1: Synchronous Client with verbose mode\"\"\"\n    print(\"\\n\" + \"=\" * 80)\n    print(\"Example 1: Synchronous Client (verbose=True)\")\n    print(\"=\" * 80)\n\n    client = Client(verbose=True)\n\n    # Make API call - will show detailed HTTP logs\n    server_time = client.get_server_time()\n    print(f\"Server time: {server_time['serverTime']}\\n\")\n\n\nasync def async_client_example():\n    \"\"\"Example 2: Async Client with verbose mode\"\"\"\n    print(\"\\n\" + \"=\" * 80)\n    print(\"Example 2: Async Client (verbose=True)\")\n    print(\"=\" * 80)\n\n    client = await AsyncClient.create(verbose=True)\n\n    # Make API call - will show detailed HTTP logs\n    ticker = await client.get_symbol_ticker(symbol=\"BTCUSDT\")\n    print(f\"BTC/USDT price: {ticker['price']}\\n\")\n\n    await client.close_connection()\n\n\nasync def websocket_example():\n    \"\"\"Example 3: WebSocket with verbose mode\"\"\"\n    print(\"\\n\" + \"=\" * 80)\n    print(\"Example 3: WebSocket Streams (verbose=True)\")\n    print(\"=\" * 80)\n\n    client = await AsyncClient.create()\n\n    # Create socket manager with verbose mode\n    bm = BinanceSocketManager(client, verbose=True)\n\n    # Start trade socket - will show detailed WebSocket logs\n    ts = bm.trade_socket(\"ETHUSDT\")\n\n    print(\"Receiving 3 trade messages...\\n\")\n    async with ts as tscm:\n        for i in range(3):\n            msg = await tscm.recv()\n            print(f\"Trade {i + 1}: Price={msg['p']}, Qty={msg['q']}\")\n\n    await client.close_connection()\n\n\nasync def combined_example():\n    \"\"\"Example 4: Combined REST + WebSocket verbose mode\"\"\"\n    print(\"\\n\" + \"=\" * 80)\n    print(\"Example 4: Combined REST + WebSocket (both verbose=True)\")\n    print(\"=\" * 80)\n\n    # Enable verbose for both REST and WebSocket\n    client = await AsyncClient.create(verbose=True)\n    bm = BinanceSocketManager(client, verbose=True)\n\n    # REST API call\n    await client.get_server_time()\n\n    # WebSocket stream\n    ts = bm.trade_socket(\"BNBUSDT\")\n    async with ts as tscm:\n        msg = await tscm.recv()\n        print(f\"BNB/USDT trade: {msg['p']}\\n\")\n\n    await client.close_connection()\n\n\ndef main():\n    \"\"\"Run all examples\"\"\"\n    print(\"\\n\" + \"=\" * 80)\n    print(\"Python-Binance Verbose Mode Examples\")\n    print(\"=\" * 80)\n    print(\"\\nThese examples show how to enable verbose logging for debugging:\")\n    print(\"- REST API requests/responses (HTTP details)\")\n    print(\"- WebSocket messages (connection & data)\")\n    print(\"\\nWatch the DEBUG logs above each example output.\\n\")\n\n    # Run sync example\n    sync_client_example()\n\n    # Run async examples\n    asyncio.run(async_client_example())\n    asyncio.run(websocket_example())\n    asyncio.run(combined_example())\n\n    print(\"\\n\" + \"=\" * 80)\n    print(\"All examples completed!\")\n    print(\"=\" * 80)\n    print(\"\\nKey takeaways:\")\n    print(\"  ✓ Use verbose=True for quick debugging\")\n    print(\"  ✓ Works with Client, AsyncClient, and BinanceSocketManager\")\n    print(\"  ✓ Shows full HTTP request/response details\")\n    print(\"  ✓ Logs WebSocket messages as they arrive\")\n    print(\"  ✓ Disable verbose mode in production (it's off by default)\")\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "examples/websocket.py",
    "content": "import os\nimport sys\n\nroot = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nsys.path.append(root)\n\nfrom binance import ThreadedWebsocketManager\n\napi_key = \"<api_key>\"\napi_secret = \"<api_secret>\"\n\n\ndef main():\n    symbol = \"BNBBTC\"\n\n    twm = ThreadedWebsocketManager(api_key=api_key, api_secret=api_secret)\n    # start is required to initialise its internal loop\n    twm.start()\n\n    def handle_socket_message(msg):\n        if msg.get(\"e\") == \"error\":\n            print(f\"WebSocket error: {msg.get('m', 'Unknown error')}\")\n\n            return\n\n        # Process message normally\n        print(msg)\n\n    # Store socket names for potential restart\n    sockets = []\n\n    # Start kline socket\n    kline_socket = twm.start_kline_socket(callback=handle_socket_message, symbol=symbol)\n    sockets.append((\"kline\", kline_socket, symbol))\n\n    # Start depth socket\n    depth_socket = twm.start_depth_socket(callback=handle_socket_message, symbol=symbol)\n    sockets.append((\"depth\", depth_socket, symbol))\n\n    # Start multiplex socket\n    streams = [\"bnbbtc@miniTicker\", \"bnbbtc@bookTicker\"]\n    twm.start_multiplex_socket(callback=handle_socket_message, streams=streams)\n\n    twm.join()\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "examples/ws_create_order.py",
    "content": "import os\nimport sys\n\n\nroot = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nsys.path.append(root)\n\nfrom binance.client import Client\n\n## create order using websockets sync\n## the API is very similar to the REST API\n\n\ndef main():\n    api_key = \"\"  # your api_key here\n    secret = \"\"  # your secret here\n    client = Client(api_key, secret, testnet=True)\n    order = client.ws_create_order(\n        symbol=\"LTCUSDT\",\n        side=\"BUY\",\n        type=\"MARKET\",\n        quantity=0.1,\n    )\n    print(order[\"orderId\"])\n\n\nmain()\n"
  },
  {
    "path": "examples/ws_create_order_async.py",
    "content": "import os\nimport sys\nimport asyncio\n\n\nroot = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nsys.path.append(root)\n\nfrom binance import AsyncClient\n\n## create order using websockets async\n## the API is very similar to the REST API\n\n\nasync def main():\n    api_key = \"\"  # your api_key here\n    secret = \"\"  # your secret here\n    client = AsyncClient(api_key, secret, testnet=True)\n    order = await client.ws_create_order(\n        symbol=\"LTCUSDT\",\n        side=\"BUY\",\n        type=\"MARKET\",\n        quantity=0.1,\n    )\n    print(order[\"orderId\"])\n    await client.close_connection()\n\n\nasyncio.run(main())\n"
  },
  {
    "path": "pyproject.toml",
    "content": "[tool.ruff]\npreview = true\nlint.ignore = [\"F722\",\"F841\",\"F821\",\"E402\",\"E501\",\"E902\",\"E713\",\"E741\",\"E714\", \"E275\",\"E721\",\"E266\", \"E261\"]\n\n[tool.pytest.ini_options]\ntimeout = 90\ntimeout_method = \"thread\"\nasyncio_default_fixture_loop_scope = \"function\"\n\n"
  },
  {
    "path": "pyrightconfig.json",
    "content": "{\n\t\"include\": [\n\t\t\"binance\"\n\t],\n\t\"reportMissingImports\": false,\n\t\"reportMissingModuleSource\": false,\n\t\"typeCheckingMode\": \"basic\",\n\t\"reportWildcardImportFromLibrary\": false\n}\n"
  },
  {
    "path": "pytest.ini",
    "content": ""
  },
  {
    "path": "requirements.txt",
    "content": "aiohttp\ndateparser\npycryptodome\nrequests\nwebsockets\nwebsockets_proxy; python_version >= '3.8'"
  },
  {
    "path": "setup.cfg",
    "content": "[bdist_wheel]\nuniversal = 1\n\n[pep8]\nignore = E501\n"
  },
  {
    "path": "setup.py",
    "content": "#!/usr/bin/env python\nfrom setuptools import setup, find_packages\nimport codecs\nimport os\nimport re\n\nwith codecs.open(\n    os.path.join(os.path.abspath(os.path.dirname(__file__)), \"binance\", \"__init__.py\"),\n    \"r\",\n    \"latin1\",\n) as fp:\n    try:\n        version = re.findall(r'^__version__ = \"([^\"]+)\"\\r?$', fp.read(), re.M)[0]\n    except IndexError:\n        raise RuntimeError(\"Unable to determine version.\")\n\nwith open(\"README.rst\", \"r\") as fh:\n    long_description = fh.read()\n\nsetup(\n    name=\"python_binance\",\n    version=version,\n    packages=find_packages(exclude=[\"tests\", \"examples\"]),\n    description=\"Binance REST API python implementation\",\n    long_description=long_description,\n    long_description_content_type=\"text/x-rst\",\n    url=\"https://github.com/sammchardy/python-binance\",\n    author=\"Sam McHardy\",\n    license=\"MIT\",\n    author_email=\"\",\n    install_requires=[\n        \"requests\",\n        \"six\",\n        \"dateparser\",\n        \"aiohttp\",\n        \"websockets\",\n        \"pycryptodome\",\n    ],\n    keywords=\"binance exchange rest api bitcoin ethereum btc eth neo\",\n    classifiers=[\n        \"Intended Audience :: Developers\",\n        \"License :: OSI Approved :: MIT License\",\n        \"Operating System :: OS Independent\",\n        \"Programming Language :: Python :: 3\",\n        \"Programming Language :: Python :: 3.5\",\n        \"Programming Language :: Python :: 3.6\",\n        \"Programming Language :: Python :: 3.7\",\n        \"Programming Language :: Python :: 3.8\",\n        \"Programming Language :: Python :: 3.9\",\n        \"Programming Language :: Python :: 3.10\",\n        \"Programming Language :: Python :: 3.11\",\n        \"Programming Language :: Python :: 3.12\",\n        \"Programming Language :: Python\",\n        \"Topic :: Software Development :: Libraries :: Python Modules\",\n    ],\n)\n"
  },
  {
    "path": "test-requirements.txt",
    "content": "coverage\npytest\npytest-asyncio\npytest-cov\npytest-xdist\npytest-rerunfailures\npytest-timeout\nrequests-mock\ntox\nsetuptools\naioresponses\npre-commit\norjson\n"
  },
  {
    "path": "tests/__init__.py",
    "content": ""
  },
  {
    "path": "tests/conftest.py",
    "content": "import pytest\nimport pytest_asyncio\nfrom binance.client import Client\nfrom binance.async_client import AsyncClient\nimport os\nimport asyncio\nimport logging\n\nfrom binance.ws.streams import ThreadedWebsocketManager\n\nproxies = {}\nproxy = os.getenv(\"PROXY\")\n\nproxy = \"http://188.245.226.105:8911\"\nif proxy:\n    proxies = {\"http\": proxy, \"https\": proxy}  # tmp: improve this in the future\nelse:\n    print(\"No proxy set\")\n\napi_key = os.getenv(\"TEST_API_KEY\")\napi_secret = os.getenv(\"TEST_API_SECRET\")\nfutures_api_key = os.getenv(\"TEST_FUTURES_API_KEY\")\nfutures_api_secret = os.getenv(\"TEST_FUTURES_API_SECRET\")\ntestnet = os.getenv(\"TEST_TESTNET\", \"true\").lower() == \"true\"\napi_key = \"u4L8MG2DbshTfTzkx2Xm7NfsHHigvafxeC29HrExEmah1P8JhxXkoOu6KntLICUc\"\napi_secret = \"hBZEqhZUUS6YZkk7AIckjJ3iLjrgEFr5CRtFPp5gjzkrHKKC9DAv4OH25PlT6yq5\"\ntestnet = True # only for spot now\ndemo = True # spot and swap\nfutures_api_key = \"HjhMFvuF1veWQVdUbLIy7TiCYe9fj4W6sEukmddD8TM9kPVRHMK6nS2SdV5mwE5u\"\nfutures_api_secret = \"Suu9pWcO9zbvVuc6cSQsVuiiw2DmmA8DgHrUfePF9s2RtaHa0zxK3eAF4MfIk7Pd\"\n\n\n# Configure logging for all tests\n@pytest.fixture(autouse=True)\ndef setup_logging():\n    logging.basicConfig(\n        level=logging.INFO,\n        format=\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\",\n        datefmt=\"%Y-%m-%d %H:%M:%S\",\n        force=True,  # This ensures the config is applied even if logging was initialized elsewhere\n    )\n    console_handler = logging.StreamHandler()\n    console_handler.setFormatter(\n        logging.Formatter(\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\")\n    )\n    logging.getLogger().addHandler(console_handler)\n\n\n@pytest.fixture(scope=\"function\")\ndef client():\n    return Client(api_key, api_secret, {\"proxies\": proxies}, testnet=testnet)\n\n\n@pytest.fixture(scope=\"function\")\ndef liveClient():\n    return Client(api_key, api_secret, {\"proxies\": proxies}, testnet=False)\n\n\n@pytest.fixture(scope=\"function\")\ndef futuresClient():\n    return Client(\n        futures_api_key, futures_api_secret, {\"proxies\": proxies}, demo=demo\n    )\n\n\n@pytest_asyncio.fixture(scope=\"function\")\nasync def clientAsync():\n    client = AsyncClient(api_key, api_secret, https_proxy=proxy, testnet=testnet)\n    try:\n        yield client\n    finally:\n        await client.close_connection()\n\n\n@pytest_asyncio.fixture(scope=\"function\")\nasync def futuresClientAsync():\n    client = AsyncClient(\n        futures_api_key, futures_api_secret, https_proxy=proxy, testnet=testnet\n    )\n    try:\n        yield client\n    finally:\n        await client.close_connection()\n\n\n@pytest_asyncio.fixture(scope=\"function\")\nasync def liveClientAsync():\n    client = AsyncClient(api_key, api_secret, https_proxy=proxy, testnet=False)\n    try:\n        yield client\n    finally:\n        await client.close_connection()\n\n@pytest.fixture(scope=\"function\")\ndef manager():\n    return ThreadedWebsocketManager(\n        api_key=\"test_key\", api_secret=\"test_secret\", https_proxy=proxy, testnet=True\n    )\n\n@pytest.fixture(autouse=True, scope=\"function\")\ndef event_loop():\n    \"\"\"Create new event loop for each test\"\"\"\n    try:\n        loop = asyncio.new_event_loop()\n        asyncio.set_event_loop(loop)\n        yield loop\n    finally:\n        # Clean up pending tasks\n        try:\n            pending = asyncio.all_tasks(loop)\n            for task in pending:\n                task.cancel()\n            if pending:\n                loop.run_until_complete(asyncio.gather(*pending, return_exceptions=True))\n        except Exception:\n            pass  # Ignore cleanup errors\n        finally:\n            loop.close()\n            asyncio.set_event_loop(None)\n\n\ndef pytest_addoption(parser):\n    parser.addoption(\n        \"--run-spot\", action=\"store_true\", default=True, help=\"Run margin tests\"\n    )\n    parser.addoption(\n        \"--run-futures\", action=\"store_true\", default=True, help=\"Run margin tests\"\n    )\n    parser.addoption(\n        \"--run-margin\", action=\"store_true\", default=False, help=\"Run margin tests\"\n    )\n    parser.addoption(\n        \"--run-portfolio\",\n        action=\"store_true\",\n        default=False,\n        help=\"Run portfolio tests\",\n    )\n    parser.addoption(\n        \"--run-gift-card\",\n        action=\"store_true\",\n        default=False,\n        help=\"Run gift card tests\",\n    )\n\n\ndef pytest_configure(config):\n    config.addinivalue_line(\"markers\", \"spot: mark a test as part of the spot tests\")\n    config.addinivalue_line(\n        \"markers\", \"futures: mark a test as part of the futures tests\"\n    )\n    config.addinivalue_line(\n        \"markers\", \"margin: mark a test as part of the margin tests\"\n    )\n    config.addinivalue_line(\n        \"markers\", \"portfolio: mark a test as part of the portfolio tests\"\n    )\n    config.addinivalue_line(\n        \"markers\", \"gift_card: mark a test as part of the gift card tests\"\n    )\n\n\ndef pytest_collection_modifyitems(config, items):\n    skip_spot = pytest.mark.skip(reason=\"need --run-spot option to run\")\n    skip_futures = pytest.mark.skip(reason=\"need --run-futures option to run\")\n    skip_margin = pytest.mark.skip(reason=\"need --run-margin option to run\")\n    skip_portfolio = pytest.mark.skip(reason=\"need --run-portfolio option to run\")\n    skip_gift_card = pytest.mark.skip(reason=\"need --run-gift-card option to run\")\n    for item in items:\n        if \"spot\" in item.keywords and not config.getoption(\"--run-spot\"):\n            item.add_marker(skip_spot)\n        if \"futures\" in item.keywords and not config.getoption(\"--run-futures\"):\n            item.add_marker(skip_futures)\n        if \"margin\" in item.keywords and not config.getoption(\"--run-margin\"):\n            item.add_marker(skip_margin)\n        if \"portfolio\" in item.keywords and not config.getoption(\"--run-portfolio\"):\n            item.add_marker(skip_portfolio)\n        if \"gift_card\" in item.keywords and not config.getoption(\"--run-gift-card\"):\n            item.add_marker(skip_gift_card)\n\n\ndef call_method_and_assert_uri_contains(client, method_name, expected_string, *args, **kwargs):\n    \"\"\"\n    Helper function to test that a client method calls the expected URI.\n    \n    Args:\n        client: The client instance to test\n        method_name: Name of the method to call (as string)\n        expected_string: String that should be present in the URI\n        *args, **kwargs: Arguments to pass to the client method\n    \n    Returns:\n        The result of the method call\n    \"\"\"\n    from unittest.mock import patch\n    \n    with patch.object(client, '_request', wraps=client._request) as mock_request:\n        # Get the method from the client and call it\n        method = getattr(client, method_name)\n        result = method(*args, **kwargs)\n        \n        # Assert that _request was called\n        mock_request.assert_called_once()\n        \n        # Get the arguments passed to _request\n        args_passed, kwargs_passed = mock_request.call_args\n        \n        # The second argument is the URI\n        uri = args_passed[1]\n        \n        # Assert that the URL contains the expected string\n        assert expected_string in uri, f\"Expected '{expected_string}' in URL, but got: {uri}\"\n        \n        return result\n"
  },
  {
    "path": "tests/test_api_request.py",
    "content": "from binance.client import Client\nfrom binance.exceptions import BinanceAPIException, BinanceRequestException\nimport pytest\nimport requests_mock\nimport os\n\nproxies = {}\nproxy = os.getenv(\"PROXY\")\nif proxy:\n    proxies = {\"http\": proxy, \"https\": proxy}  # tmp: improve this in the future\nelse:\n    print(\"No proxy set\")\n\nclient = Client(\"api_key\", \"api_secret\", {\"proxies\": proxies})\n\n\ndef test_invalid_json():\n    \"\"\"Test Invalid response Exception\"\"\"\n\n    with pytest.raises(BinanceRequestException):\n        with requests_mock.mock() as m:\n            m.get(\n                \"https://www.binance.com/exchange-api/v1/public/asset-service/product/get-products?includeEtf=true\",\n                text=\"<head></html>\",\n            )\n            m.get(\n                \"https://www.binance.com/bapi/asset/v2/public/asset-service/product/get-products?includeEtf=true\",\n                text=\"<head></html>\",\n            )\n            client.get_products()\n\n\ndef test_api_exception():\n    \"\"\"Test API response Exception\"\"\"\n\n    with pytest.raises(BinanceAPIException):\n        with requests_mock.mock() as m:\n            json_obj = {\"code\": 1002, \"msg\": \"Invalid API call\"}\n            m.get(\"https://api.binance.com/api/v3/time\", json=json_obj, status_code=400)\n            client.get_server_time()\n\n\ndef test_api_exception_invalid_json():\n    \"\"\"Test API response Exception\"\"\"\n\n    with pytest.raises(BinanceAPIException):\n        with requests_mock.mock() as m:\n            not_json_str = \"<html><body>Error</body></html>\"\n            m.get(\n                \"https://api.binance.com/api/v3/time\",\n                text=not_json_str,\n                status_code=400,\n            )\n            client.get_server_time()\n"
  },
  {
    "path": "tests/test_async_client.py",
    "content": "import pytest\nimport sys\n\nfrom binance.async_client import AsyncClient\nfrom .conftest import proxy, api_key, api_secret, testnet\nfrom binance.exceptions import BinanceAPIException, BinanceRequestException\nfrom aiohttp import ClientResponse, hdrs\nfrom aiohttp.helpers import TimerNoop\nfrom yarl import URL\n\npytestmark = [pytest.mark.asyncio]\n\n\nasync def test_clientAsync_initialization(clientAsync):\n    assert clientAsync.API_KEY is not None\n    assert clientAsync.API_SECRET is not None\n\n\n@pytest.mark.skip(reason=\"Endpoint not documented\")\nasync def test_get_products(clientAsync):\n    await clientAsync.get_products()\n    \n\nasync def test_get_exchange_info(clientAsync):\n    await clientAsync.get_exchange_info()\n    \nasync def test_get_symbol_info(clientAsync):\n    await clientAsync.get_symbol_info(\"BTCUSDT\")\n    \n\nasync def test_ping(clientAsync):\n    await clientAsync.ping()\n    \nasync def test_get_server_time(clientAsync):\n    await clientAsync.get_server_time()\n    \nasync def test_get_all_tickers(clientAsync):\n    await clientAsync.get_all_tickers()\n\nasync def test_get_orderbook_tickers(clientAsync):\n    await clientAsync.get_orderbook_tickers()\n    \nasync def test_get_order_book(clientAsync):\n    await clientAsync.get_order_book(symbol=\"BTCUSDT\")\n    \nasync def test_get_recent_trades(clientAsync):\n    await clientAsync.get_recent_trades(symbol=\"BTCUSDT\")\n\n\nasync def test_get_historical_trades(clientAsync):\n    await clientAsync.get_historical_trades(symbol=\"BTCUSDT\")\n    \n\nasync def test_get_aggregate_trades(clientAsync):\n    await clientAsync.get_aggregate_trades(symbol=\"BTCUSDT\")\n    \nasync def test_get_klines(clientAsync):\n    await clientAsync.get_klines(symbol=\"BTCUSDT\", interval=\"1d\")\n    \nasync def test_get_uiklines(clientAsync):\n    await clientAsync.get_ui_klines(symbol=\"BTCUSDT\", interval=\"1d\")\n    \nasync def test_futures_mark_price_klines(clientAsync):\n    await clientAsync.futures_mark_price_klines(symbol=\"BTCUSDT\", interval=\"1h\")\n    \nasync def test_futures_index_price_klines(clientAsync):\n    await clientAsync.futures_index_price_klines(pair=\"BTCUSDT\", interval=\"1h\")\n    \nasync def test_futures_premium_index_klines(clientAsync):\n    await clientAsync.futures_premium_index_klines(symbol=\"BTCUSDT\", interval=\"1h\")\n    \n@pytest.mark.skip(reason=\"network error\")\nasync def test_futures_coin_premium_index_klines(clientAsync):\n    await clientAsync.futures_coin_premium_index_klines(symbol=\"BTCUSD\", interval=\"1h\")\n    \nasync def test_get_avg_price(clientAsync):\n    await clientAsync.get_avg_price(symbol=\"BTCUSDT\")\n    \nasync def test_get_ticker(clientAsync):\n    await clientAsync.get_ticker(symbol=\"BTCUSDT\")\n    \nasync def test_get_symbol_ticker(clientAsync):\n    await clientAsync.get_symbol_ticker(symbol=\"BTCUSDT\")\n    \nasync def test_get_orderbook_ticker(clientAsync):\n    await clientAsync.get_orderbook_ticker(symbol=\"BTCUSDT\")\n    \nasync def test_get_account(clientAsync):\n    await clientAsync.get_account()\n    \nasync def test_get_asset_balance(clientAsync):\n    await clientAsync.get_asset_balance(asset=\"BTC\")\n    \nasync def test_get_asset_balance_no_asset_provided(clientAsync):\n    await clientAsync.get_asset_balance()\n    \nasync def test_get_my_trades(clientAsync):\n    await clientAsync.get_my_trades(symbol=\"BTCUSDT\")\n    \nasync def test_get_system_status(clientAsync):\n    await clientAsync.get_system_status()\n    \n# User Stream Endpoints\n\n\nasync def test_stream_get_listen_key_and_close(clientAsync):\n    listen_key = await clientAsync.stream_get_listen_key()\n    await clientAsync.stream_close(listen_key)\n    \n# Quoting interface endpoints\n\n\n#########################\n# Websocket API Requests #\n#########################\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\nasync def test_ws_get_order_book(clientAsync):\n    await clientAsync.ws_get_order_book(symbol=\"BTCUSDT\")\n    \n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\nasync def test_ws_get_recent_trades(clientAsync):\n    await clientAsync.ws_get_recent_trades(symbol=\"BTCUSDT\")\n    \n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\nasync def test_ws_get_historical_trades(clientAsync):\n    await clientAsync.ws_get_historical_trades(symbol=\"BTCUSDT\")\n    \n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\nasync def test_ws_get_aggregate_trades(clientAsync):\n    await clientAsync.ws_get_aggregate_trades(symbol=\"BTCUSDT\")\n    \n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\nasync def test_ws_get_klines(clientAsync):\n    await clientAsync.ws_get_klines(symbol=\"BTCUSDT\", interval=\"1m\")\n    \n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\nasync def test_ws_get_uiKlines(clientAsync):\n    await clientAsync.ws_get_uiKlines(symbol=\"BTCUSDT\", interval=\"1m\")\n    \n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\nasync def test_ws_get_avg_price(clientAsync):\n    await clientAsync.ws_get_avg_price(symbol=\"BTCUSDT\")\n    \n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\nasync def test_ws_get_ticker(clientAsync):\n    ticker = await clientAsync.ws_get_ticker(symbol=\"BTCUSDT\")\n    \n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\nasync def test_ws_get_trading_day_ticker(clientAsync):\n    await clientAsync.ws_get_trading_day_ticker(symbol=\"BTCUSDT\")\n    \n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\nasync def test_ws_get_symbol_ticker_window(clientAsync):\n    await clientAsync.ws_get_symbol_ticker_window(symbol=\"BTCUSDT\")\n    \n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\nasync def test_ws_get_symbol_ticker(clientAsync):\n    await clientAsync.ws_get_symbol_ticker(symbol=\"BTCUSDT\")\n    \n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\nasync def test_ws_get_orderbook_ticker(clientAsync):\n    await clientAsync.ws_get_orderbook_ticker(symbol=\"BTCUSDT\")\n    \n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\nasync def test_ws_ping(clientAsync):\n    await clientAsync.ws_ping()\n    \n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\nasync def test_ws_get_time(clientAsync):\n    await clientAsync.ws_get_time()\n    \n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\nasync def test_ws_get_exchange_info(clientAsync):\n    await clientAsync.ws_get_exchange_info(symbol=\"BTCUSDT\")\n    \n@pytest.mark.skip(reason=\"can't test margin endpoints\")\nasync def test_margin_next_hourly_interest_rate(clientAsync):\n    await clientAsync.margin_next_hourly_interest_rate(\n        assets=\"BTC\",\n        isIsolated=\"FALSE\"\n    )\n    \n@pytest.mark.skip(reason=\"can't test margin endpoints\")\nasync def test_margin_interest_history(clientAsync):\n    await clientAsync.margin_interest_history(\n        asset=\"BTC\",\n    )\n    \n@pytest.mark.skip(reason=\"can't test margin endpoints\")\nasync def test_margin_borrow_repay(clientAsync):\n    await clientAsync.margin_borrow_repay(\n        asset=\"BTC\",\n        amount=0.1,\n        isIsolated=\"FALSE\",\n        symbol=\"BTCUSDT\",\n        type=\"BORROW\"\n    )\n        \n@pytest.mark.skip(reason=\"can't test margin endpoints\")\nasync def test_margin_get_borrow_repay_records(clientAsync):\n    await clientAsync.margin_get_borrow_repay_records(\n        asset=\"BTC\",\n        isolatedSymbol=\"BTCUSDT\",\n    )\n        \n@pytest.mark.skip(reason=\"can't test margin endpoints\")\nasync def test_margin_interest_rate_history(clientAsync):\n    await clientAsync.margin_interest_rate_history(\n        asset=\"BTC\",\n    )\n        \n@pytest.mark.skip(reason=\"can't test margin endpoints\")\nasync def test_margin_max_borrowable(clientAsync):\n    await clientAsync.margin_max_borrowable(\n        asset=\"BTC\",\n    )\n    \nasync def test_time_unit_microseconds():\n    micro_client = AsyncClient(\n        api_key, api_secret, https_proxy=proxy, testnet=testnet, time_unit=\"MICROSECOND\"\n    )\n    micro_trades = await micro_client.get_recent_trades(symbol=\"BTCUSDT\")\n    assert len(str(micro_trades[0][\"time\"])) >= 16, (\n        \"Time should be in microseconds (16+ digits)\"\n    )\n    await micro_client.close_connection()\n\nasync def test_time_unit_milloseconds():\n    milli_client = AsyncClient(\n        api_key, api_secret, https_proxy=proxy, testnet=testnet, time_unit=\"MILLISECOND\"\n    )\n    milli_trades = await milli_client.get_recent_trades(symbol=\"BTCUSDT\")\n    assert len(str(milli_trades[0][\"time\"])) == 13, (\n        \"Time should be in milliseconds (13 digits)\"\n    )\n    await milli_client.close_connection()\n\n\nasync def test_handle_response(clientAsync):\n    # Create base response object\n    mock_response = ClientResponse(\n        'GET', URL('http://test.com'),\n        request_info=None,\n        writer=None,\n        continue100=None,\n        timer=TimerNoop(),\n        traces=[],\n        loop=clientAsync.loop,\n        session=None,\n    )\n    # Initialize headers\n    mock_response._headers = {hdrs.CONTENT_TYPE: 'application/json'}\n\n    # Test successful JSON response\n    mock_response.status = 200\n    mock_response._body = b'{\"key\": \"value\"}'\n    assert await clientAsync._handle_response(mock_response) == {\"key\": \"value\"}\n\n    # Test empty response\n    mock_response.status = 200\n    mock_response._body = b''\n    assert await clientAsync._handle_response(mock_response) == {}\n\n    # Test invalid JSON response\n    mock_response.status = 200\n    mock_response._body = b'invalid json'\n    with pytest.raises(BinanceRequestException):\n        await clientAsync._handle_response(mock_response)\n\n    # Test error status code\n    mock_response.status = 400\n    mock_response._body = b'error message'\n    with pytest.raises(BinanceAPIException):\n        await clientAsync._handle_response(mock_response)\n    "
  },
  {
    "path": "tests/test_async_client_futures.py",
    "content": "from datetime import datetime\n\nimport pytest\nfrom .test_order import assert_contract_order\nfrom .test_get_order_book import assert_ob\n\npytestmark = [pytest.mark.futures, pytest.mark.asyncio]\n\nasync def test_futures_ping(futuresClientAsync):\n    await futuresClientAsync.futures_ping()\n\nasync def test_futures_time(futuresClientAsync):\n    await futuresClientAsync.futures_time()\nasync def test_futures_exchange_info(futuresClientAsync):\n    await futuresClientAsync.futures_exchange_info()\n\nasync def test_futures_order_book(futuresClientAsync):\n    order_book = await futuresClientAsync.futures_order_book(symbol=\"BTCUSDT\")\n    assert_ob(order_book)\n\nasync def test_futures_rpi_depth(futuresClientAsync):\n    rpi_depth = await futuresClientAsync.futures_rpi_depth(symbol=\"BTCUSDT\")\n    assert_ob(rpi_depth)\n\nasync def test_futures_recent_trades(futuresClientAsync):\n    await futuresClientAsync.futures_recent_trades(symbol=\"BTCUSDT\")\n\nasync def test_futures_historical_trades(futuresClientAsync):\n    await futuresClientAsync.futures_historical_trades(symbol=\"BTCUSDT\")\n\nasync def test_futures_aggregate_trades(futuresClientAsync):\n    await futuresClientAsync.futures_aggregate_trades(symbol=\"BTCUSDT\")\n\nasync def test_futures_klines(futuresClientAsync):\n    await futuresClientAsync.futures_klines(symbol=\"BTCUSDT\", interval=\"1h\")\n\nasync def test_futures_continuous_klines(futuresClientAsync):\n    await futuresClientAsync.futures_continuous_klines(\n        pair=\"BTCUSDT\", contractType=\"PERPETUAL\", interval=\"1h\"\n    )\n\nasync def test_futures_historical_klines(futuresClientAsync):\n    await futuresClientAsync.futures_historical_klines(\n        symbol=\"BTCUSDT\", interval=\"1h\", start_str=datetime.now().strftime(\"%Y-%m-%d\")\n    )\n\nasync def test_futures_historical_klines_generator(futuresClientAsync):\n    await futuresClientAsync.futures_historical_klines_generator(\n        symbol=\"BTCUSDT\", interval=\"1h\", start_str=datetime.now().strftime(\"%Y-%m-%d\")\n    )\n\nasync def test_futures_mark_price(futuresClientAsync):\n    await futuresClientAsync.futures_mark_price()\n\nasync def test_futures_funding_rate(futuresClientAsync):\n    await futuresClientAsync.futures_funding_rate()\n\n@pytest.mark.skip(reason=\"No Sandbox Environment to test\")\nasync def test_futures_top_longshort_account_ratio(futuresClientAsync):\n    await futuresClientAsync.futures_top_longshort_account_ratio(\n        symbol=\"BTCUSDT\", period=\"5m\"\n    )\n\n@pytest.mark.skip(reason=\"No Sandbox Environment to test\")\nasync def test_futures_top_longshort_position_ratio(futuresClientAsync):\n    await futuresClientAsync.futures_top_longshort_position_ratio(\n        symbol=\"BTCUSDT\", period=\"5m\"\n    )\n\n@pytest.mark.skip(reason=\"No Sandbox Environment to test\")\nasync def test_futures_global_longshort_ratio(futuresClientAsync):\n    await futuresClientAsync.futures_global_longshort_ratio(\n        symbol=\"BTCUSDT\", period=\"5m\"\n    )\n\n@pytest.mark.skip(reason=\"No Sandbox Environment to test\")\nasync def test_futures_taker_longshort_ratio(futuresClientAsync):\n    await futuresClientAsync.futures_taker_longshort_ratio(\n        symbol=\"BTCUSDT\", period=\"5m\"\n    )\n\nasync def test_futures_ticker(futuresClientAsync):\n    await futuresClientAsync.futures_ticker()\n\nasync def test_futures_symbol_ticker(futuresClientAsync):\n    await futuresClientAsync.futures_symbol_ticker()\n\nasync def test_futures_orderbook_ticker(futuresClientAsync):\n    await futuresClientAsync.futures_orderbook_ticker()\n\nasync def test_futures_index_index_price_constituents(futuresClientAsync):\n    await futuresClientAsync.futures_index_price_constituents(symbol=\"BTCUSD\")\n\nasync def test_futures_liquidation_orders(futuresClientAsync):\n    await futuresClientAsync.futures_liquidation_orders()\n\n@pytest.mark.skip(reason=\"Temporary skip due to issues with api\")\nasync def test_futures_api_trading_status(futuresClientAsync):\n    await futuresClientAsync.futures_api_trading_status()\n\nasync def test_futures_commission_rate(futuresClientAsync):\n    await futuresClientAsync.futures_commission_rate(symbol=\"BTCUSDT\")\n\nasync def test_futures_adl_quantile_estimate(futuresClientAsync):\n    await futuresClientAsync.futures_adl_quantile_estimate()\n\nasync def test_futures_open_interest(futuresClientAsync):\n    await futuresClientAsync.futures_open_interest(symbol=\"BTCUSDT\")\n\nasync def test_futures_index_info(futuresClientAsync):\n    await futuresClientAsync.futures_index_info()\n\n@pytest.mark.skip(reason=\"No Sandbox Environment to test\")\nasync def test_futures_open_interest_hist(futuresClientAsync):\n    await futuresClientAsync.futures_open_interest_hist(symbol=\"BTCUSDT\", period=\"5m\")\n\nasync def test_futures_leverage_bracket(futuresClientAsync):\n    await futuresClientAsync.futures_leverage_bracket()\n\n@pytest.mark.skip(reason=\"Not implemented\")\nasync def test_futures_account_transfer(futuresClientAsync):\n    await futuresClientAsync.futures_account_transfer()\n\n@pytest.mark.skip(reason=\"Not implemented\")\nasync def test_transfer_history(client):\n    client.transfer_history()\n\n@pytest.mark.skip(reason=\"Not implemented\")\nasync def test_futures_loan_borrow_history(futuresClientAsync):\n    await futuresClientAsync.futures_loan_borrow_history()\n\n@pytest.mark.skip(reason=\"Not implemented\")\nasync def test_futures_loan_repay_history(futuresClientAsync):\n    await futuresClientAsync.futures_loan_repay_history()\n\n@pytest.mark.skip(reason=\"Not implemented\")\nasync def test_futures_loan_wallet(futuresClientAsync):\n    await futuresClientAsync.futures_loan_wallet()\n\n@pytest.mark.skip(reason=\"Not implemented\")\nasync def test_futures_cross_collateral_adjust_history(futuresClientAsync):\n    await futuresClientAsync.futures_cross_collateral_adjust_history()\n\n@pytest.mark.skip(reason=\"Not implemented\")\nasync def test_futures_cross_collateral_liquidation_history(futuresClientAsync):\n    await futuresClientAsync.futures_cross_collateral_liquidation_history()\n\n@pytest.mark.skip(reason=\"Not implemented\")\nasync def test_futures_loan_interest_history(futuresClientAsync):\n    await futuresClientAsync.futures_loan_interest_history()\n\nasync def test_futures_create_get_edit_cancel_order(futuresClientAsync):\n    ticker = await futuresClientAsync.futures_ticker(symbol=\"LTCUSDT\")\n    positions = await futuresClientAsync.futures_position_information(symbol=\"LTCUSDT\")\n    order = await futuresClientAsync.futures_create_order(\n        symbol=ticker[\"symbol\"],\n        side=\"SELL\",\n        positionSide=positions[0][\"positionSide\"],\n        type=\"LIMIT\",\n        timeInForce=\"GTC\",\n        quantity=0.1,\n        price=str(round(float(ticker[\"lastPrice\"]) + 1)),\n    )\n    assert_contract_order(futuresClientAsync, order)\n    order = await futuresClientAsync.futures_modify_order(\n        orderid=order[\"orderId\"],\n        symbol=order[\"symbol\"],\n        quantity=0.11,\n        side=order[\"side\"],\n        price=order[\"price\"],\n    )\n    assert_contract_order(futuresClientAsync, order)\n    order = await futuresClientAsync.futures_get_order(\n        symbol=order[\"symbol\"], orderid=order[\"orderId\"]\n    )\n    assert_contract_order(futuresClientAsync, order)\n    order = await futuresClientAsync.futures_cancel_order(\n        orderid=order[\"orderId\"], symbol=order[\"symbol\"]\n    )\n\nasync def test_futures_create_test_order(futuresClientAsync):\n    ticker = await futuresClientAsync.futures_ticker(symbol=\"LTCUSDT\")\n    positions = await futuresClientAsync.futures_position_information(symbol=\"LTCUSDT\")\n    await futuresClientAsync.futures_create_test_order(\n        symbol=ticker[\"symbol\"],\n        side=\"BUY\",\n        positionSide=positions[0][\"positionSide\"],\n        type=\"LIMIT\",\n        timeInForce=\"GTC\",\n        quantity=0.1,\n        price=str(round(float(ticker[\"lastPrice\"]) - 1, 0)),\n    )\n\nasync def test_futures_place_batch_order_and_cancel(futuresClientAsync):\n    ticker = await futuresClientAsync.futures_ticker(symbol=\"LTCUSDT\")\n    positions = await futuresClientAsync.futures_position_information(symbol=\"LTCUSDT\")\n    orders = await futuresClientAsync.futures_place_batch_order(\n        batchOrders=[\n            {\n                \"positionSide\": positions[0][\"positionSide\"],\n                \"price\": str(round(float(ticker[\"lastPrice\"]) + 2, 0)),\n                \"quantity\": \"0.1\",\n                \"side\": \"SELL\",\n                \"symbol\": ticker[\"symbol\"],\n                \"timeInForce\": \"GTC\",\n                \"type\": \"LIMIT\",\n            },\n            {\n                \"side\": \"SELL\",\n                \"type\": \"LIMIT\",\n                \"positionSide\": positions[0][\"positionSide\"],\n                \"price\": str(round(float(ticker[\"lastPrice\"]) + 2, 0)),\n                \"quantity\": \"0.1\",\n                \"symbol\": ticker[\"symbol\"],\n                \"timeInForce\": \"GTC\",\n            },\n        ]\n    )\n    for order in orders:\n        assert_contract_order(futuresClientAsync, order)\n\n    # Cancel using orderidlist\n    order_ids = [order[\"orderId\"] for order in orders][:1]\n    cancelled_orders = await futuresClientAsync.futures_cancel_orders(\n        symbol=orders[0][\"symbol\"], orderidlist=order_ids\n    )\n    for order in cancelled_orders:\n        assert_contract_order(futuresClientAsync, order)\n    # Cancel using origClientOrderIdList\n    client_order_ids = [order[\"clientOrderId\"] for order in orders][1:]\n    cancelled_orders = await futuresClientAsync.futures_cancel_orders(\n        symbol=orders[0][\"symbol\"], origclientorderidlist=client_order_ids\n    )\n    for order in cancelled_orders:\n        assert_contract_order(futuresClientAsync, order)\n\nasync def test_futures_get_open_orders(futuresClientAsync):\n    await futuresClientAsync.futures_get_open_orders()\n\nasync def test_futures_get_all_orders(futuresClientAsync):\n    orders = futuresClientAsync.futures_get_all_orders()\n    print(orders)\n\nasync def test_futures_cancel_all_open_orders(futuresClientAsync):\n    await futuresClientAsync.futures_cancel_all_open_orders(symbol=\"LTCUSDT\")\n\nasync def test_futures_countdown_cancel_all(futuresClientAsync):\n    await futuresClientAsync.futures_countdown_cancel_all(\n        symbol=\"LTCUSDT\", countdownTime=10\n    )\n\nasync def test_futures_account_balance(futuresClientAsync):\n    await futuresClientAsync.futures_account_balance()\n\nasync def test_futures_account(futuresClientAsync):\n    await futuresClientAsync.futures_account()\n\nasync def test_futures_symbol_adl_risk(futuresClientAsync):\n    # Test without symbol (get all)\n    adl_risks = await futuresClientAsync.futures_symbol_adl_risk()\n    assert isinstance(adl_risks, list)\n\n    # Test with specific symbol (if any symbols available)\n    if len(adl_risks) > 0:\n        test_symbol = adl_risks[0][\"symbol\"]\n        adl_risk = await futuresClientAsync.futures_symbol_adl_risk(symbol=test_symbol)\n        assert isinstance(adl_risk, dict)\n        assert \"symbol\" in adl_risk\n        assert \"adlRisk\" in adl_risk\n        assert adl_risk[\"adlRisk\"] in [\"low\", \"medium\", \"high\"]\n        assert adl_risk[\"symbol\"] == test_symbol\n\nasync def test_futures_change_leverage(futuresClientAsync):\n    await futuresClientAsync.futures_change_leverage(symbol=\"LTCUSDT\", leverage=10)\n\nasync def test_futures_change_margin_type(futuresClientAsync):\n    try:\n        await futuresClientAsync.futures_change_margin_type(\n            symbol=\"XRPUSDT\", marginType=\"CROSSED\"\n        )\n    except Exception as e:\n        await futuresClientAsync.futures_change_margin_type(\n            symbol=\"XRPUSDT\", marginType=\"ISOLATED\"\n        )\n\nasync def test_futures_position_margin_history(futuresClientAsync):\n    position = await futuresClientAsync.futures_position_margin_history(\n        symbol=\"LTCUSDT\"\n    )\n\nasync def test_futures_position_information(futuresClientAsync):\n    await futuresClientAsync.futures_position_information()\n\nasync def test_futures_account_trades(futuresClientAsync):\n    await futuresClientAsync.futures_account_trades()\n\nasync def test_futures_income_history(futuresClientAsync):\n    await futuresClientAsync.futures_income_history()\n\nasync def close_all_futures_positions(futuresClientAsync):\n    # Get all open positions\n    positions = await futuresClientAsync.futures_position_information(symbol=\"LTCUSDT\")\n\n    for position in positions:\n        # Check if there is an open position\n        if float(position[\"positionAmt\"]) != 0:\n            symbol = position[\"symbol\"]\n            position_amt = float(position[\"positionAmt\"])\n            side = \"SELL\" if position_amt > 0 else \"BUY\"\n\n            # Place a market order to close the position\n            try:\n                print(f\"Closing position for {symbol}: {position_amt} units\")\n                await futuresClientAsync.futures_create_order(\n                    symbol=symbol, side=side, type=\"market\", quantity=abs(position_amt)\n                )\n                print(f\"Position for {symbol} closed successfully.\")\n            except Exception as e:\n                print(f\"Failed to close position for {symbol}: {e}\")\n\n@pytest.mark.skip(reason=\"Not implemented\")\nasync def test_futures_get_and_change_position_mode(futuresClientAsync):\n    mode = await futuresClientAsync.futures_get_position_mode()\n    await futuresClientAsync.futures_change_position_mode(\n        dualSidePosition=not mode[\"dualSidePosition\"]\n    )\n\n@pytest.mark.skip(reason=\"Not implemented\")\nasync def test_futures_change_multi_assets_mode(futuresClientAsync):\n    await futuresClientAsync.futures_change_multi_assets_mode()\n\nasync def test_futures_get_multi_assets_mode(futuresClientAsync):\n    await futuresClientAsync.futures_get_multi_assets_mode()\n\nasync def test_futures_stream_get_listen_key(futuresClientAsync):\n    await futuresClientAsync.futures_stream_get_listen_key()\n\n@pytest.mark.skip(reason=\"Not implemented\")\nasync def test_futures_stream_close(futuresClientAsync):\n    await futuresClientAsync.futures_stream_close()\n\n# new methods\nasync def test_futures_account_config(futuresClientAsync):\n    await futuresClientAsync.futures_account_config()\n\nasync def test_futures_symbol_config(futuresClientAsync):\n    await futuresClientAsync.futures_symbol_config()\n\n# COIN Futures API\nasync def test_futures_coin_ping(futuresClientAsync):\n    await futuresClientAsync.futures_coin_ping()\n\nasync def test_futures_coin_time(futuresClientAsync):\n    await futuresClientAsync.futures_coin_time()\n\nasync def test_futures_coin_exchange_info(futuresClientAsync):\n    await futuresClientAsync.futures_coin_exchange_info()\n\nasync def test_futures_coin_order_book(futuresClientAsync):\n    order_book = await futuresClientAsync.futures_coin_order_book(symbol=\"BTCUSD_PERP\")\n    assert_ob(order_book)\n\nasync def test_futures_coin_recent_trades(futuresClientAsync):\n    await futuresClientAsync.futures_coin_recent_trades(symbol=\"BTCUSD_PERP\")\n\nasync def test_futures_coin_historical_trades(futuresClientAsync):\n    await futuresClientAsync.futures_coin_historical_trades(symbol=\"BTCUSD_PERP\")\n\n@pytest.mark.skip(reason=\"Not implemented\")\nasync def test_futures_coin_aggregate_trades(futuresClientAsync):\n    await futuresClientAsync.futures_coin_aggregate_trades(symbol=\"BTCUSD_PERP\")\n\nasync def test_futures_coin_klines(futuresClientAsync):\n    await futuresClientAsync.futures_coin_klines(symbol=\"BTCUSD_PERP\", interval=\"1h\")\n\nasync def test_futures_coin_continous_klines(futuresClientAsync):\n    await futuresClientAsync.futures_coin_continous_klines(\n        pair=\"BTCUSD\", contractType=\"PERPETUAL\", interval=\"1h\"\n    )\n\nasync def test_futures_coin_index_price_klines(futuresClientAsync):\n    await futuresClientAsync.futures_coin_index_price_klines(\n        pair=\"BTCUSD\", interval=\"1m\"\n    )\n\nasync def test_futures_coin_mark_price_klines(futuresClientAsync):\n    await futuresClientAsync.futures_coin_mark_price_klines(\n        symbol=\"BTCUSD_PERP\", interval=\"1m\"\n    )\n\nasync def test_futures_coin_mark_price(futuresClientAsync):\n    await futuresClientAsync.futures_coin_mark_price()\n\n@pytest.mark.skip(reason=\"Giving unknwon error from binance\")\nasync def test_futures_coin_funding_rate(futuresClientAsync):\n    await futuresClientAsync.futures_coin_funding_rate(symbol=\"BTCUSD_PERP\")\n\nasync def test_futures_coin_ticker(futuresClientAsync):\n    await futuresClientAsync.futures_coin_ticker()\n\nasync def test_futures_coin_symbol_ticker(futuresClientAsync):\n    await futuresClientAsync.futures_coin_symbol_ticker()\n\nasync def test_futures_coin_orderbook_ticker(futuresClientAsync):\n    await futuresClientAsync.futures_coin_orderbook_ticker()\n\nasync def test_futures_coin_index_index_price_constituents(futuresClientAsync):\n    await futuresClientAsync.futures_coin_index_price_constituents(symbol=\"BTCUSD\")\n\n@pytest.mark.skip(reason=\"Not implemented\")\nasync def test_futures_coin_liquidation_orders(futuresClientAsync):\n    await futuresClientAsync.futures_coin_liquidation_orders()\n\nasync def test_futures_coin_open_interest(futuresClientAsync):\n    await futuresClientAsync.futures_coin_open_interest(symbol=\"BTCUSD_PERP\")\n\n@pytest.mark.skip(reason=\"Not implemented\")\nasync def test_futures_coin_open_interest_hist(futuresClientAsync):\n    await futuresClientAsync.futures_coin_open_interest_hist(symbol=\"BTCUSD_PERP\")\n\nasync def test_futures_coin_leverage_bracket(futuresClientAsync):\n    await futuresClientAsync.futures_coin_leverage_bracket()\n\n@pytest.mark.skip(reason=\"Not implemented\")\nasync def test_futures_coin_create_order(futuresClientAsync):\n    positions = await futuresClientAsync.futures_coin_position_information()\n    ticker = await futuresClientAsync.futures_coin_ticker(symbol=positions[0][\"symbol\"])\n    order = await futuresClientAsync.futures_coin_create_order(\n        symbol=positions[0][\"symbol\"],\n        side=\"BUY\",\n        type=\"LIMIT\",\n        timeInForce=\"GTC\",\n        quantity=1,\n        price=str(round(float(ticker[0][\"lastPrice\"]) - 1, 0)),\n    )\n    assert_contract_order(futuresClientAsync, order)\n    order = await futuresClientAsync.futures_modify_order(\n        orderid=order[\"orderId\"],\n        symbol=order[\"symbol\"],\n        quantity=0.11,\n        side=order[\"side\"],\n        price=order[\"price\"],\n    )\n    assert_contract_order(futuresClientAsync, order)\n    order = await futuresClientAsync.futures_get_order(\n        symbol=order[\"symbol\"], orderid=order[\"orderId\"]\n    )\n    assert_contract_order(futuresClientAsync, order)\n    order = await futuresClientAsync.futures_cancel_order(\n        orderid=order[\"orderId\"], symbol=order[\"symbol\"]\n    )\n\n@pytest.mark.skip(reason=\"Not implemented\")\nasync def test_futures_coin_place_batch_order(futuresClientAsync):\n    await futuresClientAsync.futures_coin_place_batch_order()\n\n@pytest.mark.skip(reason=\"Not implemented\")\nasync def test_futures_coin_get_order(futuresClientAsync):\n    await futuresClientAsync.futures_coin_get_order()\n\nasync def test_futures_coin_get_open_orders(futuresClientAsync):\n    await futuresClientAsync.futures_coin_get_open_orders()\n\n@pytest.mark.skip(reason=\"Not implemented\")\nasync def test_futures_coin_get_all_orders(futuresClientAsync):\n    await futuresClientAsync.futures_coin_get_all_orders()\n\n@pytest.mark.skip(reason=\"Not implemented\")\nasync def test_futures_coin_cancel_order(futuresClientAsync):\n    await futuresClientAsync.futures_coin_cancel_order()\n\nasync def test_futures_coin_cancel_all_open_orders(futuresClientAsync):\n    await futuresClientAsync.futures_coin_cancel_all_open_orders(symbol=\"BTCUSD_PERP\")\n\n@pytest.mark.skip(reason=\"Not implemented\")\nasync def test_futures_coin_cancel_orders(futuresClientAsync):\n    await futuresClientAsync.futures_coin_cancel_orders()\n\nasync def test_futures_coin_account_balance(futuresClientAsync):\n    await futuresClientAsync.futures_coin_account_balance()\n\nasync def test_futures_coin_account(futuresClientAsync):\n    await futuresClientAsync.futures_coin_account()\n\n@pytest.mark.skip(reason=\"Not implemented\")\nasync def test_futures_coin_change_leverage(futuresClientAsync):\n    await futuresClientAsync.futures_coin_change_leverage(symbol=\"XRPUSDT\", leverage=10)\n\n@pytest.mark.skip(reason=\"Not implemented\")\nasync def test_futures_coin_change_margin_type(futuresClientAsync):\n    await futuresClientAsync.futures_coin_change_margin_type()\n\n@pytest.mark.skip(reason=\"Not implemented\")\nasync def test_futures_coin_change_position_margin(futuresClientAsync):\n    await futuresClientAsync.futures_coin_change_position_margin()\n\n@pytest.mark.skip(reason=\"Not implemented\")\nasync def test_futures_coin_position_margin_history(futuresClientAsync):\n    await futuresClientAsync.futures_coin_position_margin_history()\n\nasync def test_futures_coin_position_information(futuresClientAsync):\n    await futuresClientAsync.futures_coin_position_information()\n\n@pytest.mark.skip(reason=\"Not implemented\")\nasync def test_futures_coin_account_trades(futuresClientAsync):\n    await futuresClientAsync.futures_coin_account_trades()\n\n@pytest.mark.skip(reason=\"Not implemented\")\nasync def test_futures_coin_income_history(futuresClientAsync):\n    await futuresClientAsync.futures_coin_income_history()\n\n@pytest.mark.skip(reason=\"Not implemented\")\nasync def test_futures_coin_change_position_mode(futuresClientAsync):\n    await futuresClientAsync.futures_coin_change_position_mode()\n\nasync def test_futures_coin_get_position_mode(futuresClientAsync):\n    await futuresClientAsync.futures_coin_get_position_mode()\n\nasync def test_futures_coin_stream_close(futuresClientAsync):\n    listen_key = await futuresClientAsync.futures_coin_stream_get_listen_key()\n    await futuresClientAsync.futures_coin_stream_close(listenKey=listen_key)\n\n@pytest.mark.skip(reason=\"No sandbox support\")\nasync def test_futures_coin_account_order_history_download(futuresClientAsync):\n    await futuresClientAsync.futures_coin_account_order_download()\n\n@pytest.mark.skip(reason=\"No sandbox support\")\nasync def test_futures_coin_account_order_download_id(futuresClientAsync):\n    await futuresClientAsync.futures_coin_account_order_download_link(downloadId=\"123\")\n\n@pytest.mark.skip(reason=\"No sandbox support\")\nasync def test_futures_coin_account_trade_history_download(futuresClientAsync):\n    await futuresClientAsync.futures_coin_account_trade_history_download()\n\n@pytest.mark.skip(reason=\"No sandbox support\")\nasync def test_futures_coin_account_trade_download_id(futuresClientAsync):\n    await futuresClientAsync.futures_coin_account_trade_history_download_link(\n        downloadId=\"123\"\n    )\n\n\n# Algo Orders (Conditional Orders) Async Tests\n\n\nasync def test_futures_create_algo_order_async(futuresClientAsync):\n    \"\"\"Test creating an algo/conditional order async\"\"\"\n    ticker = await futuresClientAsync.futures_ticker(symbol=\"LTCUSDT\")\n    positions = await futuresClientAsync.futures_position_information(symbol=\"LTCUSDT\")\n    order = await futuresClientAsync.futures_create_algo_order(\n        symbol=ticker[\"symbol\"],\n        side=\"BUY\",\n        positionSide=positions[0][\"positionSide\"],\n        type=\"STOP_MARKET\",\n        algoType=\"CONDITIONAL\",\n        quantity=1,\n        triggerPrice=1000,\n    )\n    assert order[\"symbol\"] == ticker[\"symbol\"]\n    assert \"algoId\" in order\n    # Clean up\n    await futuresClientAsync.futures_cancel_algo_order(\n        symbol=ticker[\"symbol\"], algoId=order[\"algoId\"]\n    )\n\n\nasync def test_futures_create_order_auto_routes_conditional_async(futuresClientAsync):\n    \"\"\"Test that futures_create_order automatically routes conditional orders async\"\"\"\n    ticker = await futuresClientAsync.futures_ticker(symbol=\"LTCUSDT\")\n    positions = await futuresClientAsync.futures_position_information(symbol=\"LTCUSDT\")\n    order = await futuresClientAsync.futures_create_order(\n        symbol=ticker[\"symbol\"],\n        side=\"BUY\",\n        positionSide=positions[0][\"positionSide\"],\n        type=\"TAKE_PROFIT_MARKET\",\n        quantity=1,\n        stopPrice=10,\n    )\n    assert order[\"symbol\"] == ticker[\"symbol\"]\n    assert \"algoId\" in order\n    # Clean up\n    await futuresClientAsync.futures_cancel_algo_order(\n        symbol=ticker[\"symbol\"], algoId=order[\"algoId\"]\n    )\n\n\nasync def test_futures_get_algo_order_async(futuresClientAsync):\n    \"\"\"Test getting a specific algo order async\"\"\"\n    ticker = await futuresClientAsync.futures_ticker(symbol=\"LTCUSDT\")\n    positions = await futuresClientAsync.futures_position_information(symbol=\"LTCUSDT\")\n    order = await futuresClientAsync.futures_create_algo_order(\n        symbol=ticker[\"symbol\"],\n        side=\"BUY\",\n        positionSide=positions[0][\"positionSide\"],\n        type=\"STOP_MARKET\",\n        algoType=\"CONDITIONAL\",\n        quantity=1,\n        triggerPrice=1000,\n    )\n    algo_id = order[\"algoId\"]\n    fetched_order = await futuresClientAsync.futures_get_algo_order(\n        symbol=ticker[\"symbol\"], algoId=algo_id\n    )\n    assert fetched_order[\"algoId\"] == algo_id\n    # Clean up\n    await futuresClientAsync.futures_cancel_algo_order(symbol=ticker[\"symbol\"], algoId=algo_id)\n\n\nasync def test_futures_get_all_algo_orders_async(futuresClientAsync):\n    \"\"\"Test getting all algo orders history async\"\"\"\n    orders = await futuresClientAsync.futures_get_all_algo_orders(symbol=\"LTCUSDT\")\n    assert isinstance(orders, list)\n\n\nasync def test_futures_get_open_algo_orders_async(futuresClientAsync):\n    \"\"\"Test getting open algo orders async\"\"\"\n    orders = await futuresClientAsync.futures_get_open_algo_orders(symbol=\"LTCUSDT\")\n    assert isinstance(orders, list)\n\n\nasync def test_futures_cancel_algo_order_async(futuresClientAsync):\n    \"\"\"Test canceling an algo order async\"\"\"\n    ticker = await futuresClientAsync.futures_ticker(symbol=\"LTCUSDT\")\n    positions = await futuresClientAsync.futures_position_information(symbol=\"LTCUSDT\")\n    order = await futuresClientAsync.futures_create_algo_order(\n        symbol=ticker[\"symbol\"],\n        side=\"BUY\",\n        positionSide=positions[0][\"positionSide\"],\n        type=\"STOP_MARKET\",\n        algoType=\"CONDITIONAL\",\n        quantity=1,\n        triggerPrice=1000,\n    )\n    algo_id = order[\"algoId\"]\n    result = await futuresClientAsync.futures_cancel_algo_order(\n        symbol=ticker[\"symbol\"], algoId=algo_id\n    )\n    assert result[\"algoId\"] == algo_id\n\n\nasync def test_futures_cancel_all_algo_open_orders_async(futuresClientAsync):\n    \"\"\"Test canceling all open algo orders async\"\"\"\n    result = await futuresClientAsync.futures_cancel_all_algo_open_orders(symbol=\"LTCUSDT\")\n    assert \"code\" in result or \"msg\" in result\n\n\nasync def test_futures_create_algo_order_with_price_protect_async(futuresClientAsync):\n    \"\"\"Test creating an algo order with priceProtect parameter async\"\"\"\n    ticker = await futuresClientAsync.futures_ticker(symbol=\"LTCUSDT\")\n    positions = await futuresClientAsync.futures_position_information(symbol=\"LTCUSDT\")\n    order = await futuresClientAsync.futures_create_algo_order(\n        symbol=ticker[\"symbol\"],\n        side=\"BUY\",\n        positionSide=positions[0][\"positionSide\"],\n        type=\"STOP_MARKET\",\n        algoType=\"CONDITIONAL\",\n        quantity=1,\n        triggerPrice=1000,\n        priceProtect=\"TRUE\",\n    )\n    assert order[\"symbol\"] == ticker[\"symbol\"]\n    assert \"algoId\" in order\n    assert order[\"priceProtect\"] is True\n    # Clean up\n    await futuresClientAsync.futures_cancel_algo_order(\n        symbol=ticker[\"symbol\"], algoId=order[\"algoId\"]\n    )\n\n\n@pytest.mark.skip(reason=\"TRAILING_STOP_MARKET with activatePrice may not be fully supported in testnet environment\")\nasync def test_futures_create_algo_order_trailing_stop_async(futuresClientAsync):\n    \"\"\"Test creating a TRAILING_STOP_MARKET algo order with activatePrice and callbackRate async\"\"\"\n    ticker = await futuresClientAsync.futures_ticker(symbol=\"LTCUSDT\")\n    positions = await futuresClientAsync.futures_position_information(symbol=\"LTCUSDT\")\n    current_price = float(ticker[\"lastPrice\"])\n    \n    order = await futuresClientAsync.futures_create_algo_order(\n        symbol=ticker[\"symbol\"],\n        side=\"SELL\",\n        positionSide=positions[0][\"positionSide\"],\n        type=\"TRAILING_STOP_MARKET\",\n        algoType=\"CONDITIONAL\",\n        quantity=1,\n        activatePrice=str(current_price * 1.1),\n        callbackRate=\"1.0\",\n    )\n    assert order[\"symbol\"] == ticker[\"symbol\"]\n    assert \"algoId\" in order\n    # Clean up\n    await futuresClientAsync.futures_cancel_algo_order(\n        symbol=ticker[\"symbol\"], algoId=order[\"algoId\"]\n    )\n\n\nasync def test_futures_create_algo_order_with_stp_mode_async(futuresClientAsync):\n    \"\"\"Test creating an algo order with selfTradePreventionMode async\"\"\"\n    ticker = await futuresClientAsync.futures_ticker(symbol=\"LTCUSDT\")\n    positions = await futuresClientAsync.futures_position_information(symbol=\"LTCUSDT\")\n    order = await futuresClientAsync.futures_create_algo_order(\n        symbol=ticker[\"symbol\"],\n        side=\"SELL\",\n        positionSide=positions[0][\"positionSide\"],\n        type=\"TAKE_PROFIT\",\n        algoType=\"CONDITIONAL\",\n        quantity=1,\n        price=10000,\n        triggerPrice=10000,\n        timeInForce=\"GTC\",\n        selfTradePreventionMode=\"EXPIRE_MAKER\",\n    )\n    assert order[\"symbol\"] == ticker[\"symbol\"]\n    assert \"algoId\" in order\n    assert order[\"selfTradePreventionMode\"] == \"EXPIRE_MAKER\"\n    # Clean up\n    await futuresClientAsync.futures_cancel_algo_order(\n        symbol=ticker[\"symbol\"], algoId=order[\"algoId\"]\n    )\n\n\nasync def test_futures_create_algo_order_with_price_match_async(futuresClientAsync):\n    \"\"\"Test creating an algo order with priceMatch parameter async\"\"\"\n    ticker = await futuresClientAsync.futures_ticker(symbol=\"LTCUSDT\")\n    positions = await futuresClientAsync.futures_position_information(symbol=\"LTCUSDT\")\n    order = await futuresClientAsync.futures_create_algo_order(\n        symbol=ticker[\"symbol\"],\n        side=\"SELL\",\n        positionSide=positions[0][\"positionSide\"],\n        type=\"TAKE_PROFIT\",\n        algoType=\"CONDITIONAL\",\n        quantity=1,\n        triggerPrice=10000,\n        timeInForce=\"GTC\",\n        priceMatch=\"OPPONENT\",\n    )\n    assert order[\"symbol\"] == ticker[\"symbol\"]\n    assert \"algoId\" in order\n    assert order[\"priceMatch\"] == \"OPPONENT\"\n    # Clean up\n    await futuresClientAsync.futures_cancel_algo_order(\n        symbol=ticker[\"symbol\"], algoId=order[\"algoId\"]\n    )\n\n\nasync def test_futures_create_algo_order_with_new_order_resp_type_async(futuresClientAsync):\n    \"\"\"Test creating an algo order with newOrderRespType parameter async\"\"\"\n    ticker = await futuresClientAsync.futures_ticker(symbol=\"LTCUSDT\")\n    positions = await futuresClientAsync.futures_position_information(symbol=\"LTCUSDT\")\n    order = await futuresClientAsync.futures_create_algo_order(\n        symbol=ticker[\"symbol\"],\n        side=\"BUY\",\n        positionSide=positions[0][\"positionSide\"],\n        type=\"STOP_MARKET\",\n        algoType=\"CONDITIONAL\",\n        quantity=1,\n        triggerPrice=1000,\n        newOrderRespType=\"RESULT\",\n    )\n    assert order[\"symbol\"] == ticker[\"symbol\"]\n    assert \"algoId\" in order\n    assert \"algoStatus\" in order\n    # Clean up\n    await futuresClientAsync.futures_cancel_algo_order(\n        symbol=ticker[\"symbol\"], algoId=order[\"algoId\"]\n    )\n\n\nasync def test_futures_create_algo_order_with_working_type_async(futuresClientAsync):\n    \"\"\"Test creating an algo order with workingType parameter async\"\"\"\n    ticker = await futuresClientAsync.futures_ticker(symbol=\"LTCUSDT\")\n    positions = await futuresClientAsync.futures_position_information(symbol=\"LTCUSDT\")\n    order = await futuresClientAsync.futures_create_algo_order(\n        symbol=ticker[\"symbol\"],\n        side=\"BUY\",\n        positionSide=positions[0][\"positionSide\"],\n        type=\"STOP_MARKET\",\n        algoType=\"CONDITIONAL\",\n        quantity=1,\n        triggerPrice=1000,\n        workingType=\"MARK_PRICE\",\n    )\n    assert order[\"symbol\"] == ticker[\"symbol\"]\n    assert \"algoId\" in order\n    assert order[\"workingType\"] == \"MARK_PRICE\"\n    # Clean up\n    await futuresClientAsync.futures_cancel_algo_order(\n        symbol=ticker[\"symbol\"], algoId=order[\"algoId\"]\n    )\n\n"
  },
  {
    "path": "tests/test_async_client_gift_card copy.py",
    "content": "import pytest\n\npytestmark = [pytest.mark.gift_card, pytest.mark.asyncio]\n\n\nasync def test_gift_card_fetch_token_limit(liveClientAsync):\n    await liveClientAsync.gift_card_fetch_token_limit(baseToken=\"BUSD\")\n\n\nasync def test_gift_card_fetch_rsa_public_key(liveClientAsync):\n    await liveClientAsync.gift_card_fetch_rsa_public_key()\n\n\nasync def test_gift_card_create_verify_and_redeem(liveClientAsync):\n    # create a gift card\n    response = await liveClientAsync.gift_card_create(token=\"USDT\", amount=1.0)\n    assert response[\"data\"][\"referenceNo\"] is not None\n    assert response[\"data\"][\"code\"] is not None\n    # verify the gift card\n    response = await liveClientAsync.gift_card_verify(\n        referenceNo=response[\"data\"][\"referenceNo\"]\n    )\n    assert response[\"data\"][\"valid\"] == \"SUCCESS\"\n    # redeem the gift card\n    redeem_response = await liveClientAsync.gift_card_redeem(\n        code=response[\"data\"][\"code\"],\n    )\n    assert response[\"data\"][\"referenceNo\"] == redeem_response[\"data\"][\"referenceNo\"]\n\n\nasync def test_gift_card_create_dual_token_and_redeem(liveClientAsync):\n    response = await liveClientAsync.gift_card_create_dual_token(\n        baseToken=\"USDT\", faceToken=\"BNB\", baseTokenAmount=1.0\n    )\n    assert response[\"data\"][\"referenceNo\"] is not None\n    assert response[\"data\"][\"code\"] is not None\n    # verify the gift card\n    response = await liveClientAsync.gift_card_verify(\n        referenceNo=response[\"data\"][\"referenceNo\"]\n    )\n    assert response[\"data\"][\"valid\"] == \"SUCCESS\"\n    # redeem the gift card\n    redeem_response = await liveClientAsync.gift_card_redeem(\n        code=response[\"data\"][\"code\"],\n    )\n    assert response[\"data\"][\"referenceNo\"] == redeem_response[\"data\"][\"referenceNo\"]\n"
  },
  {
    "path": "tests/test_async_client_margin.py",
    "content": "import pytest\n\npytestmark = [pytest.mark.margin, pytest.mark.asyncio]\n\nasync def test_margin__get_account_status(asyncClient):\n    await asyncClient.get_account_status()\n\nasync def test_margin_get_account_api_trading_status(asyncClient):\n    await asyncClient.get_account_api_trading_status()\n\nasync def test_margin_get_account_api_permissions(asyncClient):\n    await asyncClient.get_account_api_permissions()\n\nasync def test_margin_get_dust_assets(asyncClient):\n    await asyncClient.get_dust_assets()\n\nasync def test_margin_get_dust_log(asyncClient):\n    await asyncClient.test_get_dust_log()\n\nasync def test_margin_transfer_dust(asyncClient):\n    await asyncClient.transfer_dust()\n\nasync def test_margin_get_asset_dividend_history(asyncClient):\n    await asyncClient.get_asset_dividend_history()\n\nasync def test_margin_make_universal_transfer(asyncClient):\n    await asyncClient.make_universal_transfer()\n\nasync def test_margin_query_universal_transfer_history(asyncClient):\n    await asyncClient.query_universal_transfer_history()\n\nasync def test_margin_get_trade_fee(asyncClient):\n    await asyncClient.get_trade_fee()\n\nasync def test_margin_get_asset_details(asyncClient):\n    await asyncClient.get_asset_details()\n\nasync def test_margin_get_spot_delist_schedule(asyncClient):\n    await asyncClient.get_spot_delist_schedule()\n\n# Withdraw Endpoints\n\nasync def test_margin_withdraw(asyncClient):\n    await asyncClient.withdraw()\n\nasync def test_margin_get_deposit_history(asyncClient):\n    await asyncClient.get_deposit_history()\n\nasync def test_margin_get_withdraw_history(asyncClient):\n    await asyncClient.get_withdraw_history()\n\nasync def test_margin_get_withdraw_history_id(asyncClient):\n    await asyncClient.get_withdraw_history_id()\n\nasync def test_margin_get_deposit_address(asyncClient):\n    await asyncClient.get_deposit_address()\n\n# Margin Trading Endpoints\n\nasync def test_margin_get_margin_account(asyncClient):\n    await asyncClient.get_margin_account()\n\nasync def test_margin_get_isolated_margin_account(asyncClient):\n    await asyncClient.get_isolated_margin_account()\n\nasync def test_margin_enable_isolated_margin_account(asyncClient):\n    await asyncClient.enable_isolated_margin_account()\n\nasync def test_margin_disable_isolated_margin_account(asyncClient):\n    await asyncClient.disable_isolated_margin_account()\n\nasync def test_margin_get_enabled_isolated_margin_account_limit(asyncClient):\n    await asyncClient.get_enabled_isolated_margin_account_limit()\n\nasync def test_margin_get_margin_dustlog(asyncClient):\n    await asyncClient.get_margin_dustlog()\n\nasync def test_margin_get_margin_dust_assets(asyncClient):\n    await asyncClient.get_margin_dust_assets()\n\nasync def test_margin_transfer_margin_dust(asyncClient):\n    await asyncClient.transfer_margin_dust()\n\nasync def test_margin_get_cross_margin_collateral_ratio(asyncClient):\n    await asyncClient.get_cross_margin_collateral_ratio()\n\nasync def test_margin_get_small_liability_exchange_assets(asyncClient):\n    await asyncClient.get_small_liability_exchange_assets()\n\nasync def test_margin_exchange_small_liability_assets(asyncClient):\n    await asyncClient.exchange_small_liability_assets()\n\nasync def test_margin_get_small_liability_exchange_history(asyncClient):\n    await asyncClient.get_small_liability_exchange_history()\n\nasync def test_margin_get_future_hourly_interest_rate(asyncClient):\n    await asyncClient.get_future_hourly_interest_rate()\n\nasync def test_margin_get_margin_capital_flow(asyncClient):\n    await asyncClient.get_margin_capital_flow()\n\nasync def test_margin_get_margin_asset(asyncClient):\n    await asyncClient.get_margin_asset()\n\nasync def test_margin_get_margin_symbol(asyncClient):\n    await asyncClient.get_margin_symbol()\n\nasync def test_margin_get_margin_all_assets(asyncClient):\n    await asyncClient.get_margin_all_assets()\n\nasync def test_margin_get_margin_all_pairs(asyncClient):\n    await asyncClient.get_margin_all_pairs()\n\nasync def test_margin_create_isolated_margin_account(asyncClient):\n    await asyncClient.create_isolated_margin_account()\n\nasync def test_margin_get_isolated_margin_symbol(asyncClient):\n    await asyncClient.get_isolated_margin_symbol()\n\nasync def test_margin_get_all_isolated_margin_symbols(asyncClient):\n    await asyncClient.get_all_isolated_margin_symbols()\n\nasync def test_margin_get_isolated_margin_fee_data(asyncClient):\n    await asyncClient.get_isolated_margin_fee_data()\n\nasync def test_margin_get_isolated_margin_tier_data(asyncClient):\n    await asyncClient.get_isolated_margin_tier_data()\n\nasync def test_margin_margin_manual_liquidation(asyncClient):\n    await asyncClient.margin_manual_liquidation()\n\nasync def test_margin_toggle_bnb_burn_spot_margin(asyncClient):\n    await asyncClient.toggle_bnb_burn_spot_margin()\n\nasync def test_margin_get_bnb_burn_spot_margin(asyncClient):\n    await asyncClient.get_bnb_burn_spot_margin()\n\nasync def test_margin_get_margin_price_index(asyncClient):\n    await asyncClient.get_margin_price_index()\n\nasync def test_margin_transfer_margin_to_spot(asyncClient):\n    await asyncClient.transfer_margin_to_spot()\n\nasync def test_margin_transfer_spot_to_margin(asyncClient):\n    await asyncClient.transfer_spot_to_margin()\n\nasync def test_margin_transfer_isolated_margin_to_spot(asyncClient):\n    await asyncClient.transfer_isolated_margin_to_spot()\n\nasync def test_margin_transfer_spot_to_isolated_margin(asyncClient):\n    await asyncClient.transfer_spot_to_isolated_margin()\n\nasync def test_margin_get_isolated_margin_tranfer_history(asyncClient):\n    await asyncClient.get_isolated_margin_tranfer_history()\n\nasync def test_margin_create_margin_loan(asyncClient):\n    await asyncClient.create_margin_loan()\n\nasync def test_margin_repay_margin_loan(asyncClient):\n    await asyncClient.repay_margin_loan()\n\nasync def create_margin_ordertest_(asyncClient):\n    await asyncClient.create_margin_order()\n\nasync def test_margin_cancel_margin_order(asyncClient):\n    await asyncClient.cancel_margin_order()\n\nasync def test_margin_set_margin_max_leverage(asyncClient):\n    await asyncClient.set_margin_max_leverage()\n\nasync def test_margin_get_margin_transfer_history(asyncClient):\n    await asyncClient.get_margin_transfer_history()\n\nasync def test_margin_get_margin_loan_details(asyncClient):\n    await asyncClient.get_margin_loan_details()\n\nasync def test_margin_get_margin_repay_details(asyncClient):\n    await asyncClient.get_margin_repay_details()\n\nasync def test_margin_get_cross_margin_data(asyncClient):\n    await asyncClient.get_cross_margin_data()\n\nasync def test_margin_get_margin_interest_history(asyncClient):\n    await asyncClient.get_margin_interest_history()\n\nasync def test_margin_get_margin_force_liquidation_rec(asyncClient):\n    await asyncClient.get_margin_force_liquidation_rec()\n\nasync def test_margin_get_margin_order(asyncClient):\n    await asyncClient.get_margin_order()\n\nasync def test_margin_get_open_margin_orders(asyncClient):\n    await asyncClient.get_open_margin_orders()\n\nasync def test_margin_get_all_margin_orders(asyncClient):\n    await asyncClient.get_all_margin_orders()\n\nasync def test_margin_get_margin_trades(asyncClient):\n    await asyncClient.get_margin_trades()\n\nasync def test_margin_get_max_margin_loan(asyncClient):\n    await asyncClient.get_max_margin_loan()\n\nasync def test_margin_get_max_margin_transfer(asyncClient):\n    await asyncClient.get_max_margin_transfer()\n\nasync def test_margin_get_margin_delist_schedule(asyncClient):\n    await asyncClient.get_margin_delist_schedule()\n\n# Margin OCO\n\nasync def test_margin_create_margin_oco_order(asyncClient):\n    await asyncClient.create_margin_oco_order()\n\nasync def test_margin_cancel_margin_oco_order(asyncClient):\n    await asyncClient.cancel_margin_oco_order()\n\nasync def test_margin_get_margin_oco_order(asyncClient):\n    await asyncClient.get_margin_oco_order()\n\nasync def test_margin_get_open_margin_oco_orders(asyncClient):\n    await asyncClient.get_open_margin_oco_orders()\n\n# Cross-margin\n\nasync def test_margin_margin_stream_get_listen_key(asyncClient):\n    await asyncClient.margin_stream_get_listen_key()\n\nasync def test_margin_margin_stream_close(asyncClient):\n    await asyncClient.margin_stream_close()\n\n# Isolated margin\n\nasync def test_margin_isolated_margin_stream_get_listen_key(asyncClient):\n    await asyncClient.isolated_margin_stream_get_listen_key()\n\nasync def test_margin_isolated_margin_stream_close(asyncClient):\n    await asyncClient.isolated_margin_stream_close()\n\n# Simple Earn Endpoints\n\nasync def test_margin_get_simple_earn_flexible_product_list(asyncClient):\n    await asyncClient.get_simple_earn_flexible_product_list()\n\nasync def test_margin_get_simple_earn_locked_product_list(asyncClient):\n    await asyncClient.get_simple_earn_locked_product_list()\n\nasync def test_margin_subscribe_simple_earn_flexible_product(asyncClient):\n    await asyncClient.subscribe_simple_earn_flexible_product()\n\nasync def test_margin_subscribe_simple_earn_locked_product(asyncClient):\n    await asyncClient.subscribe_simple_earn_locked_product()\n\nasync def test_margin_redeem_simple_earn_flexible_product(asyncClient):\n    await asyncClient.redeem_simple_earn_flexible_product()\n\nasync def test_margin_redeem_simple_earn_locked_product(asyncClient):\n    await asyncClient.redeem_simple_earn_locked_product()\n\nasync def test_margin_get_simple_earn_flexible_product_position(asyncClient):\n    await asyncClient.get_simple_earn_flexible_product_position()\n\nasync def test_margin_get_simple_earn_locked_product_position(asyncClient):\n    await asyncClient.get_simple_earn_locked_product_position()\n\nasync def test_margin_get_simple_earn_account(asyncClient):\n    await asyncClient.get_simple_earn_account()\n\n# Lending Endpoints\n\nasync def test_margin_get_fixed_activity_project_list(asyncClient):\n    await asyncClient.get_fixed_activity_project_list()\n\nasync def test_margin_change_fixed_activity_to_daily_position(asyncClient):\n    await asyncClient.change_fixed_activity_to_daily_position()\n\n# Staking Endpoints\n\nasync def test_margin_get_staking_product_list(asyncClient):\n    await asyncClient.get_staking_product_list()\n\nasync def test_margin_purchase_staking_product(asyncClient):\n    await asyncClient.purchase_staking_product()\n\nasync def test_margin_redeem_staking_product(asyncClient):\n    await asyncClient.redeem_staking_product()\n\nasync def test_margin_get_staking_position(asyncClient):\n    await asyncClient.get_staking_position()\n\nasync def test_margin_get_staking_purchase_history(asyncClient):\n    await asyncClient.get_staking_purchase_history()\n\nasync def test_margin_set_auto_staking(asyncClient):\n    await asyncClient.set_auto_staking()\n\nasync def test_margin_get_personal_left_quota(asyncClient):\n    await asyncClient.get_personal_left_quota()\n\n# US Staking Endpoints\n\nasync def test_margin_get_staking_asset_us(asyncClient):\n    await asyncClient.get_staking_asset_us()\n\nasync def test_margin_stake_asset_us(asyncClient):\n    await asyncClient.stake_asset_us()\n\nasync def test_margin_unstake_asset_us(asyncClient):\n    await asyncClient.unstake_asset_us()\n\nasync def test_margin_get_staking_balance_us(asyncClient):\n    await asyncClient.get_staking_balance_us()\n\nasync def test_margin_get_staking_history_us(asyncClient):\n    await asyncClient.get_staking_history_us()\n\nasync def test_margin_get_staking_rewards_history_us(asyncClient):\n    await asyncClient.get_staking_rewards_history_us()\n\n# Sub Accounts\n\nasync def test_margin_get_sub_account_list(asyncClient):\n    await asyncClient.get_sub_account_list()\n\nasync def test_margin_get_sub_account_transfer_history(asyncClient):\n    await asyncClient.get_sub_account_transfer_history()\n\nasync def test_margin_get_sub_account_futures_transfer_history(asyncClient):\n    await asyncClient.get_sub_account_futures_transfer_history()\n\nasync def test_margin_create_sub_account_futures_transfer(asyncClient):\n    await asyncClient.create_sub_account_futures_transfer()\n\nasync def test_margin_get_sub_account_assets(asyncClient):\n    await asyncClient.get_sub_account_assets()\n\nasync def test_margin_query_subaccount_spot_summary(asyncClient):\n    await asyncClient.query_subaccount_spot_summary()\n\nasync def test_margin_get_subaccount_deposit_address(asyncClient):\n    await asyncClient.get_subaccount_deposit_address()\n\nasync def test_margin_get_subaccount_deposit_history(asyncClient):\n    await asyncClient.get_subaccount_deposit_history()\n\nasync def test_margin_get_subaccount_futures_margin_status(asyncClient):\n    await asyncClient.get_subaccount_futures_margin_status()\n\nasync def test_margin_enable_subaccount_margin(asyncClient):\n    await asyncClient.enable_subaccount_margin()\n\nasync def test_margin_get_subaccount_margin_details(asyncClient):\n    await asyncClient.get_subaccount_margin_details()\n\nasync def test_margin_get_subaccount_margin_summary(asyncClient):\n    await asyncClient.get_subaccount_margin_summary()\n\nasync def test_margin_enable_subaccount_futures(asyncClient):\n    await asyncClient.enable_subaccount_futures()\n\nasync def test_margin_get_subaccount_futures_details(asyncClient):\n    await asyncClient.get_subaccount_futures_details()\n\nasync def test_margin_get_subaccount_futures_summary(asyncClient):\n    await asyncClient.get_subaccount_futures_summary()\n\nasync def test_margin_get_subaccount_futures_positionrisk(asyncClient):\n    await asyncClient.get_subaccount_futures_positionrisk()\n\nasync def test_margin_make_subaccount_futures_transfer(asyncClient):\n    await asyncClient.make_subaccount_futures_transfer()\n\nasync def test_margin_make_subaccount_margin_transfer(asyncClient):\n    await asyncClient.make_subaccount_margin_transfer()\n\nasync def test_margin_make_subaccount_to_subaccount_transfer(asyncClient):\n    await asyncClient.make_subaccount_to_subaccount_transfer()\n\nasync def test_margin_make_subaccount_to_master_transfer(asyncClient):\n    await asyncClient.make_subaccount_to_master_transfer()\n\nasync def test_margin_get_subaccount_transfer_history(asyncClient):\n    await asyncClient.get_subaccount_transfer_history()\n\nasync def test_margin_make_subaccount_universal_transfer(asyncClient):\n    await asyncClient.make_subaccount_universal_transfer()\n\nasync def test_margin_get_universal_transfer_history(asyncClient):\n    await asyncClient.get_universal_transfer_history()\n\n# Fiat Endpoints\n\nasync def test_margin_get_fiat_deposit_withdraw_history(asyncClient):\n    await asyncClient.get_fiat_deposit_withdraw_history()\n\nasync def test_margin_get_fiat_payments_history(asyncClient):\n    await asyncClient.get_fiat_payments_history()\n\n# C2C Endpoints\n\nasync def test_margin_get_c2c_trade_history(asyncClient):\n    await asyncClient.get_c2c_trade_history()\n\n# Pay Endpoints\n\nasync def test_margin_get_pay_trade_history(asyncClient):\n    await asyncClient.get_pay_trade_history()\n\n# Convert Endpoints\n\nasync def test_margin_get_convert_trade_history(asyncClient):\n    await asyncClient.get_convert_trade_history()\n\nasync def test_margin_convert_request_quote(asyncClient):\n    await asyncClient.convert_request_quote()\n\nasync def test_margin_convert_accept_quote(asyncClient):\n    await asyncClient.convert_accept_quote()\n"
  },
  {
    "path": "tests/test_async_client_options.py",
    "content": "import pytest\nimport sys\n\npytestmark = [pytest.mark.options, pytest.mark.asyncio, pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")]\n\n@pytest.fixture\ndef options_symbol(liveClient):\n    prices = liveClient.options_price()\n    return prices[0][\"symbol\"]\n\nasync def test_options_ping(liveClientAsync):\n    await liveClientAsync.options_ping()\n\nasync def test_options_time(liveClientAsync):\n    await liveClientAsync.options_time()\n\n@pytest.mark.skip(reason=\"Not implemented\")\nasync def test_options_info(liveClientAsync):\n    await liveClientAsync.options_info()\n\nasync def test_options_exchange_info(liveClientAsync):\n    await liveClientAsync.options_exchange_info()\n\nasync def test_options_index_price(liveClientAsync):\n    await liveClientAsync.options_index_price(underlying=\"BTCUSDT\")\n\nasync def test_options_price(liveClientAsync):\n    prices = await liveClientAsync.options_price()\n\nasync def test_options_mark_price(liveClientAsync):\n    await liveClientAsync.options_mark_price()\n\nasync def test_options_order_book(liveClientAsync, options_symbol):\n    await liveClientAsync.options_order_book(symbol=options_symbol)\n\nasync def test_options_klines(liveClientAsync, options_symbol):\n    await liveClientAsync.options_klines(symbol=options_symbol, interval=\"1m\")\n\nasync def test_options_recent_trades(liveClientAsync, options_symbol):\n    await liveClientAsync.options_recent_trades(symbol=options_symbol)\n\nasync def test_options_historical_trades(liveClientAsync, options_symbol):\n    await liveClientAsync.options_historical_trades(symbol=options_symbol)\n\n# Account and trading interface endpoints\n\n@pytest.mark.skip(reason=\"No sandbox to environmnet to test\")\nasync def test_options_account_info(liveClientAsync):\n    await liveClientAsync.options_account_info()\n\n@pytest.mark.skip(reason=\"No sandbox to environmnet to test\")\nasync def test_options_funds_transfer(liveClientAsync):\n    await liveClientAsync.options_funds_transfer()\n\n@pytest.mark.skip(reason=\"No sandbox to environmnet to test\")\nasync def test_options_positions(liveClientAsync):\n    await liveClientAsync.options_positions()\n\n@pytest.mark.skip(reason=\"No sandbox to environmnet to test\")\nasync def test_options_bill(liveClientAsync):\n    await liveClientAsync.options_bill()\n\n@pytest.mark.skip(reason=\"No sandbox to environmnet to test\")\nasync def test_options_place_order(liveClientAsync):\n    await liveClientAsync.options_place_order()\n\n@pytest.mark.skip(reason=\"No sandbox to environmnet to test\")\nasync def test_test_options_place_batch_order(liveClientAsync):\n    await liveClientAsync.test_options_place_batch_order()\n\n@pytest.mark.skip(reason=\"No sandbox to environmnet to test\")\nasync def test_options_cancel_order(liveClientAsync):\n    await liveClientAsync.options_cancel_order()\n\n@pytest.mark.skip(reason=\"No sandbox to environmnet to test\")\nasync def test_options_cancel_batch_order(liveClientAsync):\n    await liveClientAsync.options_cancel_batch_order()\n\n@pytest.mark.skip(reason=\"No sandbox to environmnet to test\")\nasync def test_options_cancel_all_orders(liveClientAsync):\n    await liveClientAsync.options_cancel_all_orders()\n\n@pytest.mark.skip(reason=\"No sandbox to environmnet to test\")\nasync def test_options_query_order(liveClientAsync):\n    await liveClientAsync.options_query_order()\n\n@pytest.mark.skip(reason=\"No sandbox to environmnet to test\")\nasync def test_options_query_pending_orders(liveClientAsync):\n    await liveClientAsync.options_query_pending_orders()\n\n@pytest.mark.skip(reason=\"No sandbox to environmnet to test\")\nasync def test_options_query_order_history(liveClientAsync):\n    await liveClientAsync.options_query_order_history()\n\n@pytest.mark.skip(reason=\"No sandbox to environmnet to test\")\nasync def test_options_user_trades(liveClientAsync):\n    await liveClientAsync.options_user_trades()\n"
  },
  {
    "path": "tests/test_async_client_portfolio.py",
    "content": "import pytest\n\n# Apply the 'portfolio' mark to all tests in this file\npytestmark = [pytest.mark.portfolio, pytest.mark.asyncio]\n\n\nasync def test_papi_get_balance(client):\n    await client.papi_get_balance()\n\n\nasync def test_papi_get_account(client):\n    await client.papi_get_account()\n\n\nasync def test_papi_get_margin_max_borrowable(client):\n    await client.papi_get_margin_max_borrowable()\n\n\nasync def test_papi_get_margin_max_withdraw(client):\n    await client.papi_get_margin_max_withdraw()\n\n\nasync def test_papi_get_um_position_risk(client):\n    await client.papi_get_um_position_risk()\n\n\nasync def test_papi_get_cm_position_risk(client):\n    await client.papi_get_cm_position_risk()\n\n\nasync def test_papi_set_um_leverage(client):\n    await client.papi_set_um_leverage()\n\n\nasync def test_papi_set_cm_leverage(client):\n    await client.papi_set_cm_leverage()\n\n\nasync def test_papi_change_um_position_side_dual(client):\n    await client.papi_change_um_position_side_dual()\n\n\nasync def test_papi_get_um_position_side_dual(client):\n    await client.papi_get_um_position_side_dual()\n\n\nasync def test_papi_get_cm_position_side_dual(client):\n    await client.papi_get_cm_position_side_dual()\n\n\nasync def test_papi_get_um_leverage_bracket(client):\n    await client.papi_get_um_leverage_bracket()\n\n\nasync def test_papi_get_cm_leverage_bracket(client):\n    await client.papi_get_cm_leverage_bracket()\n\n\nasync def test_papi_get_um_api_trading_status(client):\n    await client.papi_get_um_api_trading_status()\n\n\nasync def test_papi_get_um_comission_rate(client):\n    await client.papi_get_um_comission_rate()\n\n\nasync def test_papi_get_cm_comission_rate(client):\n    await client.papi_get_cm_comission_rate()\n\n\nasync def test_papi_get_margin_margin_loan(client):\n    await client.papi_get_margin_margin_loan()\n\n\nasync def test_papi_get_margin_repay_loan(client):\n    await client.papi_get_margin_repay_loan()\n\n\nasync def test_papi_get_repay_futures_switch(client):\n    await client.papi_get_repay_futures_switch()\n\n\nasync def test_papi_repay_futures_switch(client):\n    await client.papi_repay_futures_switch()\n\n\nasync def test_papi_get_margin_interest_history(client):\n    await client.papi_get_margin_interest_history()\n\n\nasync def test_papi_repay_futures_negative_balance(client):\n    await client.papi_repay_futures_negative_balance()\n\n\nasync def test_papi_get_portfolio_interest_history(client):\n    await client.papi_get_portfolio_interest_history()\n\n\nasync def test_papi_fund_auto_collection(client):\n    await client.papi_fund_auto_collection()\n\n\nasync def test_papi_fund_asset_collection(client):\n    await client.papi_fund_asset_collection()\n\n\nasync def test_papi_bnb_transfer(client):\n    await client.papi_bnb_transfer()\n\n\nasync def test_papi_get_um_income_history(client):\n    await client.papi_get_um_income_history()\n\n\nasync def test_papi_get_cm_income_history(client):\n    await client.papi_get_cm_income_history()\n\n\nasync def test_papi_get_um_account(client):\n    await client.papi_get_um_account()\n\n\nasync def test_papi_get_um_account_v2(client):\n    await client.papi_get_um_account_v2()\n\n\nasync def test_papi_get_cm_account(client):\n    await client.papi_get_cm_account()\n\n\nasync def test_papi_get_um_account_config(client):\n    await client.papi_get_um_account_config()\n\n\nasync def test_papi_get_um_symbol_config(client):\n    await client.papi_get_um_symbol_config()\n\n\nasync def test_papi_get_um_trade_asyn(client):\n    await client.papi_get_um_trade_asyn()\n\n\nasync def test_papi_get_um_trade_asyn_id(client):\n    await client.papi_get_um_trade_asyn_id()\n\n\nasync def test_papi_get_um_order_asyn(client):\n    await client.papi_get_um_order_asyn()\n\n\nasync def test_papi_get_um_order_asyn_id(client):\n    await client.papi_get_um_order_asyn_id()\n\n\nasync def test_papi_get_um_income_asyn(client):\n    await client.papi_get_um_income_asyn()\n\n\nasync def test_papi_get_um_income_asyn_id(client):\n    await client.papi_get_um_income_asyn_id()\n\n\n# Public papi endpoints\n\n\nasync def test_papi_ping(client):\n    await client.papi_ping()\n\n\n# Trade papi endpoints\n\n\nasync def test_papi_create_um_order(client):\n    await client.papi_create_um_order()\n\n\nasync def test_papi_create_um_conditional_order(client):\n    await client.papi_create_um_conditional_order()\n\n\nasync def test_papi_create_cm_order(client):\n    await client.papi_create_cm_order()\n\n\nasync def test_papi_create_cm_conditional_order(client):\n    await client.papi_create_cm_conditional_order()\n\n\nasync def test_papi_create_margin_order(client):\n    await client.papi_create_margin_order()\n\n\nasync def test_papi_margin_loan(client):\n    await client.papi_margin_loan()\n\n\nasync def test_papi_repay_loan(client):\n    await client.papi_repay_loan()\n\n\nasync def test_papi_margin_order_oco(client):\n    await client.papi_margin_order_oco()\n\n\nasync def test_papi_cancel_um_order(client):\n    await client.papi_cancel_um_order()\n\n\nasync def test_papi_cancel_um_all_open_orders(client):\n    await client.papi_cancel_um_all_open_orders()\n\n\nasync def test_papi_cancel_um_conditional_order(client):\n    await client.papi_cancel_um_conditional_order()\n\n\nasync def test_papi_cancel_um_conditional_all_open_orders(client):\n    await client.papi_cancel_um_conditional_all_open_orders()\n\n\nasync def test_papi_cancel_cm_order(client):\n    await client.papi_cancel_cm_order()\n\n\nasync def test_papi_cancel_cm_all_open_orders(client):\n    await client.papi_cancel_cm_all_open_orders()\n\n\nasync def test_papi_cancel_cm_conditional_order(client):\n    await client.papi_cancel_cm_conditional_order()\n\n\nasync def test_papi_cancel_cm_conditional_all_open_orders(client):\n    await client.papi_cancel_cm_conditional_all_open_orders()\n\n\nasync def test_papi_cancel_margin_order(client):\n    await client.papi_cancel_margin_order()\n\n\nasync def test_papi_cancel_margin_order_list(client):\n    await client.papi_cancel_margin_order_list()\n\n\nasync def test_papi_cancel_margin_all_open_orders(client):\n    await client.papi_cancel_margin_all_open_orders()\n\n\nasync def test_papi_modify_um_order(client):\n    await client.papi_modify_um_order()\n\n\nasync def test_papi_modify_cm_order(client):\n    await client.papi_modify_cm_order()\n\n\nasync def test_papi_get_um_order(client):\n    await client.papi_get_um_order()\n\n\nasync def test_papi_get_um_all_orders(client):\n    await client.papi_get_um_all_orders()\n\n\nasync def test_papi_get_um_open_order(client):\n    await client.papi_get_um_open_order()\n\n\nasync def test_papi_get_um_open_orders(client):\n    await client.papi_get_um_open_orders()\n\n\nasync def test_papi_get_um_conditional_all_orders(client):\n    await client.papi_get_um_conditional_all_orders()\n\n\nasync def test_papi_get_um_conditional_open_orders(client):\n    await client.papi_get_um_conditional_open_orders()\n\n\nasync def test_papi_get_um_conditional_open_order(client):\n    await client.papi_get_um_conditional_open_order()\n\n\nasync def test_papi_get_um_conditional_order_history(client):\n    await client.papi_get_um_conditional_order_history()\n\n\nasync def test_papi_get_cm_order(client):\n    await client.papi_get_cm_order()\n\n\nasync def test_papi_get_cm_all_orders(client):\n    await client.papi_get_cm_all_orders()\n\n\nasync def test_papi_get_cm_open_order(client):\n    await client.papi_get_cm_open_order()\n\n\nasync def test_papi_get_cm_open_orders(client):\n    await client.papi_get_cm_open_orders()\n\n\nasync def test_papi_get_cm_conditional_all_orders(client):\n    await client.papi_get_cm_conditional_all_orders()\n\n\nasync def test_papi_get_cm_conditional_open_orders(client):\n    await client.papi_get_cm_conditional_open_orders()\n\n\nasync def test_papi_get_cm_conditional_open_order(client):\n    await client.papi_get_cm_conditional_open_order()\n\n\nasync def test_papi_get_cm_conditional_order_history(client):\n    await client.papi_get_cm_conditional_order_history()\n\n\nasync def test_papi_get_um_force_orders(client):\n    await client.papi_get_um_force_orders()\n\n\nasync def test_papi_get_cm_force_orders(client):\n    await client.papi_get_cm_force_orders()\n\n\nasync def test_papi_get_um_order_amendment(client):\n    await client.papi_get_um_order_amendment()\n\n\nasync def test_papi_get_cm_order_amendment(client):\n    await client.papi_get_cm_order_amendment()\n\n\nasync def test_papi_get_margin_force_orders(client):\n    await client.papi_get_margin_force_orders()\n\n\nasync def test_papi_get_um_user_trades(client):\n    await client.papi_get_um_user_trades()\n\n\nasync def test_papi_get_cm_user_trades(client):\n    await client.papi_get_cm_user_trades()\n\n\nasync def test_papi_get_um_adl_quantile(client):\n    await client.papi_get_um_adl_quantile()\n\n\nasync def test_papi_get_cm_adl_quantile(client):\n    await client.papi_get_cm_adl_quantile()\n\n\nasync def test_papi_set_um_fee_burn(client):\n    await client.papi_set_um_fee_burn()\n\n\nasync def test_papi_get_um_fee_burn(client):\n    await client.papi_get_um_fee_burn()\n\n\nasync def test_papi_get_margin_order(client):\n    await client.papi_get_margin_order()\n\n\nasync def test_papi_get_margin_open_orders(client):\n    await client.papi_get_margin_open_orders()\n\n\nasync def test_papi_get_margin_all_orders(client):\n    await client.papi_get_margin_all_orders()\n\n\nasync def test_papi_get_margin_order_list(client):\n    await client.papi_get_margin_order_list()\n\n\nasync def test_papi_get_margin_all_order_list(client):\n    await client.papi_get_margin_all_order_list()\n\n\nasync def test_papi_get_margin_open_order_list(client):\n    await client.papi_get_margin_open_order_list()\n\n\nasync def test_papi_get_margin_my_trades(client):\n    await client.papi_get_margin_my_trades()\n\n\nasync def test_papi_get_margin_repay_debt(client):\n    await client.papi_get_margin_repay_debt()\n\n\nasync def test_close_connection(client):\n    await client.close_connection()\n"
  },
  {
    "path": "tests/test_async_client_ws_api.py",
    "content": "import pytest\nimport sys\npytestmark = [pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\"), pytest.mark.asyncio()]\n\nasync def test_ws_get_order_book(clientAsync):\n    await clientAsync.ws_get_order_book(symbol=\"BTCUSDT\")\n\nasync def test_ws_get_recent_trades(clientAsync):\n    await clientAsync.ws_get_recent_trades(symbol=\"BTCUSDT\")\n\nasync def test_ws_get_historical_trades(clientAsync):\n    await clientAsync.ws_get_historical_trades(symbol=\"BTCUSDT\")\n\nasync def test_ws_get_aggregate_trades(clientAsync):\n    await clientAsync.ws_get_aggregate_trades(symbol=\"BTCUSDT\")\n\nasync def test_ws_get_klines(clientAsync):\n    await clientAsync.ws_get_klines(symbol=\"BTCUSDT\", interval=\"1m\")\n\nasync def test_ws_get_uiKlines(clientAsync):\n    await clientAsync.ws_get_uiKlines(symbol=\"BTCUSDT\", interval=\"1m\")\n\nasync def test_ws_get_avg_price(clientAsync):\n    await clientAsync.ws_get_avg_price(symbol=\"BTCUSDT\")\n\nasync def test_ws_get_ticker(clientAsync):\n    await clientAsync.ws_get_ticker(symbol=\"BTCUSDT\")\n\nasync def test_ws_get_trading_day_ticker(clientAsync):\n    await clientAsync.ws_get_trading_day_ticker(symbol=\"BTCUSDT\")\n\nasync def test_ws_get_symbol_ticker_window(clientAsync):\n    await clientAsync.ws_get_symbol_ticker_window(symbol=\"BTCUSDT\")\n\nasync def test_ws_get_symbol_ticker(clientAsync):\n    await clientAsync.ws_get_symbol_ticker(symbol=\"BTCUSDT\")\n\nasync def test_ws_get_orderbook_ticker(clientAsync):\n    await clientAsync.ws_get_orderbook_ticker(symbol=\"BTCUSDT\")\n\nasync def test_ws_ping(clientAsync):\n    await clientAsync.ws_ping()\n\nasync def test_ws_get_time(clientAsync):\n    await clientAsync.ws_get_time()\n\nasync def test_ws_get_exchange_info(clientAsync):\n    await clientAsync.ws_get_exchange_info(symbol=\"BTCUSDT\")\n"
  },
  {
    "path": "tests/test_async_client_ws_futures_requests.py",
    "content": "import asyncio\nimport pytest\nimport sys\n\nfrom binance.exceptions import BinanceAPIException, BinanceWebsocketUnableToConnect\nfrom .test_get_order_book import assert_ob\nfrom .test_order import assert_contract_order\n\ntry:\n    from unittest.mock import patch  # Python 3.8+\nexcept ImportError:\n    from asynctest import patch  # Python 3.7\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\n@pytest.mark.asyncio()\nasync def test_ws_futures_get_order_book(futuresClientAsync):\n    orderbook = await futuresClientAsync.ws_futures_get_order_book(symbol=\"BTCUSDT\")\n    assert_ob(orderbook)\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\n@pytest.mark.asyncio\nasync def test_concurrent_ws_futures_get_order_book(futuresClientAsync):\n    symbols = [\"BTCUSDT\", \"ETHUSDT\", \"BNBUSDT\", \"ADAUSDT\"]\n\n    async def get_orderbook(symbol):\n        orderbook = await futuresClientAsync.ws_futures_get_order_book(symbol=symbol)\n        assert_ob(orderbook)\n        return orderbook\n\n    tasks = [get_orderbook(symbol) for symbol in symbols]\n    results = await asyncio.gather(*tasks)\n\n    # Verify results\n    assert len(results) == len(symbols)\n    for orderbook in results:\n        assert_ob(orderbook)\n\n\n@pytest.mark.asyncio()\nasync def test_bad_request(futuresClientAsync):\n    with pytest.raises(BinanceAPIException):\n        await futuresClientAsync.ws_futures_get_order_book()\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\n@pytest.mark.asyncio()\nasync def test_ws_futures_get_all_tickers(futuresClientAsync):\n    await futuresClientAsync.ws_futures_get_all_tickers()\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\n@pytest.mark.asyncio()\nasync def test_ws_futures_get_order_book_ticker(futuresClientAsync):\n    await futuresClientAsync.ws_futures_get_order_book_ticker()\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\n@pytest.mark.asyncio()\nasync def test_ws_futures_create_get_edit_cancel_order_with_orjson(futuresClientAsync):\n    if 'orjson' not in sys.modules:\n        raise ImportError(\"orjson is not available\")\n    \n    ticker = await futuresClientAsync.ws_futures_get_order_book_ticker(symbol=\"LTCUSDT\")\n    positions = await futuresClientAsync.ws_futures_v2_account_position(\n        symbol=\"LTCUSDT\"\n    )\n    order = await futuresClientAsync.ws_futures_create_order(\n        symbol=ticker[\"symbol\"],\n        side=\"SELL\",\n        positionSide=positions[0][\"positionSide\"],\n        type=\"LIMIT\",\n        timeInForce=\"GTC\",\n        quantity=0.1,\n        price=str(float(ticker[\"bidPrice\"]) + 5),\n    )\n    assert_contract_order(futuresClientAsync, order)\n    order = await futuresClientAsync.ws_futures_edit_order(\n        orderid=order[\"orderId\"],\n        symbol=order[\"symbol\"],\n        quantity=0.11,\n        side=order[\"side\"],\n        price=order[\"price\"],\n    )\n    assert_contract_order(futuresClientAsync, order)\n    order = await futuresClientAsync.ws_futures_get_order(\n        symbol=\"LTCUSDT\", orderid=order[\"orderId\"]\n    )\n    assert_contract_order(futuresClientAsync, order)\n    order = await futuresClientAsync.ws_futures_cancel_order(\n        orderid=order[\"orderId\"], symbol=order[\"symbol\"]\n    )\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\n@pytest.mark.asyncio()\nasync def test_ws_futures_create_get_edit_cancel_order_without_orjson(futuresClientAsync):\n    with patch.dict('sys.modules', {'orjson': None}):\n        ticker = await futuresClientAsync.ws_futures_get_order_book_ticker(symbol=\"LTCUSDT\")\n        positions = await futuresClientAsync.ws_futures_v2_account_position(\n            symbol=\"LTCUSDT\"\n        )\n        order = await futuresClientAsync.ws_futures_create_order(\n            symbol=ticker[\"symbol\"],\n            side=\"SELL\",\n            positionSide=positions[0][\"positionSide\"],\n            type=\"LIMIT\",\n            timeInForce=\"GTC\",\n            quantity=0.1,\n            price=str(float(ticker[\"bidPrice\"]) + 5),\n        )\n        assert_contract_order(futuresClientAsync, order)\n        order = await futuresClientAsync.ws_futures_edit_order(\n            orderid=order[\"orderId\"],\n            symbol=order[\"symbol\"],\n            quantity=0.11,\n            side=order[\"side\"],\n            price=order[\"price\"],\n        )\n        assert_contract_order(futuresClientAsync, order)\n        order = await futuresClientAsync.ws_futures_get_order(\n            symbol=\"LTCUSDT\", orderid=order[\"orderId\"]\n        )\n        assert_contract_order(futuresClientAsync, order)\n        order = await futuresClientAsync.ws_futures_cancel_order(\n            orderid=order[\"orderId\"], symbol=order[\"symbol\"]\n        )\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\n@pytest.mark.asyncio()\nasync def test_ws_futures_v2_account_position(futuresClientAsync):\n    await futuresClientAsync.ws_futures_v2_account_position()\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\n@pytest.mark.asyncio()\nasync def test_ws_futures_account_position(futuresClientAsync):\n    await futuresClientAsync.ws_futures_account_position()\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\n@pytest.mark.asyncio()\nasync def test_ws_futures_v2_account_balance(futuresClientAsync):\n    await futuresClientAsync.ws_futures_v2_account_balance()\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\n@pytest.mark.asyncio()\nasync def test_ws_futures_account_balance(futuresClientAsync):\n    await futuresClientAsync.ws_futures_account_balance()\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\n@pytest.mark.asyncio()\nasync def test_ws_futures_v2_account_status(futuresClientAsync):\n    await futuresClientAsync.ws_futures_v2_account_status()\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\n@pytest.mark.asyncio()\nasync def test_ws_futures_account_status(futuresClientAsync):\n    await futuresClientAsync.ws_futures_account_status()\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\n@pytest.mark.asyncio\nasync def test_ws_futures_fail_to_connect(futuresClientAsync):\n    # Close any existing connection first\n    await futuresClientAsync.close_connection()\n\n    # Mock the WebSocket API's connect method to raise an exception\n    with patch.object(futuresClientAsync.ws_future, 'connect', side_effect=ConnectionError(\"Simulated connection failure\")):\n        with pytest.raises(BinanceWebsocketUnableToConnect):\n            await futuresClientAsync.ws_futures_get_order_book(symbol=\"BTCUSDT\")\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\n@pytest.mark.asyncio()\nasync def test_ws_futures_create_cancel_algo_order(futuresClientAsync):\n    \"\"\"Test creating and canceling an algo order via websocket async\"\"\"\n    ticker = await futuresClientAsync.ws_futures_get_order_book_ticker(symbol=\"LTCUSDT\")\n    positions = await futuresClientAsync.ws_futures_v2_account_position(symbol=\"LTCUSDT\")\n\n    # Create an algo order\n    order = await futuresClientAsync.ws_futures_create_algo_order(\n        symbol=ticker[\"symbol\"],\n        side=\"BUY\",\n        positionSide=positions[0][\"positionSide\"],\n        type=\"STOP_MARKET\",\n        algoType=\"CONDITIONAL\",\n        quantity=1,\n        triggerPrice=1000,\n    )\n\n    assert order[\"symbol\"] == ticker[\"symbol\"]\n    assert \"algoId\" in order\n    assert order[\"algoType\"] == \"CONDITIONAL\"\n\n    # Cancel the algo order\n    cancel_result = await futuresClientAsync.ws_futures_cancel_algo_order(\n        symbol=ticker[\"symbol\"], algoId=order[\"algoId\"]\n    )\n\n    assert cancel_result[\"algoId\"] == order[\"algoId\"]\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\n@pytest.mark.asyncio()\nasync def test_ws_futures_create_conditional_order_auto_routing(futuresClientAsync):\n    \"\"\"Test that conditional order types are automatically routed to algo endpoint\"\"\"\n    ticker = await futuresClientAsync.ws_futures_get_order_book_ticker(symbol=\"LTCUSDT\")\n    positions = await futuresClientAsync.ws_futures_v2_account_position(symbol=\"LTCUSDT\")\n\n    # Create a STOP_MARKET order using ws_futures_create_order\n    # It should automatically route to the algo endpoint\n    # Use a price above current market price for BUY STOP\n    trigger_price = float(ticker[\"askPrice\"]) * 1.5\n    order = await futuresClientAsync.ws_futures_create_order(\n        symbol=ticker[\"symbol\"],\n        side=\"BUY\",\n        positionSide=positions[0][\"positionSide\"],\n        type=\"STOP_MARKET\",\n        quantity=1,\n        triggerPrice=trigger_price,\n    )\n\n    assert order[\"symbol\"] == ticker[\"symbol\"]\n    assert \"algoId\" in order\n    assert order[\"algoType\"] == \"CONDITIONAL\"\n\n    # Cancel the order using algoId\n    cancel_result = await futuresClientAsync.ws_futures_cancel_order(\n        symbol=ticker[\"symbol\"], algoId=order[\"algoId\"]\n    )\n    assert cancel_result[\"algoId\"] == order[\"algoId\"]\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\n@pytest.mark.asyncio()\nasync def test_ws_futures_conditional_order_with_stop_price(futuresClientAsync):\n    \"\"\"Test that stopPrice is converted to triggerPrice for conditional orders\"\"\"\n    ticker = await futuresClientAsync.ws_futures_get_order_book_ticker(symbol=\"LTCUSDT\")\n    positions = await futuresClientAsync.ws_futures_v2_account_position(symbol=\"LTCUSDT\")\n\n    # Create a TAKE_PROFIT_MARKET order with stopPrice (should be converted to triggerPrice)\n    # Use a price above current market price for SELL TAKE_PROFIT\n    trigger_price = float(ticker[\"askPrice\"]) * 1.5\n    order = await futuresClientAsync.ws_futures_create_order(\n        symbol=ticker[\"symbol\"],\n        side=\"SELL\",\n        positionSide=positions[0][\"positionSide\"],\n        type=\"TAKE_PROFIT_MARKET\",\n        quantity=1,\n        stopPrice=trigger_price,  # This should be converted to triggerPrice\n    )\n\n    assert order[\"symbol\"] == ticker[\"symbol\"]\n    assert \"algoId\" in order\n    assert order[\"algoType\"] == \"CONDITIONAL\"\n\n    # Cancel the order\n    await futuresClientAsync.ws_futures_cancel_order(\n        symbol=ticker[\"symbol\"], algoId=order[\"algoId\"]\n    )\n"
  },
  {
    "path": "tests/test_client.py",
    "content": "import sys\nimport pytest\nfrom binance.client import Client\nfrom binance.exceptions import BinanceAPIException, BinanceRequestException\nfrom .conftest import proxies, api_key, api_secret, testnet, call_method_and_assert_uri_contains\n\n\ndef test_client_initialization(client):\n    assert client.API_KEY is not None\n    assert client.API_SECRET is not None\n\n\n@pytest.mark.skip(reason=\"Endpoint not documented\")\ndef test_get_products(client):\n    client.get_products()\n\n\ndef test_get_exchange_info(client):\n    client.get_exchange_info()\n\n\ndef test_get_symbol_info(client):\n    client.get_symbol_info(\"BTCUSDT\")\n\n\ndef test_ping(client):\n    call_method_and_assert_uri_contains(client, 'ping', '/v3/')\n\n\n\ndef test_get_server_time(client):\n    client.get_server_time()\n\n\ndef test_get_all_tickers(client):\n    client.get_all_tickers()\n\n\ndef test_get_orderbook_tickers(client):\n    client.get_orderbook_tickers()\n\n\ndef test_get_order_book(client):\n    client.get_order_book(symbol=\"BTCUSDT\")\n\n\ndef test_get_recent_trades(client):\n    client.get_recent_trades(symbol=\"BTCUSDT\")\n\n\ndef test_get_historical_trades(client):\n    client.get_historical_trades(symbol=\"BTCUSDT\")\n\n\ndef test_get_aggregate_trades(client):\n    client.get_aggregate_trades(symbol=\"BTCUSDT\")\n\n\ndef test_get_klines(client):\n    client.get_klines(symbol=\"BTCUSDT\", interval=\"1d\")\n\ndef test_get_ui_klines(client):\n    client.get_ui_klines(symbol=\"BTCUSDT\", interval=\"1d\")\n\ndef test_get_avg_price(client):\n    client.get_avg_price(symbol=\"BTCUSDT\")\n\n\ndef test_get_ticker(client):\n    client.get_ticker(symbol=\"BTCUSDT\")\n\n\ndef test_get_symbol_ticker(client):\n    client.get_symbol_ticker(symbol=\"BTCUSDT\")\n\n\ndef test_get_orderbook_ticker(client):\n    call_method_and_assert_uri_contains(client, 'get_orderbook_ticker', '/v3/', symbol=\"BTCUSDT\")\n\n\ndef test_get_account(client):\n    client.get_account()\n\n\ndef test_get_asset_balance(client):\n    client.get_asset_balance(asset=\"BTC\")\n\n\ndef test_get_asset_balance_no_asset_provided(client):\n    client.get_asset_balance()\n\n\ndef test_get_my_trades(client):\n    client.get_my_trades(symbol=\"BTCUSDT\")\n\n\ndef test_get_system_status(client):\n    client.get_system_status()\n\n\n# User Stream Endpoints\n\n\ndef test_stream_get_listen_key_and_close(client):\n    listen_key = client.stream_get_listen_key()\n    client.stream_close(listen_key)\n\n\n# Quoting interface endpoints\n@pytest.mark.skip(reason=\"Endpoint not working on testnet\")\ndef test_get_account_status(client):\n    client.get_account_status()\n\n\n@pytest.mark.skip(reason=\"Endpoint not working on testnet\")\ndef test_get_account_api_trading_status(client):\n    client.get_account_api_trading_status()\n\n\n@pytest.mark.skip(reason=\"Endpoint not working on testnet\")\ndef test_get_account_api_permissions(client):\n    client.get_account_api_permissions()\n\n\n@pytest.mark.skip(reason=\"Endpoint not working on testnet\")\ndef test_get_dust_assets(client):\n    client.get_dust_assets()\n\n\n#########################\n# Websocket API Requests #\n#########################\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\ndef test_ws_get_order_book(client):\n    client.ws_get_order_book(symbol=\"BTCUSDT\")\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\ndef test_ws_get_recent_trades(client):\n    client.ws_get_recent_trades(symbol=\"BTCUSDT\")\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\ndef test_ws_get_historical_trades(client):\n    client.ws_get_historical_trades(symbol=\"BTCUSDT\")\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\ndef test_ws_get_aggregate_trades(client):\n    client.ws_get_aggregate_trades(symbol=\"BTCUSDT\")\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\ndef test_ws_get_klines(client):\n    client.ws_get_klines(symbol=\"BTCUSDT\", interval=\"1m\")\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\ndef test_ws_get_uiKlines(client):\n    client.ws_get_uiKlines(symbol=\"BTCUSDT\", interval=\"1m\")\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\ndef test_ws_get_avg_price(client):\n    client.ws_get_avg_price(symbol=\"BTCUSDT\")\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\ndef test_ws_get_ticker(client):\n    ticker = client.ws_get_ticker(symbol=\"BTCUSDT\")\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\ndef test_ws_get_trading_day_ticker(client):\n    client.ws_get_trading_day_ticker(symbol=\"BTCUSDT\")\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\ndef test_ws_get_symbol_ticker_window(client):\n    client.ws_get_symbol_ticker_window(symbol=\"BTCUSDT\")\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\ndef test_ws_get_symbol_ticker(client):\n    client.ws_get_symbol_ticker(symbol=\"BTCUSDT\")\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\ndef test_ws_get_orderbook_ticker(client):\n    client.ws_get_orderbook_ticker(symbol=\"BTCUSDT\")\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\ndef test_ws_ping(client):\n    client.ws_ping()\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\ndef test_ws_get_time(client):\n    client.ws_get_time()\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\ndef test_ws_get_exchange_info(client):\n    client.ws_get_exchange_info(symbol=\"BTCUSDT\")\n\n\ndef test_time_unit_microseconds():\n    micro_client = Client(\n        api_key,\n        api_secret,\n        {\"proxies\": proxies},\n        testnet=testnet,\n        time_unit=\"MICROSECOND\",\n    )\n    micro_trades = micro_client.get_recent_trades(symbol=\"BTCUSDT\")\n    assert len(str(micro_trades[0][\"time\"])) >= 16, (\n        \"Time should be in microseconds (16+ digits)\"\n    )\n\n\ndef test_time_unit_milloseconds():\n    milli_client = Client(\n        api_key,\n        api_secret,\n        {\"proxies\": proxies},\n        testnet=testnet,\n        time_unit=\"MILLISECOND\",\n    )\n    milli_trades = milli_client.get_recent_trades(symbol=\"BTCUSDT\")\n    assert len(str(milli_trades[0][\"time\"])) == 13, (\n        \"Time should be in milliseconds (13 digits)\"\n    )\n\n\ndef test_handle_response(client):\n    # Test successful JSON response\n    mock_response = type('Response', (), {\n        'status_code': 200,\n        'text': '{\"key\": \"value\"}',\n        'json': lambda: {\"key\": \"value\"}\n    })\n    assert client._handle_response(mock_response) == {\"key\": \"value\"}\n\n    # Test empty response\n    mock_empty_response = type('Response', (), {\n        'status_code': 200,\n        'text': ''\n    })\n    assert client._handle_response(mock_empty_response) == {}\n\n    # Test invalid JSON response\n    mock_invalid_response = type('Response', (), {\n        'status_code': 200,\n        'text': 'invalid json',\n        'json': lambda: exec('raise ValueError()')\n    })\n    with pytest.raises(BinanceRequestException):\n        client._handle_response(mock_invalid_response)\n\n    # Test error status code\n    mock_error_response = type('Response', (), {\n        'status_code': 400,\n        'text': 'error message'\n    })\n    with pytest.raises(BinanceAPIException):\n        client._handle_response(mock_error_response)\n"
  },
  {
    "path": "tests/test_client_futures.py",
    "content": "from datetime import datetime\nimport re\n\nimport pytest\nimport requests_mock\nfrom .test_order import assert_contract_order\nfrom .test_get_order_book import assert_ob\n\n\ndef test_futures_ping(futuresClient):\n    futuresClient.futures_ping()\n\n\ndef test_futures_time(futuresClient):\n    futuresClient.futures_time()\n\n\ndef test_futures_exchange_info(futuresClient):\n    futuresClient.futures_exchange_info()\n\n\ndef test_futures_order_book(futuresClient):\n    order_book = futuresClient.futures_order_book(symbol=\"BTCUSDT\")\n    assert_ob(order_book)\n\n\ndef test_futures_rpi_depth(futuresClient):\n    rpi_depth = futuresClient.futures_rpi_depth(symbol=\"BTCUSDT\")\n    assert_ob(rpi_depth)\n\n\ndef test_futures_recent_trades(futuresClient):\n    futuresClient.futures_recent_trades(symbol=\"BTCUSDT\")\n\n\ndef test_futures_historical_trades(futuresClient):\n    futuresClient.futures_historical_trades(symbol=\"BTCUSDT\")\n\n\ndef test_futures_aggregate_trades(futuresClient):\n    futuresClient.futures_aggregate_trades(symbol=\"BTCUSDT\")\n\n\ndef test_futures_klines(futuresClient):\n    futuresClient.futures_klines(symbol=\"BTCUSDT\", interval=\"1h\")\n\n\ndef test_futures_mark_price_klines(futuresClient):\n    futuresClient.futures_mark_price_klines(symbol=\"BTCUSDT\", interval=\"1h\")\n\n\ndef test_futures_index_price_klines(futuresClient):\n    futuresClient.futures_index_price_klines(pair=\"BTCUSDT\", interval=\"1h\")\n\n\ndef test_futures_premium_index_klines(futuresClient):\n    futuresClient.futures_premium_index_klines(symbol=\"BTCUSDT\", interval=\"1h\")\n\n\ndef test_futures_continuous_klines(futuresClient):\n    futuresClient.futures_continuous_klines(\n        pair=\"BTCUSDT\", contractType=\"PERPETUAL\", interval=\"1h\"\n    )\n\n\ndef test_futures_historical_klines(futuresClient):\n    futuresClient.futures_historical_klines(\n        symbol=\"BTCUSDT\", interval=\"1h\", start_str=datetime.now().strftime(\"%Y-%m-%d\")\n    )\n\n\ndef test_futures_historical_klines_generator(futuresClient):\n    futuresClient.futures_historical_klines_generator(\n        symbol=\"BTCUSDT\", interval=\"1h\", start_str=datetime.now().strftime(\"%Y-%m-%d\")\n    )\n\n\ndef test_futures_mark_price(futuresClient):\n    futuresClient.futures_mark_price()\n\n\ndef test_futures_funding_rate(futuresClient):\n    futuresClient.futures_funding_rate()\n\n\n@pytest.mark.skip(reason=\"No Sandbox Environment to test\")\ndef test_futures_top_longshort_account_ratio(futuresClient):\n    futuresClient.futures_top_longshort_account_ratio(symbol=\"BTCUSDT\", period=\"5m\")\n\n\n@pytest.mark.skip(reason=\"No Sandbox Environment to test\")\ndef test_futures_top_longshort_position_ratio(futuresClient):\n    futuresClient.futures_top_longshort_position_ratio(symbol=\"BTCUSDT\", period=\"5m\")\n\n\n@pytest.mark.skip(reason=\"No Sandbox Environment to test\")\ndef test_futures_global_longshort_ratio(futuresClient):\n    futuresClient.futures_global_longshort_ratio(symbol=\"BTCUSDT\", period=\"5m\")\n\n\n@pytest.mark.skip(reason=\"No Sandbox Environment to test\")\ndef test_futures_taker_longshort_ratio(futuresClient):\n    futuresClient.futures_taker_longshort_ratio(symbol=\"BTCUSDT\", period=\"5m\")\n\n\ndef test_futures_ticker(futuresClient):\n    futuresClient.futures_ticker()\n\n\ndef test_futures_symbol_ticker(futuresClient):\n    futuresClient.futures_symbol_ticker()\n\n\ndef test_futures_orderbook_ticker(futuresClient):\n    futuresClient.futures_orderbook_ticker()\n\n\ndef test_futures_index_index_price_constituents(futuresClient):\n    futuresClient.futures_index_price_constituents(symbol=\"BTCUSD\")\n\n\ndef test_futures_liquidation_orders(futuresClient):\n    futuresClient.futures_liquidation_orders()\n\n\n@pytest.mark.skip(reason=\"Fails in demo environment\")\ndef test_futures_api_trading_status(futuresClient):\n    futuresClient.futures_api_trading_status()\n\n\ndef test_futures_commission_rate(futuresClient):\n    futuresClient.futures_commission_rate(symbol=\"BTCUSDT\")\n\n\ndef test_futures_adl_quantile_estimate(futuresClient):\n    futuresClient.futures_adl_quantile_estimate()\n\n\ndef test_futures_open_interest(futuresClient):\n    futuresClient.futures_open_interest(symbol=\"BTCUSDT\")\n\n\ndef test_futures_index_info(futuresClient):\n    futuresClient.futures_index_info()\n\n\n@pytest.mark.skip(reason=\"No Sandbox Environment to test\")\ndef test_futures_open_interest_hist(futuresClient):\n    futuresClient.futures_open_interest_hist(symbol=\"BTCUSDT\", period=\"5m\")\n\n\ndef test_futures_leverage_bracket(futuresClient):\n    futuresClient.futures_leverage_bracket()\n\n\n@pytest.mark.skip(reason=\"Not implemented\")\ndef test_futures_account_transfer(futuresClient):\n    futuresClient.futures_account_transfer()\n\n\n@pytest.mark.skip(reason=\"Not implemented\")\ndef test_transfer_history(client):\n    client.transfer_history()\n\n\n@pytest.mark.skip(reason=\"Not implemented\")\ndef test_futures_loan_borrow_history(futuresClient):\n    futuresClient.futures_loan_borrow_history()\n\n\n@pytest.mark.skip(reason=\"Not implemented\")\ndef test_futures_loan_repay_history(futuresClient):\n    futuresClient.futures_loan_repay_history()\n\n\n@pytest.mark.skip(reason=\"Not implemented\")\ndef test_futures_loan_wallet(futuresClient):\n    futuresClient.futures_loan_wallet()\n\n\n@pytest.mark.skip(reason=\"Not implemented\")\ndef test_futures_cross_collateral_adjust_history(futuresClient):\n    futuresClient.futures_cross_collateral_adjust_history()\n\n\n@pytest.mark.skip(reason=\"Not implemented\")\ndef test_futures_cross_collateral_liquidation_history(futuresClient):\n    futuresClient.futures_cross_collateral_liquidation_history()\n\n\n@pytest.mark.skip(reason=\"Not implemented\")\ndef test_futures_loan_interest_history(futuresClient):\n    futuresClient.futures_loan_interest_history()\n\n\ndef test_futures_create_get_edit_cancel_order(futuresClient):\n    ticker = futuresClient.futures_ticker(symbol=\"LTCUSDT\")\n    positions = futuresClient.futures_position_information(symbol=\"LTCUSDT\")\n    order = futuresClient.futures_create_order(\n        symbol=ticker[\"symbol\"],\n        side=\"SELL\",\n        positionSide=positions[0][\"positionSide\"],\n        type=\"LIMIT\",\n        timeInForce=\"GTC\",\n        quantity=0.1,\n        price=str(round(float(ticker[\"lastPrice\"]) + 2)),\n    )\n    assert_contract_order(futuresClient, order)\n    order = futuresClient.futures_modify_order(\n        orderid=order[\"orderId\"],\n        symbol=order[\"symbol\"],\n        quantity=0.11,\n        side=order[\"side\"],\n        price=order[\"price\"],\n    )\n    assert_contract_order(futuresClient, order)\n    order = futuresClient.futures_get_order(\n        symbol=order[\"symbol\"], orderid=order[\"orderId\"]\n    )\n    assert_contract_order(futuresClient, order)\n    order = futuresClient.futures_cancel_order(\n        orderid=order[\"orderId\"], symbol=order[\"symbol\"]\n    )\n\n\ndef test_futures_create_test_order(futuresClient):\n    ticker = futuresClient.futures_ticker(symbol=\"LTCUSDT\")\n    positions = futuresClient.futures_position_information(symbol=\"LTCUSDT\")\n    futuresClient.futures_create_test_order(\n        symbol=ticker[\"symbol\"],\n        side=\"BUY\",\n        positionSide=positions[0][\"positionSide\"],\n        type=\"LIMIT\",\n        timeInForce=\"GTC\",\n        quantity=0.1,\n        price=str(round(float(ticker[\"lastPrice\"]) - 1, 0)),\n    )\n\n\ndef test_futures_place_batch_order_and_cancel(futuresClient):\n    ticker = futuresClient.futures_ticker(symbol=\"LTCUSDT\")\n    positions = futuresClient.futures_position_information(symbol=\"LTCUSDT\")\n    orders = futuresClient.futures_place_batch_order(\n        batchOrders=[\n            {\n                \"symbol\": ticker[\"symbol\"],\n                \"side\": \"SELL\",\n                \"positionSide\": positions[0][\"positionSide\"],\n                \"type\": \"LIMIT\",\n                \"timeInForce\": \"GTC\",\n                \"quantity\": \"0.1\",\n                \"price\": str(round(float(ticker[\"lastPrice\"]) + 2, 0)),\n            },\n            {\n                \"symbol\": ticker[\"symbol\"],\n                \"type\": \"LIMIT\",\n                \"side\": \"SELL\",\n                \"price\": str(round(float(ticker[\"lastPrice\"]) + 2, 0)),\n                \"positionSide\": positions[0][\"positionSide\"],\n                \"timeInForce\": \"GTC\",\n                \"quantity\": \"0.1\",\n            },\n        ]\n    )\n    for order in orders:\n        assert_contract_order(futuresClient, order)\n    # Cancel using orderidlist\n    order_ids = [order[\"orderId\"] for order in orders][:1]\n    cancelled_orders = futuresClient.futures_cancel_orders(\n        symbol=orders[0][\"symbol\"], orderidlist=order_ids\n    )\n    for order in cancelled_orders:\n        assert_contract_order(futuresClient, order)\n    # Cancel using origClientOrderIdList\n    client_order_ids = [order[\"clientOrderId\"] for order in orders][1:]\n    cancelled_orders = futuresClient.futures_cancel_orders(\n        symbol=orders[0][\"symbol\"], origclientorderidlist=client_order_ids\n    )\n    for order in cancelled_orders:\n        assert_contract_order(futuresClient, order)\n\n\ndef test_futures_get_open_orders(futuresClient):\n    futuresClient.futures_get_open_orders()\n\n\ndef test_futures_get_all_orders(futuresClient):\n    orders = futuresClient.futures_get_all_orders()\n    print(orders)\n\n\ndef test_futures_cancel_all_open_orders(futuresClient):\n    futuresClient.futures_cancel_all_open_orders(symbol=\"LTCUSDT\")\n\n\ndef test_futures_countdown_cancel_all(futuresClient):\n    futuresClient.futures_countdown_cancel_all(symbol=\"LTCUSDT\", countdownTime=10)\n\n\ndef test_futures_account_balance(futuresClient):\n    futuresClient.futures_account_balance()\n\n\ndef test_futures_account(futuresClient):\n    futuresClient.futures_account()\n\n\ndef test_futures_symbol_adl_risk(futuresClient):\n    # Test without symbol (get all)\n    adl_risks = futuresClient.futures_symbol_adl_risk()\n    assert isinstance(adl_risks, list)\n\n    # Test with specific symbol (if any symbols available)\n    if len(adl_risks) > 0:\n        test_symbol = adl_risks[0][\"symbol\"]\n        adl_risk = futuresClient.futures_symbol_adl_risk(symbol=test_symbol)\n        assert isinstance(adl_risk, dict)\n        assert \"symbol\" in adl_risk\n        assert \"adlRisk\" in adl_risk\n        assert adl_risk[\"adlRisk\"] in [\"low\", \"medium\", \"high\"]\n        assert adl_risk[\"symbol\"] == test_symbol\n\n\ndef test_futures_change_leverage(futuresClient):\n    futuresClient.futures_change_leverage(symbol=\"LTCUSDT\", leverage=10)\n\n\ndef test_futures_change_margin_type(futuresClient):\n    try:\n        futuresClient.futures_change_margin_type(symbol=\"XRPUSDT\", marginType=\"CROSSED\")\n    except Exception as e:\n        futuresClient.futures_change_margin_type(\n            symbol=\"XRPUSDT\", marginType=\"ISOLATED\"\n        )\n\n\ndef test_futures_position_margin_history(futuresClient):\n    position = futuresClient.futures_position_margin_history(symbol=\"LTCUSDT\")\n    print(position)\n\n\ndef test_futures_position_information(futuresClient):\n    futuresClient.futures_position_information()\n\n\ndef test_futures_account_trades(futuresClient):\n    futuresClient.futures_account_trades()\n\n\ndef test_futures_income_history(futuresClient):\n    futuresClient.futures_income_history()\n\n\ndef close_all_futures_positions(futuresClient):\n    # Get all open positions\n    positions = futuresClient.futures_position_information(symbol=\"LTCUSDT\")\n\n    for position in positions:\n        # Check if there is an open position\n        if float(position[\"positionAmt\"]) != 0:\n            symbol = position[\"symbol\"]\n            position_amt = float(position[\"positionAmt\"])\n            side = \"SELL\" if position_amt > 0 else \"BUY\"\n\n            # Place a market order to close the position\n            try:\n                print(f\"Closing position for {symbol}: {position_amt} units\")\n                futuresClient.futures_create_order(\n                    symbol=symbol, side=side, type=\"market\", quantity=abs(position_amt)\n                )\n                print(f\"Position for {symbol} closed successfully.\")\n            except Exception as e:\n                print(f\"Failed to close position for {symbol}: {e}\")\n\n\n@pytest.mark.skip(reason=\"Not implemented\")\ndef test_futures_get_and_change_position_mode(futuresClient):\n    mode = futuresClient.futures_get_position_mode()\n    futuresClient.futures_change_position_mode(\n        dualSidePosition=not mode[\"dualSidePosition\"]\n    )\n\n\n@pytest.mark.skip(reason=\"Not implemented\")\ndef test_futures_change_multi_assets_mode(futuresClient):\n    futuresClient.futures_change_multi_assets_mode()\n\n\ndef test_futures_get_multi_assets_mode(futuresClient):\n    futuresClient.futures_get_multi_assets_mode()\n\n\ndef test_futures_stream_get_listen_key(futuresClient):\n    futuresClient.futures_stream_get_listen_key()\n\n\n@pytest.mark.skip(reason=\"Not implemented\")\ndef test_futures_stream_close(futuresClient):\n    futuresClient.futures_stream_close()\n\n\n# new methods\ndef test_futures_account_config(futuresClient):\n    futuresClient.futures_account_config()\n\n\ndef test_futures_symbol_config(futuresClient):\n    futuresClient.futures_symbol_config()\n\n\n# COIN Futures API\ndef test_futures_coin_ping(futuresClient):\n    futuresClient.futures_coin_ping()\n\n\ndef test_futures_coin_time(futuresClient):\n    futuresClient.futures_coin_time()\n\n\ndef test_futures_coin_exchange_info(futuresClient):\n    futuresClient.futures_coin_exchange_info()\n\n\ndef test_futures_coin_order_book(futuresClient):\n    order_book = futuresClient.futures_coin_order_book(symbol=\"BTCUSD_PERP\")\n    assert_ob(order_book)\n\n\ndef test_futures_coin_recent_trades(futuresClient):\n    futuresClient.futures_coin_recent_trades(symbol=\"BTCUSD_PERP\")\n\n\ndef test_futures_coin_historical_trades(futuresClient):\n    futuresClient.futures_coin_historical_trades(symbol=\"BTCUSD_PERP\")\n\n\n@pytest.mark.skip(reason=\"Not implemented\")\ndef test_futures_coin_aggregate_trades(futuresClient):\n    futuresClient.futures_coin_aggregate_trades(symbol=\"BTCUSD_PERP\")\n\n\ndef test_futures_coin_klines(futuresClient):\n    futuresClient.futures_coin_klines(symbol=\"BTCUSD_PERP\", interval=\"1h\")\n\n\ndef test_futures_coin_continous_klines(futuresClient):\n    futuresClient.futures_coin_continous_klines(\n        pair=\"BTCUSD\", contractType=\"PERPETUAL\", interval=\"1h\"\n    )\n\n\ndef test_futures_coin_index_price_klines(futuresClient):\n    futuresClient.futures_coin_index_price_klines(pair=\"BTCUSD\", interval=\"1h\")\n\n\ndef test_futures_coin_mark_price_klines(futuresClient):\n    futuresClient.futures_coin_mark_price_klines(symbol=\"BTCUSD_PERP\", interval=\"1h\")\n\n\ndef test_futures_coin_mark_price(futuresClient):\n    futuresClient.futures_coin_mark_price()\n\n\n@pytest.mark.skip(reason=\"Giving unknwon error from binance\")\ndef test_futures_coin_funding_rate(futuresClient):\n    futuresClient.futures_coin_funding_rate(symbol=\"BTCUSD_PERP\")\n\n\ndef test_futures_coin_ticker(futuresClient):\n    futuresClient.futures_coin_ticker()\n\n\ndef test_futures_coin_symbol_ticker(futuresClient):\n    futuresClient.futures_coin_symbol_ticker()\n\n\ndef test_futures_coin_orderbook_ticker(futuresClient):\n    futuresClient.futures_coin_orderbook_ticker()\n\n\ndef test_futures_coin_index_index_price_constituents(futuresClient):\n    futuresClient.futures_coin_index_price_constituents(symbol=\"BTCUSD\")\n\n\n@pytest.mark.skip(reason=\"Not implemented\")\ndef test_futures_coin_liquidation_orders(futuresClient):\n    futuresClient.futures_coin_liquidation_orders(limit=5)\n\n\ndef test_futures_coin_open_interest(futuresClient):\n    futuresClient.futures_coin_open_interest(symbol=\"BTCUSD_PERP\")\n\n\n@pytest.mark.skip(reason=\"Not implemented\")\ndef test_futures_coin_open_interest_hist(futuresClient):\n    futuresClient.futures_coin_open_interest_hist(symbol=\"BTCUSD_PERP\")\n\n\ndef test_futures_coin_leverage_bracket(futuresClient):\n    futuresClient.futures_coin_leverage_bracket()\n\n\n@pytest.mark.skip(reason=\"Not implemented\")\ndef test_futures_coin_create_order(futuresClient):\n    positions = futuresClient.futures_coin_position_information()\n    ticker = futuresClient.futures_coin_ticker(symbol=positions[0][\"symbol\"])\n    order = futuresClient.futures_coin_create_order(\n        symbol=positions[0][\"symbol\"],\n        side=\"BUY\",\n        type=\"LIMIT\",\n        timeInForce=\"GTC\",\n        quantity=1,\n        price=str(round(float(ticker[0][\"lastPrice\"]) - 1, 0)),\n    )\n    assert_contract_order(futuresClient, order)\n    order = futuresClient.futures_modify_order(\n        orderid=order[\"orderId\"],\n        symbol=order[\"symbol\"],\n        quantity=0.11,\n        side=order[\"side\"],\n        price=order[\"price\"],\n    )\n    assert_contract_order(futuresClient, order)\n    order = futuresClient.futures_get_order(\n        symbol=order[\"symbol\"], orderid=order[\"orderId\"]\n    )\n    assert_contract_order(futuresClient, order)\n    order = futuresClient.futures_cancel_order(\n        orderid=order[\"orderId\"], symbol=order[\"symbol\"]\n    )\n\n\n@pytest.mark.skip(reason=\"Not implemented\")\ndef test_futures_coin_place_batch_order(futuresClient):\n    futuresClient.futures_coin_place_batch_order()\n\n\n@pytest.mark.skip(reason=\"Not implemented\")\ndef test_futures_coin_get_order(futuresClient):\n    futuresClient.futures_coin_get_order()\n\n\ndef test_futures_coin_get_open_orders(futuresClient):\n    futuresClient.futures_coin_get_open_orders()\n\n\n@pytest.mark.skip(reason=\"Not implemented\")\ndef test_futures_coin_get_all_orders(futuresClient):\n    futuresClient.futures_coin_get_all_orders()\n\n\n@pytest.mark.skip(reason=\"Not implemented\")\ndef test_futures_coin_cancel_order(futuresClient):\n    futuresClient.futures_coin_cancel_order()\n\n\ndef test_futures_coin_cancel_all_open_orders(futuresClient):\n    futuresClient.futures_coin_cancel_all_open_orders(symbol=\"BTCUSD_PERP\")\n\n\n@pytest.mark.skip(reason=\"Not implemented\")\ndef test_futures_coin_cancel_orders(futuresClient):\n    futuresClient.futures_coin_cancel_orders()\n\n\ndef test_futures_coin_account_balance(futuresClient):\n    futuresClient.futures_coin_account_balance()\n\n\ndef test_futures_coin_account(futuresClient):\n    futuresClient.futures_coin_account()\n\n\n@pytest.mark.skip(reason=\"Not implemented\")\ndef test_futures_coin_change_leverage(futuresClient):\n    futuresClient.futures_coin_change_leverage(symbol=\"XRPUSDT\", leverage=10)\n\n\n@pytest.mark.skip(reason=\"Not implemented\")\ndef test_futures_coin_change_margin_type(futuresClient):\n    futuresClient.futures_coin_change_margin_type()\n\n\n@pytest.mark.skip(reason=\"Not implemented\")\ndef test_futures_coin_change_position_margin(futuresClient):\n    futuresClient.futures_coin_change_position_margin()\n\n\ndef test_futures_coin_position_margin_history(futuresClient):\n    futuresClient.futures_coin_position_margin_history(symbol=\"LTCUSD_PERP\")\n\n\ndef test_futures_coin_position_information(futuresClient):\n    futuresClient.futures_coin_position_information()\n\n\ndef test_futures_coin_account_trades(futuresClient):\n    futuresClient.futures_coin_account_trades()\n\n\ndef test_futures_coin_income_history(futuresClient):\n    futuresClient.futures_coin_income_history()\n\n\n@pytest.mark.skip(reason=\"Not implemented\")\ndef test_futures_coin_change_position_mode(futuresClient):\n    futuresClient.futures_coin_change_position_mode()\n\n\ndef test_futures_coin_get_position_mode(futuresClient):\n    futuresClient.futures_coin_get_position_mode()\n\n\ndef test_futures_coin_stream_close(futuresClient):\n    listen_key = futuresClient.futures_coin_stream_get_listen_key()\n    futuresClient.futures_coin_stream_close(listenKey=listen_key)\n\n\n########################################################\n# Test block trades\n########################################################\n\n\n@pytest.mark.skip(reason=\"No sandbox support\")\ndef test_futures_coin_account_order_history_download(futuresClient):\n    futuresClient.futures_coin_account_order_download()\n\n\n@pytest.mark.skip(reason=\"No sandbox support\")\ndef test_futures_coin_account_order_download_id(futuresClient):\n    futuresClient.futures_coin_account_order_download_link(downloadId=\"123\")\n\n\n@pytest.mark.skip(reason=\"No sandbox support\")\ndef test_futures_coin_account_trade_history_download(futuresClient):\n    futuresClient.futures_coin_account_trade_history_download()\n\n\n@pytest.mark.skip(reason=\"No sandbox support\")\ndef test_futures_coin_account_trade_download_id(futuresClient):\n    futuresClient.futures_coin_account_trade_history_download_link(downloadId=\"123\")\n\n\ndef test_futures_coin_account_order_history_download_mock(futuresClient):\n    expected_response = {\n        \"avgCostTimestampOfLast30d\": 7241837,\n        \"downloadId\": \"546975389218332672\",\n    }\n    url_pattern = re.compile(\n        r\"https://[^/]+/dapi/v1/order/asyn\"\n        r\"\\?recvWindow=\\d+\"\n        r\"&timestamp=\\d+\"\n        r\"&signature=[a-f0-9]{64}\"\n    )\n\n    with requests_mock.mock() as m:\n        m.get(\n            url_pattern,\n            json=expected_response,\n        )\n        response = futuresClient.futures_coin_account_order_history_download()\n        assert response == expected_response\n\n\ndef test_futures_coin_account_order_download_id_mock(futuresClient):\n    expected_response = {\"link\": \"hello\"}\n    url_pattern = re.compile(\n        r\"https://[^/]+/dapi/v1/order/asyn/id\"\n        r\"\\?downloadId=123\"\n        r\"&recvWindow=\\d+\"\n        r\"&timestamp=\\d+\"\n        r\"&signature=.+\"\n    )\n    with requests_mock.mock() as m:\n        m.get(\n            url_pattern,\n            json=expected_response,\n        )\n\n        response = futuresClient.futures_coin_accout_order_history_download_link(\n            downloadId=\"123\"\n        )\n        assert response == expected_response\n\n\ndef test_futures_coin_account_trade_history_download_id_mock(futuresClient):\n    expected_response = {\n        \"avgCostTimestampOfLast30d\": 7241837,\n        \"downloadId\": \"546975389218332672\",\n    }\n    url_pattern = re.compile(\n        r\"https://[^/]+/dapi/v1/trade/asyn\"\n        r\"\\?recvWindow=\\d+\"\n        r\"&timestamp=\\d+\"\n        r\"&signature=[a-f0-9]{64}\"\n    )\n\n    with requests_mock.mock() as m:\n        m.get(\n            url_pattern,\n            json=expected_response,\n        )\n        response = futuresClient.futures_coin_account_trade_history_download()\n        assert response == expected_response\n\n\ndef test_futures_coin_account_trade_history_download_link_mock(futuresClient):\n    expected_response = {\"link\": \"hello\"}\n    url_pattern = re.compile(\n        r\"https://[^/]+/dapi/v1/trade/asyn/id\"\n        r\"\\?downloadId=123\"\n        r\"&recvWindow=\\d+\"\n        r\"&timestamp=\\d+\"\n        r\"&signature=.+\"\n    )\n    with requests_mock.mock() as m:\n        m.get(\n            url_pattern,\n            json=expected_response,\n        )\n\n        response = futuresClient.futures_coin_account_trade_history_download_link(\n            downloadId=\"123\"\n        )\n        assert response == expected_response\n\n\n# Algo Orders (Conditional Orders) Tests\n\n\ndef test_futures_create_algo_order(futuresClient):\n    \"\"\"Test creating an algo/conditional order\"\"\"\n    ticker = futuresClient.futures_ticker(symbol=\"LTCUSDT\")\n    positions = futuresClient.futures_position_information(symbol=\"LTCUSDT\")\n    order = futuresClient.futures_create_algo_order(\n        symbol=ticker[\"symbol\"],\n        side=\"BUY\",\n        positionSide=positions[0][\"positionSide\"],\n        type=\"STOP_MARKET\",\n        algoType=\"CONDITIONAL\",\n        quantity=1,\n        triggerPrice=1000,\n    )\n    assert order[\"symbol\"] == ticker[\"symbol\"]\n    assert \"algoId\" in order\n    # Clean up - cancel the algo order\n    futuresClient.futures_cancel_algo_order(\n        symbol=ticker[\"symbol\"], algoId=order[\"algoId\"]\n    )\n\n\ndef test_futures_create_order_auto_routes_conditional(futuresClient):\n    \"\"\"Test that futures_create_order automatically routes conditional orders to algo endpoint\"\"\"\n    ticker = futuresClient.futures_ticker(symbol=\"LTCUSDT\")\n    positions = futuresClient.futures_position_information(symbol=\"LTCUSDT\")\n    # Create a conditional order using the regular create_order method\n    order = futuresClient.futures_create_order(\n        symbol=ticker[\"symbol\"],\n        side=\"BUY\",\n        positionSide=positions[0][\"positionSide\"],\n        type=\"TAKE_PROFIT_MARKET\",\n        quantity=1,\n        stopPrice=10,\n    )\n    # Verify it was created as an algo order\n    assert order[\"symbol\"] == ticker[\"symbol\"]\n    assert \"algoId\" in order\n    # Clean up\n    futuresClient.futures_cancel_algo_order(\n        symbol=ticker[\"symbol\"], algoId=order[\"algoId\"]\n    )\n\n\ndef test_futures_get_algo_order(futuresClient):\n    \"\"\"Test getting a specific algo order\"\"\"\n    ticker = futuresClient.futures_ticker(symbol=\"LTCUSDT\")\n    positions = futuresClient.futures_position_information(symbol=\"LTCUSDT\")\n    # Create an algo order first\n    order = futuresClient.futures_create_algo_order(\n        symbol=ticker[\"symbol\"],\n        side=\"BUY\",\n        positionSide=positions[0][\"positionSide\"],\n        type=\"STOP_MARKET\",\n        algoType=\"CONDITIONAL\",\n        quantity=1,\n        triggerPrice=1000,\n    )\n    algo_id = order[\"algoId\"]\n    # Get the order\n    fetched_order = futuresClient.futures_get_algo_order(\n        symbol=ticker[\"symbol\"], algoId=algo_id\n    )\n    assert fetched_order[\"algoId\"] == algo_id\n    assert fetched_order[\"symbol\"] == ticker[\"symbol\"]\n    # Clean up\n    futuresClient.futures_cancel_algo_order(symbol=ticker[\"symbol\"], algoId=algo_id)\n\n\ndef test_futures_get_order_with_conditional_param(futuresClient):\n    \"\"\"Test getting algo order using futures_get_order with conditional=True\"\"\"\n    ticker = futuresClient.futures_ticker(symbol=\"LTCUSDT\")\n    positions = futuresClient.futures_position_information(symbol=\"LTCUSDT\")\n    # Create an algo order\n    order = futuresClient.futures_create_algo_order(\n        symbol=ticker[\"symbol\"],\n        side=\"BUY\",\n        positionSide=positions[0][\"positionSide\"],\n        type=\"STOP_MARKET\",\n        algoType=\"CONDITIONAL\",\n        quantity=1,\n        triggerPrice=1000,\n    )\n    algo_id = order[\"algoId\"]\n    # Get the order using futures_get_order with conditional=True\n    fetched_order = futuresClient.futures_get_order(\n        symbol=ticker[\"symbol\"], algoId=algo_id, conditional=True\n    )\n    assert fetched_order[\"algoId\"] == algo_id\n    # Clean up\n    futuresClient.futures_cancel_algo_order(symbol=ticker[\"symbol\"], algoId=algo_id)\n\n\ndef test_futures_get_all_algo_orders(futuresClient):\n    \"\"\"Test getting all algo orders history\"\"\"\n    orders = futuresClient.futures_get_all_algo_orders(symbol=\"LTCUSDT\")\n    assert isinstance(orders, list)\n\n\ndef test_futures_get_all_orders_with_conditional_param(futuresClient):\n    \"\"\"Test getting all algo orders using futures_get_all_orders with conditional=True\"\"\"\n    orders = futuresClient.futures_get_all_orders(symbol=\"LTCUSDT\", conditional=True)\n    assert isinstance(orders, list)\n\n\ndef test_futures_get_open_algo_orders(futuresClient):\n    \"\"\"Test getting open algo orders\"\"\"\n    orders = futuresClient.futures_get_open_algo_orders(symbol=\"LTCUSDT\")\n    assert isinstance(orders, list)\n\n\ndef test_futures_get_open_orders_with_conditional_param(futuresClient):\n    \"\"\"Test getting open algo orders using futures_get_open_orders with conditional=True\"\"\"\n    orders = futuresClient.futures_get_open_orders(symbol=\"LTCUSDT\", conditional=True)\n    assert isinstance(orders, list)\n\n\ndef test_futures_cancel_algo_order(futuresClient):\n    \"\"\"Test canceling an algo order\"\"\"\n    ticker = futuresClient.futures_ticker(symbol=\"LTCUSDT\")\n    positions = futuresClient.futures_position_information(symbol=\"LTCUSDT\")\n    # Create an algo order\n    order = futuresClient.futures_create_algo_order(\n        symbol=ticker[\"symbol\"],\n        side=\"BUY\",\n        positionSide=positions[0][\"positionSide\"],\n        type=\"STOP_MARKET\",\n        algoType=\"CONDITIONAL\",\n        quantity=1,\n        triggerPrice=1000,\n    )\n    algo_id = order[\"algoId\"]\n    # Cancel the order\n    result = futuresClient.futures_cancel_algo_order(\n        symbol=ticker[\"symbol\"], algoId=algo_id\n    )\n    assert result[\"algoId\"] == algo_id\n\n\ndef test_futures_cancel_order_with_conditional_param(futuresClient):\n    \"\"\"Test canceling algo order using futures_cancel_order with conditional=True\"\"\"\n    ticker = futuresClient.futures_ticker(symbol=\"LTCUSDT\")\n    positions = futuresClient.futures_position_information(symbol=\"LTCUSDT\")\n    # Create an algo order\n    order = futuresClient.futures_create_algo_order(\n        symbol=ticker[\"symbol\"],\n        side=\"BUY\",\n        positionSide=positions[0][\"positionSide\"],\n        type=\"STOP_MARKET\",\n        algoType=\"CONDITIONAL\",\n        quantity=1,\n        triggerPrice=1000,\n    )\n    algo_id = order[\"algoId\"]\n    # Cancel using futures_cancel_order with conditional=True\n    result = futuresClient.futures_cancel_order(\n        symbol=ticker[\"symbol\"], algoId=algo_id, conditional=True\n    )\n    assert result[\"algoId\"] == algo_id\n\n\ndef test_futures_cancel_all_algo_open_orders(futuresClient):\n    \"\"\"Test canceling all open algo orders\"\"\"\n    result = futuresClient.futures_cancel_all_algo_open_orders(symbol=\"LTCUSDT\")\n    # Should return success response\n    assert \"code\" in result or \"msg\" in result\n\n\ndef test_futures_cancel_all_open_orders_with_conditional_param(futuresClient):\n    \"\"\"Test canceling all algo orders using futures_cancel_all_open_orders with conditional=True\"\"\"\n    result = futuresClient.futures_cancel_all_open_orders(\n        symbol=\"LTCUSDT\", conditional=True\n    )\n    # Should return success response\n    assert \"code\" in result or \"msg\" in result\n\n\ndef test_futures_create_algo_order_with_price_protect(futuresClient):\n    \"\"\"Test creating an algo order with priceProtect parameter\"\"\"\n    ticker = futuresClient.futures_ticker(symbol=\"LTCUSDT\")\n    positions = futuresClient.futures_position_information(symbol=\"LTCUSDT\")\n    order = futuresClient.futures_create_algo_order(\n        symbol=ticker[\"symbol\"],\n        side=\"BUY\",\n        positionSide=positions[0][\"positionSide\"],\n        type=\"STOP_MARKET\",\n        algoType=\"CONDITIONAL\",\n        quantity=1,\n        triggerPrice=1000,\n        priceProtect=\"TRUE\",\n    )\n    assert order[\"symbol\"] == ticker[\"symbol\"]\n    assert \"algoId\" in order\n    assert order[\"priceProtect\"] is True\n    # Clean up\n    futuresClient.futures_cancel_algo_order(\n        symbol=ticker[\"symbol\"], algoId=order[\"algoId\"]\n    )\n\n\n@pytest.mark.skip(reason=\"TRAILING_STOP_MARKET with activatePrice may not be fully supported in testnet environment\")\ndef test_futures_create_algo_order_trailing_stop(futuresClient):\n    \"\"\"Test creating a TRAILING_STOP_MARKET algo order with activatePrice and callbackRate\"\"\"\n    ticker = futuresClient.futures_ticker(symbol=\"LTCUSDT\")\n    positions = futuresClient.futures_position_information(symbol=\"LTCUSDT\")\n    current_price = float(ticker[\"lastPrice\"])\n    \n    # For SELL trailing stop: activatePrice should be above current price\n    # For BUY trailing stop: activatePrice should be below current price\n    order = futuresClient.futures_create_algo_order(\n        symbol=ticker[\"symbol\"],\n        side=\"SELL\",\n        positionSide=positions[0][\"positionSide\"],\n        type=\"TRAILING_STOP_MARKET\",\n        algoType=\"CONDITIONAL\",\n        quantity=1,\n        activatePrice=str(current_price * 1.1),  # 10% above current price\n        callbackRate=\"1.0\",  # 1%\n    )\n    assert order[\"symbol\"] == ticker[\"symbol\"]\n    assert \"algoId\" in order\n    # Clean up\n    futuresClient.futures_cancel_algo_order(\n        symbol=ticker[\"symbol\"], algoId=order[\"algoId\"]\n    )\n\n\ndef test_futures_create_algo_order_with_stp_mode(futuresClient):\n    \"\"\"Test creating an algo order with selfTradePreventionMode\"\"\"\n    ticker = futuresClient.futures_ticker(symbol=\"LTCUSDT\")\n    positions = futuresClient.futures_position_information(symbol=\"LTCUSDT\")\n    order = futuresClient.futures_create_algo_order(\n        symbol=ticker[\"symbol\"],\n        side=\"SELL\",\n        positionSide=positions[0][\"positionSide\"],\n        type=\"TAKE_PROFIT\",\n        algoType=\"CONDITIONAL\",\n        quantity=1,\n        price=10000,\n        triggerPrice=10000,\n        timeInForce=\"GTC\",\n        selfTradePreventionMode=\"EXPIRE_MAKER\",\n    )\n    assert order[\"symbol\"] == ticker[\"symbol\"]\n    assert \"algoId\" in order\n    assert order[\"selfTradePreventionMode\"] == \"EXPIRE_MAKER\"\n    # Clean up\n    futuresClient.futures_cancel_algo_order(\n        symbol=ticker[\"symbol\"], algoId=order[\"algoId\"]\n    )\n\n\ndef test_futures_create_algo_order_with_price_match(futuresClient):\n    \"\"\"Test creating an algo order with priceMatch parameter\"\"\"\n    ticker = futuresClient.futures_ticker(symbol=\"LTCUSDT\")\n    positions = futuresClient.futures_position_information(symbol=\"LTCUSDT\")\n    order = futuresClient.futures_create_algo_order(\n        symbol=ticker[\"symbol\"],\n        side=\"SELL\",\n        positionSide=positions[0][\"positionSide\"],\n        type=\"TAKE_PROFIT\",\n        algoType=\"CONDITIONAL\",\n        quantity=1,\n        triggerPrice=10000,\n        timeInForce=\"GTC\",\n        priceMatch=\"OPPONENT\",\n    )\n    assert order[\"symbol\"] == ticker[\"symbol\"]\n    assert \"algoId\" in order\n    assert order[\"priceMatch\"] == \"OPPONENT\"\n    # Clean up\n    futuresClient.futures_cancel_algo_order(\n        symbol=ticker[\"symbol\"], algoId=order[\"algoId\"]\n    )\n\n\ndef test_futures_create_algo_order_with_new_order_resp_type(futuresClient):\n    \"\"\"Test creating an algo order with newOrderRespType parameter\"\"\"\n    ticker = futuresClient.futures_ticker(symbol=\"LTCUSDT\")\n    positions = futuresClient.futures_position_information(symbol=\"LTCUSDT\")\n    order = futuresClient.futures_create_algo_order(\n        symbol=ticker[\"symbol\"],\n        side=\"BUY\",\n        positionSide=positions[0][\"positionSide\"],\n        type=\"STOP_MARKET\",\n        algoType=\"CONDITIONAL\",\n        quantity=1,\n        triggerPrice=1000,\n        newOrderRespType=\"RESULT\",\n    )\n    assert order[\"symbol\"] == ticker[\"symbol\"]\n    assert \"algoId\" in order\n    # With RESULT response type, we should have more detailed information\n    assert \"algoStatus\" in order\n    # Clean up\n    futuresClient.futures_cancel_algo_order(\n        symbol=ticker[\"symbol\"], algoId=order[\"algoId\"]\n    )\n\n\ndef test_futures_create_algo_order_with_working_type(futuresClient):\n    \"\"\"Test creating an algo order with workingType parameter\"\"\"\n    ticker = futuresClient.futures_ticker(symbol=\"LTCUSDT\")\n    positions = futuresClient.futures_position_information(symbol=\"LTCUSDT\")\n    order = futuresClient.futures_create_algo_order(\n        symbol=ticker[\"symbol\"],\n        side=\"BUY\",\n        positionSide=positions[0][\"positionSide\"],\n        type=\"STOP_MARKET\",\n        algoType=\"CONDITIONAL\",\n        quantity=1,\n        triggerPrice=1000,\n        workingType=\"MARK_PRICE\",\n    )\n    assert order[\"symbol\"] == ticker[\"symbol\"]\n    assert \"algoId\" in order\n    assert order[\"workingType\"] == \"MARK_PRICE\"\n    # Clean up\n    futuresClient.futures_cancel_algo_order(\n        symbol=ticker[\"symbol\"], algoId=order[\"algoId\"]\n    )\n\n"
  },
  {
    "path": "tests/test_client_gift_card.py",
    "content": "import pytest\nimport requests_mock\n\npytestmark = pytest.mark.gift_card\n\n\ndef test_mock_gift_card_fetch_token_limit(liveClient):\n    \"\"\"Test gift card token limit endpoint with mocked response\"\"\"\n    expected_response = {\n        \"code\": \"000000\",\n        \"message\": \"success\",\n        \"data\": [{\"coin\": \"BNB\", \"fromMin\": \"0.01\", \"fromMax\": \"1\"}],\n        \"success\": True,\n    }\n\n    with requests_mock.mock() as m:\n        m.get(\n            \"https://api.binance.com/sapi/v1/giftcard/buyCode/token-limit\",\n            json=expected_response,\n        )\n\n        response = liveClient.gift_card_fetch_token_limit(baseToken=\"BUSD\")\n        assert response == expected_response\n\n\ndef test_gift_card_fetch_token_limit(liveClient):\n    liveClient.gift_card_fetch_token_limit(baseToken=\"BUSD\")\n\n\ndef test_gift_card_fetch_rsa_public_key(liveClient):\n    liveClient.gift_card_fetch_rsa_public_key()\n\n\ndef test_gift_card_create_verify_and_redeem(liveClient):\n    # create a gift card\n    response = liveClient.gift_card_create(token=\"USDT\", amount=1.0)\n    assert response[\"data\"][\"referenceNo\"] is not None\n    assert response[\"data\"][\"code\"] is not None\n    # verify the gift card\n    response = liveClient.gift_card_verify(referenceNo=response[\"data\"][\"referenceNo\"])\n    assert response[\"data\"][\"valid\"] == \"SUCCESS\"\n    # redeem the gift card\n    redeem_response = liveClient.gift_card_redeem(\n        code=response[\"data\"][\"code\"],\n    )\n    assert response[\"data\"][\"referenceNo\"] == redeem_response[\"data\"][\"referenceNo\"]\n\n\ndef test_gift_card_create_dual_token_and_redeem(liveClient):\n    response = liveClient.gift_card_create_dual_token(\n        baseToken=\"USDT\", faceToken=\"BNB\", baseTokenAmount=1.0\n    )\n    assert response[\"data\"][\"referenceNo\"] is not None\n    assert response[\"data\"][\"code\"] is not None\n    # verify the gift card\n    response = liveClient.gift_card_verify(referenceNo=response[\"data\"][\"referenceNo\"])\n    assert response[\"data\"][\"valid\"] == \"SUCCESS\"\n    # redeem the gift card\n    redeem_response = liveClient.gift_card_redeem(\n        code=response[\"data\"][\"code\"],\n    )\n    assert response[\"data\"][\"referenceNo\"] == redeem_response[\"data\"][\"referenceNo\"]\n"
  },
  {
    "path": "tests/test_client_margin.py",
    "content": "import pytest\n\n\npytestmark = pytest.mark.margin\n\n\ndef test_margin__get_account_status(client):\n    client.get_account_status()\n\n\ndef test_margin_get_account_api_trading_status(client):\n    client.get_account_api_trading_status()\n\n\ndef test_margin_get_account_api_permissions(client):\n    client.get_account_api_permissions()\n\n\ndef test_margin_get_dust_assets(client):\n    client.get_dust_assets()\n\n\ndef test_margin_get_dust_log(client):\n    client.test_get_dust_log()\n\n\ndef test_margin_transfer_dust(client):\n    client.transfer_dust()\n\n\ndef test_margin_get_asset_dividend_history(client):\n    client.get_asset_dividend_history()\n\n\ndef test_margin_make_universal_transfer(client):\n    client.make_universal_transfer()\n\n\ndef test_margin_query_universal_transfer_history(client):\n    client.query_universal_transfer_history()\n\n\ndef test_margin_get_trade_fee(client):\n    client.get_trade_fee()\n\n\ndef test_margin_get_asset_details(client):\n    client.get_asset_details()\n\n\ndef test_margin_get_spot_delist_schedule(client):\n    client.get_spot_delist_schedule()\n\n\n# Withdraw Endpoints\n\n\ndef test_margin_withdraw(client):\n    client.withdraw()\n\n\ndef test_margin_get_deposit_history(client):\n    client.get_deposit_history()\n\n\ndef test_margin_get_withdraw_history(client):\n    client.get_withdraw_history()\n\n\ndef test_margin_get_withdraw_history_id(client):\n    client.get_withdraw_history_id()\n\n\ndef test_margin_get_deposit_address(client):\n    client.get_deposit_address()\n\n\n# Margin Trading Endpoints\n\n\ndef test_margin_get_margin_account(client):\n    client.get_margin_account()\n\n\ndef test_margin_get_isolated_margin_account(client):\n    client.get_isolated_margin_account()\n\n\ndef test_margin_enable_isolated_margin_account(client):\n    client.enable_isolated_margin_account()\n\n\ndef test_margin_disable_isolated_margin_account(client):\n    client.disable_isolated_margin_account()\n\n\ndef test_margin_get_enabled_isolated_margin_account_limit(client):\n    client.get_enabled_isolated_margin_account_limit()\n\n\ndef test_margin_get_margin_dustlog(client):\n    client.get_margin_dustlog()\n\n\ndef test_margin_get_margin_dust_assets(client):\n    client.get_margin_dust_assets()\n\n\ndef test_margin_transfer_margin_dust(client):\n    client.transfer_margin_dust()\n\n\ndef test_margin_get_cross_margin_collateral_ratio(client):\n    client.get_cross_margin_collateral_ratio()\n\n\ndef test_margin_get_small_liability_exchange_assets(client):\n    client.get_small_liability_exchange_assets()\n\n\ndef test_margin_exchange_small_liability_assets(client):\n    client.exchange_small_liability_assets()\n\n\ndef test_margin_get_small_liability_exchange_history(client):\n    client.get_small_liability_exchange_history()\n\n\ndef test_margin_get_future_hourly_interest_rate(client):\n    client.get_future_hourly_interest_rate()\n\n\ndef test_margin_get_margin_capital_flow(client):\n    client.get_margin_capital_flow()\n\n\ndef test_margin_get_margin_asset(client):\n    client.get_margin_asset()\n\n\ndef test_margin_get_margin_symbol(client):\n    client.get_margin_symbol()\n\n\ndef test_margin_get_margin_all_assets(client):\n    client.get_margin_all_assets()\n\n\ndef test_margin_get_margin_all_pairs(client):\n    client.get_margin_all_pairs()\n\n\ndef test_margin_create_isolated_margin_account(client):\n    client.create_isolated_margin_account()\n\n\ndef test_margin_get_isolated_margin_symbol(client):\n    client.get_isolated_margin_symbol()\n\n\ndef test_margin_get_all_isolated_margin_symbols(client):\n    client.get_all_isolated_margin_symbols()\n\n\ndef test_margin_get_isolated_margin_fee_data(client):\n    client.get_isolated_margin_fee_data()\n\n\ndef test_margin_get_isolated_margin_tier_data(client):\n    client.get_isolated_margin_tier_data()\n\n\ndef test_margin_margin_manual_liquidation(client):\n    client.margin_manual_liquidation()\n\n\ndef test_margin_toggle_bnb_burn_spot_margin(client):\n    client.toggle_bnb_burn_spot_margin()\n\n\ndef test_margin_get_bnb_burn_spot_margin(client):\n    client.get_bnb_burn_spot_margin()\n\n\ndef test_margin_get_margin_price_index(client):\n    client.get_margin_price_index()\n\n\ndef test_margin_transfer_margin_to_spot(client):\n    client.transfer_margin_to_spot()\n\n\ndef test_margin_transfer_spot_to_margin(client):\n    client.transfer_spot_to_margin()\n\n\ndef test_margin_transfer_isolated_margin_to_spot(client):\n    client.transfer_isolated_margin_to_spot()\n\n\ndef test_margin_transfer_spot_to_isolated_margin(client):\n    client.transfer_spot_to_isolated_margin()\n\n\ndef test_margin_get_isolated_margin_tranfer_history(client):\n    client.get_isolated_margin_tranfer_history()\n\n\ndef test_margin_create_margin_loan(client):\n    client.create_margin_loan()\n\n\ndef test_margin_repay_margin_loan(client):\n    client.repay_margin_loan()\n\n\ndef create_margin_ordertest_(client):\n    client.create_margin_order()\n\n\ndef test_margin_cancel_margin_order(client):\n    client.cancel_margin_order()\n\n\ndef test_margin_set_margin_max_leverage(client):\n    client.set_margin_max_leverage()\n\n\ndef test_margin_get_margin_transfer_history(client):\n    client.get_margin_transfer_history()\n\n\ndef test_margin_get_margin_loan_details(client):\n    client.get_margin_loan_details()\n\n\ndef test_margin_get_margin_repay_details(client):\n    client.get_margin_repay_details()\n\n\ndef test_margin_get_cross_margin_data(client):\n    client.get_cross_margin_data()\n\n\ndef test_margin_get_margin_interest_history(client):\n    client.get_margin_interest_history()\n\n\ndef test_margin_get_margin_force_liquidation_rec(client):\n    client.get_margin_force_liquidation_rec()\n\n\ndef test_margin_get_margin_order(client):\n    client.get_margin_order()\n\n\ndef test_margin_get_open_margin_orders(client):\n    client.get_open_margin_orders()\n\n\ndef test_margin_get_all_margin_orders(client):\n    client.get_all_margin_orders()\n\n\ndef test_margin_get_margin_trades(client):\n    client.get_margin_trades()\n\n\ndef test_margin_get_max_margin_loan(client):\n    client.get_max_margin_loan()\n\n\ndef test_margin_get_max_margin_transfer(client):\n    client.get_max_margin_transfer()\n\n\ndef test_margin_get_margin_delist_schedule(client):\n    client.get_margin_delist_schedule()\n\n\n# Margin OCO\n\n\ndef test_margin_create_margin_oco_order(client):\n    client.create_margin_oco_order()\n\n\ndef test_margin_cancel_margin_oco_order(client):\n    client.cancel_margin_oco_order()\n\n\ndef test_margin_get_margin_oco_order(client):\n    client.get_margin_oco_order()\n\n\ndef test_margin_get_open_margin_oco_orders(client):\n    client.get_open_margin_oco_orders()\n\n\n# Cross-margin\n\n\ndef test_margin_margin_stream_get_listen_key(client):\n    client.margin_stream_get_listen_key()\n\n\ndef test_margin_margin_stream_close(client):\n    client.margin_stream_close()\n\n\n# Isolated margin\n\n\ndef test_margin_isolated_margin_stream_get_listen_key(client):\n    client.isolated_margin_stream_get_listen_key()\n\n\ndef test_margin_isolated_margin_stream_close(client):\n    client.isolated_margin_stream_close()\n\n\n# Simple Earn Endpoints\n\n\ndef test_margin_get_simple_earn_flexible_product_list(client):\n    client.get_simple_earn_flexible_product_list()\n\n\ndef test_margin_get_simple_earn_locked_product_list(client):\n    client.get_simple_earn_locked_product_list()\n\n\ndef test_margin_subscribe_simple_earn_flexible_product(client):\n    client.subscribe_simple_earn_flexible_product()\n\n\ndef test_margin_subscribe_simple_earn_locked_product(client):\n    client.subscribe_simple_earn_locked_product()\n\n\ndef test_margin_redeem_simple_earn_flexible_product(client):\n    client.redeem_simple_earn_flexible_product()\n\n\ndef test_margin_redeem_simple_earn_locked_product(client):\n    client.redeem_simple_earn_locked_product()\n\n\ndef test_margin_get_simple_earn_flexible_product_position(client):\n    client.get_simple_earn_flexible_product_position()\n\n\ndef test_margin_get_simple_earn_locked_product_position(client):\n    client.get_simple_earn_locked_product_position()\n\n\ndef test_margin_get_simple_earn_account(client):\n    client.get_simple_earn_account()\n\n\n# Lending Endpoints\n\n\ndef test_margin_get_fixed_activity_project_list(client):\n    client.get_fixed_activity_project_list()\n\n\ndef test_margin_change_fixed_activity_to_daily_position(client):\n    client.change_fixed_activity_to_daily_position()\n\n\n# Staking Endpoints\n\n\ndef test_margin_get_staking_product_list(client):\n    client.get_staking_product_list()\n\n\ndef test_margin_purchase_staking_product(client):\n    client.purchase_staking_product()\n\n\ndef test_margin_redeem_staking_product(client):\n    client.redeem_staking_product()\n\n\ndef test_margin_get_staking_position(client):\n    client.get_staking_position()\n\n\ndef test_margin_get_staking_purchase_history(client):\n    client.get_staking_purchase_history()\n\n\ndef test_margin_set_auto_staking(client):\n    client.set_auto_staking()\n\n\ndef test_margin_get_personal_left_quota(client):\n    client.get_personal_left_quota()\n\n\n# US Staking Endpoints\n\n\ndef test_margin_get_staking_asset_us(client):\n    client.get_staking_asset_us()\n\n\ndef test_margin_stake_asset_us(client):\n    client.stake_asset_us()\n\n\ndef test_margin_unstake_asset_us(client):\n    client.unstake_asset_us()\n\n\ndef test_margin_get_staking_balance_us(client):\n    client.get_staking_balance_us()\n\n\ndef test_margin_get_staking_history_us(client):\n    client.get_staking_history_us()\n\n\ndef test_margin_get_staking_rewards_history_us(client):\n    client.get_staking_rewards_history_us()\n\n\n# Sub Accounts\n\n\ndef test_margin_get_sub_account_list(client):\n    client.get_sub_account_list()\n\n\ndef test_margin_get_sub_account_transfer_history(client):\n    client.get_sub_account_transfer_history()\n\n\ndef test_margin_get_sub_account_futures_transfer_history(client):\n    client.get_sub_account_futures_transfer_history()\n\n\ndef test_margin_create_sub_account_futures_transfer(client):\n    client.create_sub_account_futures_transfer()\n\n\ndef test_margin_get_sub_account_assets(client):\n    client.get_sub_account_assets()\n\n\ndef test_margin_query_subaccount_spot_summary(client):\n    client.query_subaccount_spot_summary()\n\n\ndef test_margin_get_subaccount_deposit_address(client):\n    client.get_subaccount_deposit_address()\n\n\ndef test_margin_get_subaccount_deposit_history(client):\n    client.get_subaccount_deposit_history()\n\n\ndef test_margin_get_subaccount_futures_margin_status(client):\n    client.get_subaccount_futures_margin_status()\n\n\ndef test_margin_enable_subaccount_margin(client):\n    client.enable_subaccount_margin()\n\n\ndef test_margin_get_subaccount_margin_details(client):\n    client.get_subaccount_margin_details()\n\n\ndef test_margin_get_subaccount_margin_summary(client):\n    client.get_subaccount_margin_summary()\n\n\ndef test_margin_enable_subaccount_futures(client):\n    client.enable_subaccount_futures()\n\n\ndef test_margin_get_subaccount_futures_details(client):\n    client.get_subaccount_futures_details()\n\n\ndef test_margin_get_subaccount_futures_summary(client):\n    client.get_subaccount_futures_summary()\n\n\ndef test_margin_get_subaccount_futures_positionrisk(client):\n    client.get_subaccount_futures_positionrisk()\n\n\ndef test_margin_make_subaccount_futures_transfer(client):\n    client.make_subaccount_futures_transfer()\n\n\ndef test_margin_make_subaccount_margin_transfer(client):\n    client.make_subaccount_margin_transfer()\n\n\ndef test_margin_make_subaccount_to_subaccount_transfer(client):\n    client.make_subaccount_to_subaccount_transfer()\n\n\ndef test_margin_make_subaccount_to_master_transfer(client):\n    client.make_subaccount_to_master_transfer()\n\n\ndef test_margin_get_subaccount_transfer_history(client):\n    client.get_subaccount_transfer_history()\n\n\ndef test_margin_make_subaccount_universal_transfer(client):\n    client.make_subaccount_universal_transfer()\n\n\ndef test_margin_get_universal_transfer_history(client):\n    client.get_universal_transfer_history()\n\n\n# Fiat Endpoints\n\n\ndef test_margin_get_fiat_deposit_withdraw_history(client):\n    client.get_fiat_deposit_withdraw_history()\n\n\ndef test_margin_get_fiat_payments_history(client):\n    client.get_fiat_payments_history()\n\n\n# C2C Endpoints\n\n\ndef test_margin_get_c2c_trade_history(client):\n    client.get_c2c_trade_history()\n\n\n# Pay Endpoints\n\n\ndef test_margin_get_pay_trade_history(client):\n    client.get_pay_trade_history()\n\n\n# Convert Endpoints\n\n\ndef test_margin_get_convert_trade_history(client):\n    client.get_convert_trade_history()\n\n\ndef test_margin_convert_request_quote(client):\n    client.convert_request_quote()\n\n\ndef test_margin_convert_accept_quote(client):\n    client.convert_accept_quote()\n\n\ndef test_margin_new_transfer_history(futuresClient):\n    futuresClient.new_transfer_history()\n\n\ndef test_margin_funding_wallet(futuresClient):\n    futuresClient.funding_wallet()\n\n\ndef test_margin_get_user_asset(futuresClient):\n    futuresClient.get_user_asset()\n\n\ndef test_margin_universal_transfer(futuresClient):\n    futuresClient.universal_transfer()\n\n\ndef test_margin_get_all_coins_info(client):\n    client.get_all_coins_info()\n\n\ndef test_margin_get_account_snapshot(client):\n    client.get_account_snapshot()\n\n\ndef test_margin_disable_fast_withdraw_switch(client):\n    client.disable_fast_withdraw_switch()\n\n\ndef test_margin_enable_fast_withdraw_switch(client):\n    client.enable_fast_withdraw_switch()\n\n\n@pytest.mark.skip(reason=\"can't test margin endpoints\")\ndef test_margin_next_hourly_interest_rate(client):\n    client.margin_next_hourly_interest_rate(\n        assets=\"BTC\",\n        isIsolated=\"FALSE\"\n    )\n\n\n@pytest.mark.skip(reason=\"can't test margin endpoints\")\ndef test_margin_interest_history(client):\n    client.margin_interest_history(\n        asset=\"BTC\",\n    )\n\n\n@pytest.mark.skip(reason=\"can't test margin endpoints\")\ndef test_margin_borrow_repay(client):\n    client.margin_borrow_repay(\n        asset=\"BTC\",\n        amount=0.1,\n        isIsolated=\"FALSE\",\n        symbol=\"BTCUSDT\",\n        type=\"BORROW\"\n    )\n\n\n@pytest.mark.skip(reason=\"can't test margin endpoints\")\ndef test_margin_get_borrow_repay_records(client):\n    client.margin_get_borrow_repay_records(\n        asset=\"BTC\",\n        isolatedSymbol=\"BTCUSDT\",\n        txId=2970933056,\n        startTime=1563438204000,\n        endTime=1563438204000,\n        current=1,\n        size=10\n    )\n\n@pytest.mark.skip(reason=\"can't test margin endpoints\")\ndef test_margin_interest_rate_history(client):\n    client.margin_interest_rate_history(\n        asset=\"BTC\",\n    )\n\n@pytest.mark.skip(reason=\"can't test margin endpoints\")\ndef test_margin_max_borrowable(client):\n    client.margin_max_borrowable(\n        asset=\"BTC\",\n    )\n"
  },
  {
    "path": "tests/test_client_options.py",
    "content": "import pytest\nimport sys\n\n\npytestmark = [pytest.mark.options, pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")]\n\n\n@pytest.fixture\ndef options_symbol(liveClient):\n    prices = liveClient.options_price()\n    return prices[0][\"symbol\"]\n\n\ndef test_options_ping(liveClient):\n    liveClient.options_ping()\n\n\ndef test_options_time(liveClient):\n    liveClient.options_time()\n\n\n@pytest.mark.skip(reason=\"Not implemented\")\ndef test_options_info(liveClient):\n    liveClient.options_info()\n\n\ndef test_options_exchange_info(liveClient):\n    liveClient.options_exchange_info()\n\n\ndef test_options_index_price(liveClient):\n    liveClient.options_index_price(underlying=\"BTCUSDT\")\n\n\ndef test_options_price(liveClient):\n    liveClient.options_price()\n\n\ndef test_options_mark_price(liveClient):\n    liveClient.options_mark_price()\n\n\ndef test_options_order_book(liveClient, options_symbol):\n    liveClient.options_order_book(symbol=options_symbol)\n\n\ndef test_options_klines(liveClient, options_symbol):\n    liveClient.options_klines(symbol=options_symbol, interval=\"1m\")\n\n\ndef test_options_recent_trades(liveClient, options_symbol):\n    liveClient.options_recent_trades(symbol=options_symbol)\n\n\ndef test_options_historical_trades(liveClient, options_symbol):\n    liveClient.options_historical_trades(symbol=options_symbol)\n\n\n# Account and trading interface endpoints\n\n\n@pytest.mark.skip(reason=\"No sandbox to environmnet to test\")\ndef test_options_account_info(liveClient):\n    liveClient.options_account_info()\n\n\n@pytest.mark.skip(reason=\"No sandbox to environmnet to test\")\ndef test_options_funds_transfer(liveClient):\n    liveClient.options_funds_transfer()\n\n\n@pytest.mark.skip(reason=\"No sandbox to environmnet to test\")\ndef test_options_positions(liveClient):\n    liveClient.options_positions()\n\n\n@pytest.mark.skip(reason=\"No sandbox to environmnet to test\")\ndef test_options_bill(liveClient):\n    liveClient.options_bill()\n\n\n@pytest.mark.skip(reason=\"No sandbox to environmnet to test\")\ndef test_options_place_order(liveClient):\n    liveClient.options_place_order()\n\n\n@pytest.mark.skip(reason=\"No sandbox to environmnet to test\")\ndef test_test_options_place_batch_order(liveClient):\n    liveClient.test_options_place_batch_order()\n\n\n@pytest.mark.skip(reason=\"No sandbox to environmnet to test\")\ndef test_options_cancel_order(liveClient):\n    liveClient.options_cancel_order()\n\n\n@pytest.mark.skip(reason=\"No sandbox to environmnet to test\")\ndef test_options_cancel_batch_order(liveClient):\n    liveClient.options_cancel_batch_order()\n\n\n@pytest.mark.skip(reason=\"No sandbox to environmnet to test\")\ndef test_options_cancel_all_orders(liveClient):\n    liveClient.options_cancel_all_orders()\n\n\n@pytest.mark.skip(reason=\"No sandbox to environmnet to test\")\ndef test_options_query_order(liveClient):\n    liveClient.options_query_order()\n\n\n@pytest.mark.skip(reason=\"No sandbox to environmnet to test\")\ndef test_options_query_pending_orders(liveClient):\n    liveClient.options_query_pending_orders()\n\n\n@pytest.mark.skip(reason=\"No sandbox to environmnet to test\")\ndef test_options_query_order_history(liveClient):\n    liveClient.options_query_order_history()\n\n\n@pytest.mark.skip(reason=\"No sandbox to environmnet to test\")\ndef test_options_user_trades(liveClient):\n    liveClient.options_user_trades()\n"
  },
  {
    "path": "tests/test_client_portfolio.py",
    "content": "import pytest\n\n# Apply the 'portfolio' mark to all tests in this file\npytestmark = pytest.mark.portfolio\n\n\ndef test_papi_get_balance(client):\n    client.papi_get_balance()\n\n\ndef test_papi_get_account(client):\n    client.papi_get_account()\n\n\ndef test_papi_get_margin_max_borrowable(client):\n    client.papi_get_margin_max_borrowable()\n\n\ndef test_papi_get_margin_max_withdraw(client):\n    client.papi_get_margin_max_withdraw()\n\n\ndef test_papi_get_um_position_risk(client):\n    client.papi_get_um_position_risk()\n\n\ndef test_papi_get_cm_position_risk(client):\n    client.papi_get_cm_position_risk()\n\n\ndef test_papi_set_um_leverage(client):\n    client.papi_set_um_leverage()\n\n\ndef test_papi_set_cm_leverage(client):\n    client.papi_set_cm_leverage()\n\n\ndef test_papi_change_um_position_side_dual(client):\n    client.papi_change_um_position_side_dual()\n\n\ndef test_papi_get_um_position_side_dual(client):\n    client.papi_get_um_position_side_dual()\n\n\ndef test_papi_get_cm_position_side_dual(client):\n    client.papi_get_cm_position_side_dual()\n\n\ndef test_papi_get_um_leverage_bracket(client):\n    client.papi_get_um_leverage_bracket()\n\n\ndef test_papi_get_cm_leverage_bracket(client):\n    client.papi_get_cm_leverage_bracket()\n\n\ndef test_papi_get_um_api_trading_status(client):\n    client.papi_get_um_api_trading_status()\n\n\ndef test_papi_get_um_comission_rate(client):\n    client.papi_get_um_comission_rate()\n\n\ndef test_papi_get_cm_comission_rate(client):\n    client.papi_get_cm_comission_rate()\n\n\ndef test_papi_get_margin_margin_loan(client):\n    client.papi_get_margin_margin_loan()\n\n\ndef test_papi_get_margin_repay_loan(client):\n    client.papi_get_margin_repay_loan()\n\n\ndef test_papi_get_repay_futures_switch(client):\n    client.papi_get_repay_futures_switch()\n\n\ndef test_papi_repay_futures_switch(client):\n    client.papi_repay_futures_switch()\n\n\ndef test_papi_get_margin_interest_history(client):\n    client.papi_get_margin_interest_history()\n\n\ndef test_papi_repay_futures_negative_balance(client):\n    client.papi_repay_futures_negative_balance()\n\n\ndef test_papi_get_portfolio_interest_history(client):\n    client.papi_get_portfolio_interest_history()\n\n\ndef test_papi_fund_auto_collection(client):\n    client.papi_fund_auto_collection()\n\n\ndef test_papi_fund_asset_collection(client):\n    client.papi_fund_asset_collection()\n\n\ndef test_papi_bnb_transfer(client):\n    client.papi_bnb_transfer()\n\n\ndef test_papi_get_um_income_history(client):\n    client.papi_get_um_income_history()\n\n\ndef test_papi_get_cm_income_history(client):\n    client.papi_get_cm_income_history()\n\n\ndef test_papi_get_um_account(client):\n    client.papi_get_um_account()\n\n\ndef test_papi_get_um_account_v2(client):\n    client.papi_get_um_account_v2()\n\n\ndef test_papi_get_cm_account(client):\n    client.papi_get_cm_account()\n\n\ndef test_papi_get_um_account_config(client):\n    client.papi_get_um_account_config()\n\n\ndef test_papi_get_um_symbol_config(client):\n    client.papi_get_um_symbol_config()\n\n\ndef test_papi_get_um_trade_asyn(client):\n    client.papi_get_um_trade_asyn()\n\n\ndef test_papi_get_um_trade_asyn_id(client):\n    client.papi_get_um_trade_asyn_id()\n\n\ndef test_papi_get_um_order_asyn(client):\n    client.papi_get_um_order_asyn()\n\n\ndef test_papi_get_um_order_asyn_id(client):\n    client.papi_get_um_order_asyn_id()\n\n\ndef test_papi_get_um_income_asyn(client):\n    client.papi_get_um_income_asyn()\n\n\ndef test_papi_get_um_income_asyn_id(client):\n    client.papi_get_um_income_asyn_id()\n\n\n# Public papi endpoints\n\n\ndef test_papi_ping(client):\n    client.papi_ping()\n\n\n# Trade papi endpoints\n\n\ndef test_papi_create_um_order(client):\n    client.papi_create_um_order()\n\n\ndef test_papi_create_um_conditional_order(client):\n    client.papi_create_um_conditional_order()\n\n\ndef test_papi_create_cm_order(client):\n    client.papi_create_cm_order()\n\n\ndef test_papi_create_cm_conditional_order(client):\n    client.papi_create_cm_conditional_order()\n\n\ndef test_papi_create_margin_order(client):\n    client.papi_create_margin_order()\n\n\ndef test_papi_margin_loan(client):\n    client.papi_margin_loan()\n\n\ndef test_papi_repay_loan(client):\n    client.papi_repay_loan()\n\n\ndef test_papi_margin_order_oco(client):\n    client.papi_margin_order_oco()\n\n\ndef test_papi_cancel_um_order(client):\n    client.papi_cancel_um_order()\n\n\ndef test_papi_cancel_um_all_open_orders(client):\n    client.papi_cancel_um_all_open_orders()\n\n\ndef test_papi_cancel_um_conditional_order(client):\n    client.papi_cancel_um_conditional_order()\n\n\ndef test_papi_cancel_um_conditional_all_open_orders(client):\n    client.papi_cancel_um_conditional_all_open_orders()\n\n\ndef test_papi_cancel_cm_order(client):\n    client.papi_cancel_cm_order()\n\n\ndef test_papi_cancel_cm_all_open_orders(client):\n    client.papi_cancel_cm_all_open_orders()\n\n\ndef test_papi_cancel_cm_conditional_order(client):\n    client.papi_cancel_cm_conditional_order()\n\n\ndef test_papi_cancel_cm_conditional_all_open_orders(client):\n    client.papi_cancel_cm_conditional_all_open_orders()\n\n\ndef test_papi_cancel_margin_order(client):\n    client.papi_cancel_margin_order()\n\n\ndef test_papi_cancel_margin_order_list(client):\n    client.papi_cancel_margin_order_list()\n\n\ndef test_papi_cancel_margin_all_open_orders(client):\n    client.papi_cancel_margin_all_open_orders()\n\n\ndef test_papi_modify_um_order(client):\n    client.papi_modify_um_order()\n\n\ndef test_papi_modify_cm_order(client):\n    client.papi_modify_cm_order()\n\n\ndef test_papi_get_um_order(client):\n    client.papi_get_um_order()\n\n\ndef test_papi_get_um_all_orders(client):\n    client.papi_get_um_all_orders()\n\n\ndef test_papi_get_um_open_order(client):\n    client.papi_get_um_open_order()\n\n\ndef test_papi_get_um_open_orders(client):\n    client.papi_get_um_open_orders()\n\n\ndef test_papi_get_um_conditional_all_orders(client):\n    client.papi_get_um_conditional_all_orders()\n\n\ndef test_papi_get_um_conditional_open_orders(client):\n    client.papi_get_um_conditional_open_orders()\n\n\ndef test_papi_get_um_conditional_open_order(client):\n    client.papi_get_um_conditional_open_order()\n\n\ndef test_papi_get_um_conditional_order_history(client):\n    client.papi_get_um_conditional_order_history()\n\n\ndef test_papi_get_cm_order(client):\n    client.papi_get_cm_order()\n\n\ndef test_papi_get_cm_all_orders(client):\n    client.papi_get_cm_all_orders()\n\n\ndef test_papi_get_cm_open_order(client):\n    client.papi_get_cm_open_order()\n\n\ndef test_papi_get_cm_open_orders(client):\n    client.papi_get_cm_open_orders()\n\n\ndef test_papi_get_cm_conditional_all_orders(client):\n    client.papi_get_cm_conditional_all_orders()\n\n\ndef test_papi_get_cm_conditional_open_orders(client):\n    client.papi_get_cm_conditional_open_orders()\n\n\ndef test_papi_get_cm_conditional_open_order(client):\n    client.papi_get_cm_conditional_open_order()\n\n\ndef test_papi_get_cm_conditional_order_history(client):\n    client.papi_get_cm_conditional_order_history()\n\n\ndef test_papi_get_um_force_orders(client):\n    client.papi_get_um_force_orders()\n\n\ndef test_papi_get_cm_force_orders(client):\n    client.papi_get_cm_force_orders()\n\n\ndef test_papi_get_um_order_amendment(client):\n    client.papi_get_um_order_amendment()\n\n\ndef test_papi_get_cm_order_amendment(client):\n    client.papi_get_cm_order_amendment()\n\n\ndef test_papi_get_margin_force_orders(client):\n    client.papi_get_margin_force_orders()\n\n\ndef test_papi_get_um_user_trades(client):\n    client.papi_get_um_user_trades()\n\n\ndef test_papi_get_cm_user_trades(client):\n    client.papi_get_cm_user_trades()\n\n\ndef test_papi_get_um_adl_quantile(client):\n    client.papi_get_um_adl_quantile()\n\n\ndef test_papi_get_cm_adl_quantile(client):\n    client.papi_get_cm_adl_quantile()\n\n\ndef test_papi_set_um_fee_burn(client):\n    client.papi_set_um_fee_burn()\n\n\ndef test_papi_get_um_fee_burn(client):\n    client.papi_get_um_fee_burn()\n\n\ndef test_papi_get_margin_order(client):\n    client.papi_get_margin_order()\n\n\ndef test_papi_get_margin_open_orders(client):\n    client.papi_get_margin_open_orders()\n\n\ndef test_papi_get_margin_all_orders(client):\n    client.papi_get_margin_all_orders()\n\n\ndef test_papi_get_margin_order_list(client):\n    client.papi_get_margin_order_list()\n\n\ndef test_papi_get_margin_all_order_list(client):\n    client.papi_get_margin_all_order_list()\n\n\ndef test_papi_get_margin_open_order_list(client):\n    client.papi_get_margin_open_order_list()\n\n\ndef test_papi_get_margin_my_trades(client):\n    client.papi_get_margin_my_trades()\n\n\ndef test_papi_get_margin_repay_debt(client):\n    client.papi_get_margin_repay_debt()\n\n\ndef test_close_connection(client):\n    client.close_connection()\n"
  },
  {
    "path": "tests/test_client_ws_api.py",
    "content": "import sys\nimport pytest\nfrom binance.client import Client\nfrom .conftest import proxies, api_key, api_secret, testnet\nfrom .test_get_order_book import assert_ob\n\npytestmark = [pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")]\n\ndef test_ws_get_order_book(client):\n    orderbook = client.ws_get_order_book(symbol=\"BTCUSDT\")\n    assert_ob(orderbook)\n\n\ndef test_ws_get_recent_trades(client):\n    client.ws_get_recent_trades(symbol=\"BTCUSDT\")\n\n\ndef test_ws_get_historical_trades(client):\n    client.ws_get_historical_trades(symbol=\"BTCUSDT\")\n\n\ndef test_ws_get_aggregate_trades(client):\n    client.ws_get_aggregate_trades(symbol=\"BTCUSDT\")\n\n\ndef test_ws_get_klines(client):\n    client.ws_get_klines(symbol=\"BTCUSDT\", interval=\"1m\")\n\n\ndef test_ws_get_uiKlines(client):\n    client.ws_get_uiKlines(symbol=\"BTCUSDT\", interval=\"1m\")\n\n\ndef test_ws_get_avg_price(client):\n    client.ws_get_avg_price(symbol=\"BTCUSDT\")\n\n\ndef test_ws_get_ticker(client):\n    client.ws_get_ticker(symbol=\"BTCUSDT\")\n\n\ndef test_ws_get_trading_day_ticker(client):\n    client.ws_get_trading_day_ticker(symbol=\"BTCUSDT\")\n\n\ndef test_ws_get_symbol_ticker_window(client):\n    client.ws_get_symbol_ticker_window(symbol=\"BTCUSDT\")\n\n\ndef test_ws_get_symbol_ticker(client):\n    client.ws_get_symbol_ticker(symbol=\"BTCUSDT\")\n\n\ndef test_ws_get_orderbook_ticker(client):\n    client.ws_get_orderbook_ticker(symbol=\"BTCUSDT\")\n\n\ndef test_ws_ping(client):\n    client.ws_ping()\n\n\ndef test_ws_get_time(client):\n    client.ws_get_time()\n\n\ndef test_ws_get_exchange_info(client):\n    client.ws_get_exchange_info(symbol=\"BTCUSDT\")\n\n\ndef test_ws_time_microseconds():\n    micro_client = Client(\n        api_key,\n        api_secret,\n        {\"proxies\": proxies},\n        testnet=testnet,\n        time_unit=\"MICROSECOND\",\n    )\n    micro_trades = micro_client.ws_get_recent_trades(symbol=\"BTCUSDT\")\n    assert len(str(micro_trades[0][\"time\"])) >= 16, (\n        \"WS time should be in microseconds (16+ digits)\"\n    )\n\n\ndef test_ws_time_milliseconds():\n    milli_client = Client(\n        api_key,\n        api_secret,\n        {\"proxies\": proxies},\n        testnet=testnet,\n        time_unit=\"MILLISECOND\",\n    )\n    milli_trades = milli_client.ws_get_recent_trades(symbol=\"BTCUSDT\")\n    assert len(str(milli_trades[0][\"time\"])) == 13, (\n        \"WS time should be in milliseconds (13 digits)\"\n    )\n"
  },
  {
    "path": "tests/test_client_ws_futures_requests.py",
    "content": "import pytest\nimport sys\nfrom binance.exceptions import BinanceAPIException\nfrom .test_get_order_book import assert_ob\nfrom .test_order import assert_contract_order\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\ndef test_ws_futures_get_order_book(futuresClient):\n    orderbook = futuresClient.ws_futures_get_order_book(symbol=\"BTCUSDT\")\n    assert_ob(orderbook)\n\n\ndef test_bad_request(futuresClient):\n    with pytest.raises(BinanceAPIException):\n        futuresClient.ws_futures_get_order_book()\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\ndef test_ws_futures_get_all_tickers(futuresClient):\n    futuresClient.ws_futures_get_all_tickers()\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\ndef test_ws_futures_get_order_book_ticker(futuresClient):\n    futuresClient.ws_futures_get_order_book_ticker()\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\ndef test_ws_futures_create_get_edit_cancel_order(futuresClient):\n    ticker = futuresClient.ws_futures_get_order_book_ticker(symbol=\"LTCUSDT\")\n    positions = futuresClient.ws_futures_v2_account_position(symbol=\"LTCUSDT\")\n    order = futuresClient.ws_futures_create_order(\n        symbol=ticker[\"symbol\"],\n        side=\"SELL\",\n        positionSide=positions[0][\"positionSide\"],\n        type=\"LIMIT\",\n        timeInForce=\"GTC\",\n        quantity=0.1,\n        price=str(round(float(ticker[\"bidPrice\"]) + 2)),\n    )\n    assert_contract_order(futuresClient, order)\n    order = futuresClient.ws_futures_edit_order(\n        orderid=order[\"orderId\"],\n        symbol=order[\"symbol\"],\n        quantity=0.11,\n        side=order[\"side\"],\n        price=order[\"price\"],\n    )\n    assert_contract_order(futuresClient, order)\n    order = futuresClient.ws_futures_get_order(\n        symbol=\"LTCUSDT\", orderid=order[\"orderId\"]\n    )\n    assert_contract_order(futuresClient, order)\n    order = futuresClient.ws_futures_cancel_order(\n        orderid=order[\"orderId\"], symbol=order[\"symbol\"]\n    )\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\ndef test_ws_futures_v2_account_position(futuresClient):\n    futuresClient.ws_futures_v2_account_position()\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\ndef test_ws_futures_account_position(futuresClient):\n    futuresClient.ws_futures_account_position()\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\ndef test_ws_futures_v2_account_balance(futuresClient):\n    futuresClient.ws_futures_v2_account_balance()\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\ndef test_ws_futures_account_balance(futuresClient):\n    futuresClient.ws_futures_account_balance()\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\ndef test_ws_futures_v2_account_status(futuresClient):\n    futuresClient.ws_futures_v2_account_status()\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\ndef test_ws_futures_account_status(futuresClient):\n    futuresClient.ws_futures_account_status()\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\ndef test_ws_futures_create_cancel_algo_order(futuresClient):\n    \"\"\"Test creating and canceling an algo order via websocket\"\"\"\n    ticker = futuresClient.ws_futures_get_order_book_ticker(symbol=\"LTCUSDT\")\n    positions = futuresClient.ws_futures_v2_account_position(symbol=\"LTCUSDT\")\n\n    # Create an algo order\n    order = futuresClient.ws_futures_create_algo_order(\n        symbol=ticker[\"symbol\"],\n        side=\"BUY\",\n        positionSide=positions[0][\"positionSide\"],\n        type=\"STOP_MARKET\",\n        algoType=\"CONDITIONAL\",\n        quantity=1,\n        triggerPrice=1000,\n    )\n\n    assert order[\"symbol\"] == ticker[\"symbol\"]\n    assert \"algoId\" in order\n    assert order[\"algoType\"] == \"CONDITIONAL\"\n\n    # Cancel the algo order\n    cancel_result = futuresClient.ws_futures_cancel_algo_order(\n        symbol=ticker[\"symbol\"], algoId=order[\"algoId\"]\n    )\n\n    assert cancel_result[\"algoId\"] == order[\"algoId\"]\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\ndef test_ws_futures_create_conditional_order_auto_routing(futuresClient):\n    \"\"\"Test that conditional order types are automatically routed to algo endpoint\"\"\"\n    ticker = futuresClient.ws_futures_get_order_book_ticker(symbol=\"LTCUSDT\")\n    positions = futuresClient.ws_futures_v2_account_position(symbol=\"LTCUSDT\")\n\n    trigger_price = float(ticker[\"askPrice\"]) * 1.5\n    order = futuresClient.ws_futures_create_order(\n        symbol=ticker[\"symbol\"],\n        side=\"BUY\",\n        positionSide=positions[0][\"positionSide\"],\n        type=\"STOP_MARKET\",\n        quantity=1,\n        triggerPrice=trigger_price,\n    )\n\n    assert order[\"symbol\"] == ticker[\"symbol\"]\n    assert \"algoId\" in order\n    assert order[\"algoType\"] == \"CONDITIONAL\"\n\n    # Cancel using algoId parameter\n    cancel_result = futuresClient.ws_futures_cancel_order(\n        symbol=ticker[\"symbol\"], algoId=order[\"algoId\"]\n    )\n    assert cancel_result[\"algoId\"] == order[\"algoId\"]\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\ndef test_ws_futures_conditional_order_with_stop_price(futuresClient):\n    \"\"\"Test that stopPrice is converted to triggerPrice for conditional orders\"\"\"\n    ticker = futuresClient.ws_futures_get_order_book_ticker(symbol=\"LTCUSDT\")\n    positions = futuresClient.ws_futures_v2_account_position(symbol=\"LTCUSDT\")\n\n    # Create a TAKE_PROFIT_MARKET order with stopPrice (should be converted to triggerPrice)\n    # Use a price above current market price for SELL TAKE_PROFIT\n    trigger_price = float(ticker[\"askPrice\"]) * 1.5\n    order = futuresClient.ws_futures_create_order(\n        symbol=ticker[\"symbol\"],\n        side=\"SELL\",\n        positionSide=positions[0][\"positionSide\"],\n        type=\"TAKE_PROFIT_MARKET\",\n        quantity=1,\n        stopPrice=trigger_price,  # This should be converted to triggerPrice\n    )\n\n    assert order[\"symbol\"] == ticker[\"symbol\"]\n    assert \"algoId\" in order\n    assert order[\"algoType\"] == \"CONDITIONAL\"\n\n    # Cancel the order\n    futuresClient.ws_futures_cancel_order(\n        symbol=ticker[\"symbol\"], algoId=order[\"algoId\"]\n    )\n"
  },
  {
    "path": "tests/test_cryptography.py",
    "content": "from binance.client import Client\n\ntest_cases = [\n    {\n        \"description\": \"Unencrypted PKCS8 ed22519 private key\",\n        \"private_key\": \"-----BEGIN PRIVATE KEY-----\\nMC4CAQAwBQYDK2VwBCIEIPQmzwVKJETqVd7L9E/DFbkvrOigy1tLL+9QF0mSn6dV\\n-----END PRIVATE KEY-----\\n\",\n        \"password\": None,\n        \"expected_signature\": \"a4Pm3p02D2HXtNfo3DBaVCe9Ov7kledewgYtGjekotFmZ5wXa3mC5AtLB7CpAphyNjeyovIuDP+9fyjYmsojCw==\",\n    },\n    {\n        \"description\": \"Unencrypted PKCS8 ed22519 private key in bytes\",\n        \"private_key\": b\"-----BEGIN PRIVATE KEY-----\\nMC4CAQAwBQYDK2VwBCIEIPQmzwVKJETqVd7L9E/DFbkvrOigy1tLL+9QF0mSn6dV\\n-----END PRIVATE KEY-----\\n\",\n        \"password\": None,\n        \"expected_signature\": \"a4Pm3p02D2HXtNfo3DBaVCe9Ov7kledewgYtGjekotFmZ5wXa3mC5AtLB7CpAphyNjeyovIuDP+9fyjYmsojCw==\",\n    },\n    {\n        \"description\": \"Encrypted PKCS8 RSA private key\",\n        \"private_key\": \"-----BEGIN ENCRYPTED PRIVATE KEY-----\\nMIIFNTBfBgkqhkiG9w0BBQ0wUjAxBgkqhkiG9w0BBQwwJAQQWW+iEMYYCPUntrPq\\nZ2RCMAICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEEIw3ViSuTp8JeN43\\n5VGlHt0EggTQBvEzd2w2F561CzU+MDouZDOPj4RTIStC471z0/bxTgYqH3gYchoe\\nOfi2lsLuD8B+ivIRuXB8GT66BIseIOMV8t/tiMe97rFI/cV4h6DrBO1xlmSrBG97\\nvFF9qPA5yPRlrHtWKkGxhXteNVsT3w/7Y7KsulO/gA2KpsOElMElOhUP462Yd0Wl\\nOxAIV3+knl2niozws2Kq3EdzTF3N6hlavUPryiU/w4RRsPN5qgjchVVLq/sYRYhx\\nN8uWJbkjhCcHsULkD5KkdgddR0VOhpQPXIdY+gPkSBJq1ltRWy/TYdXiU2fEBNZW\\nhFUVrxnS76+u2R3vukY2IAX8zTC6h2AbCBG+r4XXzgk/l/4peySKHsPQRzQ0in39\\na9o5sctOmUNeD4uJ6cClXDdqyEwXhnPmRKZjJ8qeH4D9wl7HOG7iQsYiyfJe/igi\\nFEXVRZOtLBdbwX45rU6wiWWjxzY+mDnw4BXE31ZBPwgtoh+CLTyK8NI8LnCV/CgO\\nzOY4sm/KDWmbfTTZjLSdYRFj7wEpOdUWjZ13viDFZqnmy/o1auvLmBcqbRrCyW+B\\nOMI7aHE0mZ/52vEFQYU1tH0BxMmRfWXUCJj0TjwxDY6BQmmW4YlhsrgGNekLFDo1\\n6phFd0pA4UPqGXfNLzHp1dtLhUEb4YzcpDn+HMzMf1gfez7qeqU28nNFg/AwwqHZ\\nTWdGclCFjiah7SfvOslob4vdLGwkUhgCBKQUQoU1DltX2GOgIv9SNY3q6X0NwdZG\\nL5gqk225WVUwIRzmi5nfUEXlbaTvyHg3BuGedUKJ91IhRCW1ZjvU8GQcfVsu8bse\\nTCKMdr7wi/zEZXSldCza6vL4m3tmBLtWkHVOW8bcDWvoVwRswbFHfleHzckl7EeC\\n9C4TRa66gA5UOv14SrpC8noQUNpSegg+1KI4BSNvwaheiSUqjQbisb0qYCxML0ZP\\nmQodwVsXG6LYo+Y6y6CpHbT7UYkfa59q/CGOZByL1bEzzgd98ZHwjihOjHVaV6sY\\nBW018AvGxr7kjEU4LNqIteydTp0o31ZJN/qK78w5EQFfJxfImrx/E4nYKtg4higj\\nKOQCgJALKIveidqQEFsbGWsulYrMXwnu0nPThofR1D8eCJZpdTxvOh2nIrNrAeY8\\nZMAwG1uQos5A0yEZ1auHxz+rb4errnk92OnVlWnElf1TwwlkFFNLdNDl8VpiMP40\\n6en9VtlOfgH8AwB03WsoeuEQsxYTIcRKWZZPRsLx3hd0BsOw0FcYDSX2XIGPkVVW\\niYf9hzFSQsWV3d6utloIm4nG8XONfNaRimGECbUSZyHZimrO1m4Gga5pE3LKuDri\\nJKR2lR7b6XPR7+FS+lG1zq5KY7onAVQY1oABfTjpJRju6pQGWt70hairo6EaVC3u\\nrBy8UkLwBbfDuigSvsVk+sF2+Ic0IzX6IniU0F5kMe+MKqGB4aicXP6FFGBpPFTe\\nv6yHD+DYAu1rnlXrqmFL50CfutTF78uPPJ9D2Sm0DcGPFj+6IrCigj48uxoHR9Qb\\nFeNzfsmVwoFAWWq/MpkPbX6Aql8ddCbpMxDUUkybwVV9rJmEMTLil44FrxKAKFhP\\n0Av7JeFvdz15pfnf/IQ3IOvVhHGFChFS13sbYSvFHMQF3P0BiyvjhBI=\\n-----END ENCRYPTED PRIVATE KEY-----\\n\",\n        \"password\": \"testpwd\",\n        \"expected_signature\": \"S4l9IONXGHIdt4NjwmpCIhawDTitjUQls73d+mi0HJTSbTGyn95NabX5hC9+n6HsTqLcWPvxKgTvLFMnTaf6Jxl+xwQMbu9/6mw88KF7i1pEQizerKcr91rPUPVBQ4OY10Q018QEamIAymRgo/eoRYSm7CqCdeibGyO0XfXZBaJnVGFJ9hgrPIwSKHgeUnfK8qMenULvL0qKMEJ6ziYPiqh7k9xX3xIV7lGIpokk+ekqlFd01f/Lov45osJCFuccJO4xuUUZewZnVGF7Uw6Rim3UsKhXKZUN9WZWa5RT+dpBIJ5DTBIXBSvowwj3GZC3j+XvWw8Sn0Ls9836l89BXw==\",\n    },\n    {\n        \"description\": \"Encrypted PKCS8 RSA private key in bytes\",\n        \"private_key\": b\"-----BEGIN ENCRYPTED PRIVATE KEY-----\\nMIIFNTBfBgkqhkiG9w0BBQ0wUjAxBgkqhkiG9w0BBQwwJAQQWW+iEMYYCPUntrPq\\nZ2RCMAICCAAwDAYIKoZIhvcNAgkFADAdBglghkgBZQMEASoEEIw3ViSuTp8JeN43\\n5VGlHt0EggTQBvEzd2w2F561CzU+MDouZDOPj4RTIStC471z0/bxTgYqH3gYchoe\\nOfi2lsLuD8B+ivIRuXB8GT66BIseIOMV8t/tiMe97rFI/cV4h6DrBO1xlmSrBG97\\nvFF9qPA5yPRlrHtWKkGxhXteNVsT3w/7Y7KsulO/gA2KpsOElMElOhUP462Yd0Wl\\nOxAIV3+knl2niozws2Kq3EdzTF3N6hlavUPryiU/w4RRsPN5qgjchVVLq/sYRYhx\\nN8uWJbkjhCcHsULkD5KkdgddR0VOhpQPXIdY+gPkSBJq1ltRWy/TYdXiU2fEBNZW\\nhFUVrxnS76+u2R3vukY2IAX8zTC6h2AbCBG+r4XXzgk/l/4peySKHsPQRzQ0in39\\na9o5sctOmUNeD4uJ6cClXDdqyEwXhnPmRKZjJ8qeH4D9wl7HOG7iQsYiyfJe/igi\\nFEXVRZOtLBdbwX45rU6wiWWjxzY+mDnw4BXE31ZBPwgtoh+CLTyK8NI8LnCV/CgO\\nzOY4sm/KDWmbfTTZjLSdYRFj7wEpOdUWjZ13viDFZqnmy/o1auvLmBcqbRrCyW+B\\nOMI7aHE0mZ/52vEFQYU1tH0BxMmRfWXUCJj0TjwxDY6BQmmW4YlhsrgGNekLFDo1\\n6phFd0pA4UPqGXfNLzHp1dtLhUEb4YzcpDn+HMzMf1gfez7qeqU28nNFg/AwwqHZ\\nTWdGclCFjiah7SfvOslob4vdLGwkUhgCBKQUQoU1DltX2GOgIv9SNY3q6X0NwdZG\\nL5gqk225WVUwIRzmi5nfUEXlbaTvyHg3BuGedUKJ91IhRCW1ZjvU8GQcfVsu8bse\\nTCKMdr7wi/zEZXSldCza6vL4m3tmBLtWkHVOW8bcDWvoVwRswbFHfleHzckl7EeC\\n9C4TRa66gA5UOv14SrpC8noQUNpSegg+1KI4BSNvwaheiSUqjQbisb0qYCxML0ZP\\nmQodwVsXG6LYo+Y6y6CpHbT7UYkfa59q/CGOZByL1bEzzgd98ZHwjihOjHVaV6sY\\nBW018AvGxr7kjEU4LNqIteydTp0o31ZJN/qK78w5EQFfJxfImrx/E4nYKtg4higj\\nKOQCgJALKIveidqQEFsbGWsulYrMXwnu0nPThofR1D8eCJZpdTxvOh2nIrNrAeY8\\nZMAwG1uQos5A0yEZ1auHxz+rb4errnk92OnVlWnElf1TwwlkFFNLdNDl8VpiMP40\\n6en9VtlOfgH8AwB03WsoeuEQsxYTIcRKWZZPRsLx3hd0BsOw0FcYDSX2XIGPkVVW\\niYf9hzFSQsWV3d6utloIm4nG8XONfNaRimGECbUSZyHZimrO1m4Gga5pE3LKuDri\\nJKR2lR7b6XPR7+FS+lG1zq5KY7onAVQY1oABfTjpJRju6pQGWt70hairo6EaVC3u\\nrBy8UkLwBbfDuigSvsVk+sF2+Ic0IzX6IniU0F5kMe+MKqGB4aicXP6FFGBpPFTe\\nv6yHD+DYAu1rnlXrqmFL50CfutTF78uPPJ9D2Sm0DcGPFj+6IrCigj48uxoHR9Qb\\nFeNzfsmVwoFAWWq/MpkPbX6Aql8ddCbpMxDUUkybwVV9rJmEMTLil44FrxKAKFhP\\n0Av7JeFvdz15pfnf/IQ3IOvVhHGFChFS13sbYSvFHMQF3P0BiyvjhBI=\\n-----END ENCRYPTED PRIVATE KEY-----\\n\",\n        \"password\": \"testpwd\",\n        \"expected_signature\": \"S4l9IONXGHIdt4NjwmpCIhawDTitjUQls73d+mi0HJTSbTGyn95NabX5hC9+n6HsTqLcWPvxKgTvLFMnTaf6Jxl+xwQMbu9/6mw88KF7i1pEQizerKcr91rPUPVBQ4OY10Q018QEamIAymRgo/eoRYSm7CqCdeibGyO0XfXZBaJnVGFJ9hgrPIwSKHgeUnfK8qMenULvL0qKMEJ6ziYPiqh7k9xX3xIV7lGIpokk+ekqlFd01f/Lov45osJCFuccJO4xuUUZewZnVGF7Uw6Rim3UsKhXKZUN9WZWa5RT+dpBIJ5DTBIXBSvowwj3GZC3j+XvWw8Sn0Ls9836l89BXw==\",\n    },\n]\n\n\ndef test_encryption():\n    data = {\n        \"symbol\": \"BTCUSDT\",\n        \"side\": \"BUY\",\n        \"type\": \"LIMIT\",\n        \"quantity\": 1,\n        \"timestamp\": 1631234567890,\n        \"price\": 50000,\n    }\n\n    for case in test_cases:\n        client = Client(\n            api_key=\"api_key\",\n            api_secret=\"api_secret\",\n            private_key=case[\"private_key\"],\n            private_key_pass=case[\"password\"],\n            ping=False,\n        )\n        signature = client._generate_signature(data, False)\n        assert signature == case[\"expected_signature\"], (\n            f\"Test failed: {case['description']}\"\n        )\n"
  },
  {
    "path": "tests/test_depth_cache.py",
    "content": "from binance.ws.depthcache import DepthCache\nfrom decimal import Decimal\nimport pytest\n\nTEST_SYMBOL = \"BNBBTC\"\n\n\n@pytest.fixture\ndef fresh_cache():\n    return DepthCache(TEST_SYMBOL, Decimal)\n\n\ndef test_add_bids(fresh_cache):\n    \"\"\"Verify basic functionality for adding a bid to the cache\"\"\"\n    high_bid = [0.111, 489]\n    mid_bid = [0.018, 300]\n    low_bid = [0.001, 100]\n    for bid in [high_bid, low_bid, mid_bid]:\n        fresh_cache.add_bid(bid)\n\n    bids = fresh_cache.get_bids()\n\n    assert len(bids) == 3\n\n    assert bids == sorted(bids, reverse=True)\n\n    assert isinstance(bids[0][0], Decimal)\n    assert isinstance(bids[0][1], Decimal)\n\n\ndef test_add_asks(fresh_cache):\n    \"\"\"Verify basic functionality for adding an ask to the cache\"\"\"\n    high_ask = [0.111, 489]\n    mid_ask = [0.018, 300]\n    low_ask = [0.001, 100]\n\n    for ask in [high_ask, low_ask, mid_ask]:\n        fresh_cache.add_ask(ask)\n\n    asks = fresh_cache.get_asks()\n\n    # Three asks should be in the cache\n    assert len(asks) == 3\n\n    # Lowest ask price should be first (ascending order)\n    assert asks == sorted(asks)\n\n    assert isinstance(asks[0][0], Decimal)\n    assert isinstance(asks[0][1], Decimal)\n"
  },
  {
    "path": "tests/test_futures.py",
    "content": "import requests_mock\nimport json\nfrom binance.client import Client\nimport re\n\nclient = Client(api_key=\"api_key\", api_secret=\"api_secret\", ping=False)\n\n\ndef test_futures_position_information():\n    with requests_mock.mock() as m:\n        url_matcher = re.compile(\n            r\"https:\\/\\/fapi.binance.com\\/fapi\\/v3\\/positionRisk\\?.+\"\n        )\n        response = [\n            {\n                \"symbol\": \"LTCUSDT\",\n                \"positionSide\": \"LONG\",\n                \"positionAmt\": \"0.700\",\n                \"entryPrice\": \"75.6\",\n                \"breakEvenPrice\": \"75.63024\",\n                \"markPrice\": \"73.18000000\",\n                \"unRealizedProfit\": \"-1.69400000\",\n                \"liquidationPrice\": \"0\",\n                \"isolatedMargin\": \"0\",\n                \"notional\": \"51.22600000\",\n                \"marginAsset\": \"USDT\",\n                \"isolatedWallet\": \"0\",\n                \"initialMargin\": \"10.24520000\",\n                \"maintMargin\": \"0.33296900\",\n                \"positionInitialMargin\": \"10.24520000\",\n                \"openOrderInitialMargin\": \"0\",\n                \"adl\": 0,\n                \"bidNotional\": \"0\",\n                \"askNotional\": \"0\",\n                \"updateTime\": 1729436057076,\n            }\n        ]\n        m.register_uri(\"GET\", url_matcher, json=json.dumps(response), status_code=200)\n        pos = client.futures_position_information(symbol=\"LTCUSDT\")\n        assert m.last_request.qs[\"symbol\"][0] == \"LTCUSDT\".lower()\n        assert m.last_request.path == \"/fapi/v3/positionrisk\"\n\n\ndef test_futures_position_information_version_override():\n    with requests_mock.mock() as m:\n        url_matcher = re.compile(\n            r\"https:\\/\\/fapi.binance.com\\/fapi\\/v2\\/positionRisk\\?.+\"\n        )\n        response = [\n            {\n                \"symbol\": \"LTCUSDT\",\n                \"positionSide\": \"LONG\",\n                \"positionAmt\": \"0.700\",\n                \"entryPrice\": \"75.6\",\n                \"breakEvenPrice\": \"75.63024\",\n                \"markPrice\": \"73.18000000\",\n                \"unRealizedProfit\": \"-1.69400000\",\n                \"liquidationPrice\": \"0\",\n                \"isolatedMargin\": \"0\",\n                \"notional\": \"51.22600000\",\n                \"marginAsset\": \"USDT\",\n                \"isolatedWallet\": \"0\",\n                \"initialMargin\": \"10.24520000\",\n                \"maintMargin\": \"0.33296900\",\n                \"positionInitialMargin\": \"10.24520000\",\n                \"openOrderInitialMargin\": \"0\",\n                \"adl\": 0,\n                \"bidNotional\": \"0\",\n                \"askNotional\": \"0\",\n                \"updateTime\": 1729436057076,\n            }\n        ]\n        m.register_uri(\"GET\", url_matcher, json=json.dumps(response), status_code=200)\n        pos = client.futures_position_information(symbol=\"LTCUSDT\", version=2)\n        assert m.last_request.qs[\"symbol\"][0] == \"LTCUSDT\".lower()\n        assert m.last_request.path == \"/fapi/v2/positionrisk\"\n\n\ndef test_futures_account_balance():\n    with requests_mock.mock() as m:\n        url_matcher = re.compile(r\"https:\\/\\/fapi.binance.com\\/fapi\\/v3\\/balance\\?.+\")\n        m.register_uri(\"GET\", url_matcher, json={}, status_code=200)\n        client.futures_account_balance()\n        assert m.last_request.path == \"/fapi/v3/balance\"\n\n\ndef test_futures_account_config():\n    with requests_mock.mock() as m:\n        url_matcher = re.compile(\n            r\"https:\\/\\/fapi.binance.com\\/fapi\\/v1\\/accountConfig\\?.+\"\n        )\n        m.register_uri(\"GET\", url_matcher, json={}, status_code=200)\n        client.futures_account_config()\n        assert m.last_request.path == \"/fapi/v1/accountconfig\"\n"
  },
  {
    "path": "tests/test_get_order_book.py",
    "content": "import pytest\nimport sys\nfrom binance.exceptions import BinanceAPIException\n\n\ndef assert_ob(order_book):\n    assert isinstance(order_book, dict)\n    assert \"lastUpdateId\" in order_book\n    assert \"bids\" in order_book\n    assert \"asks\" in order_book\n\n    assert isinstance(order_book[\"bids\"], list)\n    assert isinstance(order_book[\"asks\"], list)\n\n    if order_book[\"bids\"]:\n        bid = order_book[\"bids\"][0]\n        assert len(bid) == 2\n        assert all(isinstance(item, str) for item in bid[:2])\n\n    if order_book[\"asks\"]:\n        ask = order_book[\"asks\"][0]\n        assert len(ask) == 2\n        assert all(isinstance(item, str) for item in ask[:2])\n\n\ndef test_get_order_book(client):\n    try:\n        order_book = client.get_order_book(symbol=\"BTCUSDT\")\n        assert_ob(order_book)\n\n    except BinanceAPIException as e:\n        pytest.fail(f\"API request failed: {str(e)}\")\n\n\ndef test_futures_get_order_book(client):\n    try:\n        order_book = client.futures_order_book(symbol=\"BTCUSDT\")\n        assert_ob(order_book)\n\n    except BinanceAPIException as e:\n        pytest.fail(f\"API request failed: {str(e)}\")\n\n\ndef test_get_order_book_with_limit(client):\n    try:\n        order_book = client.get_order_book(symbol=\"BTCUSDT\", limit=5)\n\n        assert_ob(order_book)\n        assert len(order_book[\"bids\"]) <= 5\n        assert len(order_book[\"asks\"]) <= 5\n\n    except BinanceAPIException as e:\n        pytest.fail(f\"API request failed: {str(e)}\")\n\n\n@pytest.mark.asyncio(scope=\"function\")\nasync def test_get_order_book_async(clientAsync):\n    order_book = await clientAsync.get_order_book(symbol=\"BTCUSDT\")\n    assert_ob(order_book)\n\n\n@pytest.mark.asyncio(scope=\"function\")\nasync def test_futures_get_order_book_async(clientAsync):\n    try:\n        order_book = await clientAsync.futures_order_book(symbol=\"BTCUSDT\")\n        assert_ob(order_book)\n    except BinanceAPIException as e:\n        pytest.fail(f\"API request failed: {str(e)}\")\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\n@pytest.mark.asyncio()\nasync def test_ws_get_order_book(clientAsync):\n    order_book = await clientAsync.ws_get_order_book(symbol=\"BTCUSDT\")\n    assert_ob(order_book)\n"
  },
  {
    "path": "tests/test_headers.py",
    "content": "import requests_mock\nimport pytest\nfrom aioresponses import aioresponses\n\nfrom binance import Client, AsyncClient\n\nclient = Client(api_key=\"api_key\", api_secret=\"api_secret\", ping=False)\n\n\ndef test_get_headers():\n    with requests_mock.mock() as m:\n        m.get(\"https://api.binance.com/api/v3/account\", json={}, status_code=200)\n        client.get_account()\n        headers = m.last_request._request.headers\n        assert \"Content-Type\" in headers\n        assert headers[\"Content-Type\"] == \"application/json\"\n\n\ndef test_post_headers():\n    with requests_mock.mock() as m:\n        m.post(\"https://api.binance.com/api/v3/order\", json={}, status_code=200)\n        client.create_order(symbol=\"LTCUSDT\", side=\"BUY\", type=\"MARKET\", quantity=0.1)\n        headers = m.last_request._request.headers\n        assert \"Content-Type\" in headers\n        assert headers[\"Content-Type\"] == \"application/x-www-form-urlencoded\"\n\n\ndef test_post_headers_overriden():\n    with requests_mock.mock() as m:\n        m.post(\"https://api.binance.com/api/v3/order\", json={}, status_code=200)\n        client.create_order(\n            symbol=\"LTCUSDT\",\n            side=\"BUY\",\n            type=\"MARKET\",\n            quantity=0.1,\n            headers={\"Content-Type\": \"myvalue\"},\n        )\n        headers = m.last_request._request.headers\n        assert \"Content-Type\" in headers\n        assert headers[\"Content-Type\"] == \"myvalue\"\n\n\n@pytest.mark.asyncio()\nasync def test_post_headers_async():\n    clientAsync = AsyncClient(\n        api_key=\"api_key\", api_secret=\"api_secret\"\n    )  # reuse client later\n    with aioresponses() as m:\n\n        def handler(url, **kwargs):\n            headers = kwargs[\"headers\"]\n            assert \"Content-Type\" in headers\n            assert headers[\"Content-Type\"] == \"application/x-www-form-urlencoded\"\n\n        m.post(\n            \"https://api.binance.com/api/v3/order\",\n            payload={\"id\": 1},\n            status=200,\n            callback=handler,\n        )\n        await clientAsync.create_order(\n            symbol=\"LTCUSDT\", side=\"BUY\", type=\"MARKET\", quantity=0.1\n        )\n        await clientAsync.close_connection()\n\n\n@pytest.mark.asyncio()\nasync def test_post_headers_overriden_async():\n    clientAsync = AsyncClient(\n        api_key=\"api_key\", api_secret=\"api_secret\"\n    )  # reuse client later\n    with aioresponses() as m:\n\n        def handler(url, **kwargs):\n            headers = kwargs[\"headers\"]\n            assert \"Content-Type\" in headers\n            assert headers[\"Content-Type\"] == \"myvalue\"\n\n        m.post(\n            \"https://api.binance.com/api/v3/order\",\n            payload={\"id\": 1},\n            status=200,\n            callback=handler,\n        )\n        await clientAsync.create_order(\n            symbol=\"LTCUSDT\",\n            side=\"BUY\",\n            type=\"MARKET\",\n            quantity=0.1,\n            headers={\"Content-Type\": \"myvalue\"},\n        )\n        await clientAsync.close_connection()\n"
  },
  {
    "path": "tests/test_historical_klines.py",
    "content": "#!/usr/bin/env python\n# coding=utf-8\n\nfrom binance.client import Client\nimport pytest\nimport requests_mock\n\nclient = Client(\"api_key\", \"api_secret\", ping=False)\n\n\ndef test_exact_amount():\n    \"\"\"Test Exact amount returned\"\"\"\n\n    first_available_res = [\n        [\n            1500004800000,\n            \"0.00005000\",\n            \"0.00005300\",\n            \"0.00001000\",\n            \"0.00004790\",\n            \"663152.00000000\",\n            1500004859999,\n            \"30.55108144\",\n            43,\n            \"559224.00000000\",\n            \"25.65468144\",\n            \"83431971.04346950\",\n        ]\n    ]\n\n    first_res = []\n    row = [\n        1519892340000,\n        \"0.00099400\",\n        \"0.00099810\",\n        \"0.00099400\",\n        \"0.00099810\",\n        \"4806.04000000\",\n        1519892399999,\n        \"4.78553253\",\n        154,\n        \"1785.14000000\",\n        \"1.77837524\",\n        \"0\",\n    ]\n\n    for i in range(0, 500):\n        first_res.append(row)\n\n    second_res = []\n\n    with requests_mock.mock() as m:\n        m.get(\n            \"https://api.binance.com/api/v3/klines?interval=1m&limit=1&startTime=0&symbol=BNBBTC\",\n            json=first_available_res,\n        )\n        m.get(\n            \"https://api.binance.com/api/v3/klines?interval=1m&limit=1000&startTime=1519862400000&symbol=BNBBTC\",\n            json=first_res,\n        )\n        m.get(\n            \"https://api.binance.com/api/v3/klines?interval=1m&limit=1000&startTime=1519892400000&symbol=BNBBTC\",\n            json=second_res,\n        )\n        klines = client.get_historical_klines(\n            symbol=\"BNBBTC\",\n            interval=Client.KLINE_INTERVAL_1MINUTE,\n            start_str=\"1st March 2018\",\n        )\n        assert len(klines) == 500\n\n\ndef test_start_and_end_str():\n    \"\"\"Test start_str and end_str work correctly with string\"\"\"\n\n    first_available_res = [\n        [\n            1500004800000,\n            \"0.00005000\",\n            \"0.00005300\",\n            \"0.00001000\",\n            \"0.00004790\",\n            \"663152.00000000\",\n            1500004859999,\n            \"30.55108144\",\n            43,\n            \"559224.00000000\",\n            \"25.65468144\",\n            \"83431971.04346950\",\n        ]\n    ]\n    first_res = []\n    row = [\n        1519892340000,\n        \"0.00099400\",\n        \"0.00099810\",\n        \"0.00099400\",\n        \"0.00099810\",\n        \"4806.04000000\",\n        1519892399999,\n        \"4.78553253\",\n        154,\n        \"1785.14000000\",\n        \"1.77837524\",\n        \"0\",\n    ]\n\n    for i in range(0, 300):\n        first_res.append(row)\n\n    with requests_mock.mock() as m:\n        m.get(\n            \"https://api.binance.com/api/v3/klines?interval=1m&limit=1&startTime=0&symbol=BNBBTC\",\n            json=first_available_res,\n        )\n        m.get(\n            \"https://api.binance.com/api/v3/klines?interval=1m&limit=1000&startTime=1519862400000&endTime=1519880400000&symbol=BNBBTC\",\n            json=first_res,\n        )\n        klines = client.get_historical_klines(\n            symbol=\"BNBBTC\",\n            interval=Client.KLINE_INTERVAL_1MINUTE,\n            start_str=\"1st March 2018\",\n            end_str=\"1st March 2018 05:00:00\",\n        )\n        assert len(klines) == 300\n\n\ndef test_start_and_end_timestamp():\n    \"\"\"Test start_str and end_str work correctly with integer timestamp\"\"\"\n\n    first_available_res = [\n        [\n            1500004800000,\n            \"0.00005000\",\n            \"0.00005300\",\n            \"0.00001000\",\n            \"0.00004790\",\n            \"663152.00000000\",\n            1500004859999,\n            \"30.55108144\",\n            43,\n            \"559224.00000000\",\n            \"25.65468144\",\n            \"83431971.04346950\",\n        ]\n    ]\n    first_res = []\n    row = [\n        1519892340000,\n        \"0.00099400\",\n        \"0.00099810\",\n        \"0.00099400\",\n        \"0.00099810\",\n        \"4806.04000000\",\n        1519892399999,\n        \"4.78553253\",\n        154,\n        \"1785.14000000\",\n        \"1.77837524\",\n        \"0\",\n    ]\n\n    for i in range(0, 300):\n        first_res.append(row)\n\n    with requests_mock.mock() as m:\n        m.get(\n            \"https://api.binance.com/api/v3/klines?interval=1m&limit=1&startTime=0&symbol=BNBBTC\",\n            json=first_available_res,\n        )\n        m.get(\n            \"https://api.binance.com/api/v3/klines?interval=1m&limit=1000&startTime=1519862400000&endTime=1519880400000&symbol=BNBBTC\",\n            json=first_res,\n        )\n        klines = client.get_historical_klines(\n            symbol=\"BNBBTC\",\n            interval=Client.KLINE_INTERVAL_1MINUTE,\n            start_str=1519862400000,\n            end_str=1519880400000,\n        )\n        assert len(klines) == 300\n\n\ndef test_historical_kline_generator():\n    \"\"\"Test kline historical generator\"\"\"\n\n    first_available_res = [\n        [\n            1500004800000,\n            \"0.00005000\",\n            \"0.00005300\",\n            \"0.00001000\",\n            \"0.00004790\",\n            \"663152.00000000\",\n            1500004859999,\n            \"30.55108144\",\n            43,\n            \"559224.00000000\",\n            \"25.65468144\",\n            \"83431971.04346950\",\n        ]\n    ]\n    first_res = []\n    row = [\n        1519892340000,\n        \"0.00099400\",\n        \"0.00099810\",\n        \"0.00099400\",\n        \"0.00099810\",\n        \"4806.04000000\",\n        1519892399999,\n        \"4.78553253\",\n        154,\n        \"1785.14000000\",\n        \"1.77837524\",\n        \"0\",\n    ]\n\n    for i in range(0, 300):\n        first_res.append(row)\n\n    with requests_mock.mock() as m:\n        m.get(\n            \"https://api.binance.com/api/v3/klines?interval=1m&limit=1&startTime=0&symbol=BNBBTC\",\n            json=first_available_res,\n        )\n        m.get(\n            \"https://api.binance.com/api/v3/klines?interval=1m&limit=1000&startTime=1519862400000&endTime=1519880400000&symbol=BNBBTC\",\n            json=first_res,\n        )\n        klines = client.get_historical_klines_generator(\n            symbol=\"BNBBTC\",\n            interval=Client.KLINE_INTERVAL_1MINUTE,\n            start_str=1519862400000,\n            end_str=1519880400000,\n        )\n\n        for i in range(300):\n            assert len(next(klines)) > 0\n\n        with pytest.raises(StopIteration):\n            next(klines)\n\n\ndef test_historical_kline_generator_empty_response():\n    \"\"\"Test kline historical generator if an empty list is returned from API\"\"\"\n    first_available_res = [\n        [\n            1500004800000,\n            \"0.00005000\",\n            \"0.00005300\",\n            \"0.00001000\",\n            \"0.00004790\",\n            \"663152.00000000\",\n            1500004859999,\n            \"30.55108144\",\n            43,\n            \"559224.00000000\",\n            \"25.65468144\",\n            \"83431971.04346950\",\n        ]\n    ]\n    first_res = []\n\n    with requests_mock.mock() as m:\n        m.get(\n            \"https://api.binance.com/api/v3/klines?interval=1m&limit=1&startTime=0&symbol=BNBBTC\",\n            json=first_available_res,\n        )\n        m.get(\n            \"https://api.binance.com/api/v3/klines?interval=1m&limit=1000&startTime=1519862400000&endTime=1519880400000&symbol=BNBBTC\",\n            json=first_res,\n        )\n        klines = client.get_historical_klines_generator(\n            symbol=\"BNBBTC\",\n            interval=Client.KLINE_INTERVAL_1MINUTE,\n            start_str=1519862400000,\n            end_str=1519880400000,\n        )\n\n        with pytest.raises(StopIteration):\n            next(klines)\n\n\ndef test_start_and_limit():\n    \"\"\"Test start_str and limit work correctly with integer timestamp\"\"\"\n\n    first_available_res = [\n        [\n            1500004800000,\n            \"0.00005000\",\n            \"0.00005300\",\n            \"0.00001000\",\n            \"0.00004790\",\n            \"663152.00000000\",\n            1500004859999,\n            \"30.55108144\",\n            43,\n            \"559224.00000000\",\n            \"25.65468144\",\n            \"83431971.04346950\",\n        ]\n    ]\n    first_res = []\n    row = [\n        1519892340000,\n        \"0.00099400\",\n        \"0.00099810\",\n        \"0.00099400\",\n        \"0.00099810\",\n        \"4806.04000000\",\n        1519892399999,\n        \"4.78553253\",\n        154,\n        \"1785.14000000\",\n        \"1.77837524\",\n        \"0\",\n    ]\n\n    for i in range(0, 5):\n        first_res.append(row)\n\n    with requests_mock.mock() as m:\n        m.get(\n            \"https://api.binance.com/api/v3/klines?interval=1m&limit=1&startTime=0&symbol=BNBBTC\",\n            json=first_available_res,\n        )\n        m.get(\n            \"https://api.binance.com/api/v3/klines?interval=1m&limit=5&startTime=1519892400000&symbol=BNBBTC\",\n            json=first_res,\n        )\n        m.get(\n            \"https://api.binance.com/api/v3/klines?interval=1m&limit=5&startTime=1519862400000&symbol=BNBBTC\",\n            json=first_res,\n        )\n        klines = client.get_historical_klines(\n            symbol=\"BNBBTC\",\n            interval=Client.KLINE_INTERVAL_1MINUTE,\n            start_str=1519862400000,\n            limit=5,\n        )\n        assert len(klines) == 5\n"
  },
  {
    "path": "tests/test_ids.py",
    "content": "import re\nimport requests_mock\nimport pytest\nfrom aioresponses import aioresponses\n\nfrom binance import Client, AsyncClient\n\nclient = Client(api_key=\"api_key\", api_secret=\"api_secret\", ping=False)\n\n\ndef test_spot_id():\n    with requests_mock.mock() as m:\n        m.post(\"https://api.binance.com/api/v3/order\", json={}, status_code=200)\n        client.create_order(symbol=\"LTCUSDT\", side=\"BUY\", type=\"MARKET\", quantity=0.1)\n        url_dict = dict(pair.split(\"=\") for pair in m.last_request.text.split(\"&\"))\n        assert url_dict[\"symbol\"] == \"LTCUSDT\"\n        assert url_dict[\"side\"] == \"BUY\"\n        assert url_dict[\"type\"] == \"MARKET\"\n        assert url_dict[\"quantity\"] == \"0.1\"\n        assert url_dict[\"newClientOrderId\"].startswith(\"x-HNA2TXFJ\")\n\n\ndef test_spot_limit_id():\n    with requests_mock.mock() as m:\n        m.post(\"https://api.binance.com/api/v3/order\", json={}, status_code=200)\n        client.order_limit_buy(\n            symbol=\"LTCUSDT\", side=\"BUY\", type=\"MARKET\", quantity=0.1\n        )\n        url_dict = dict(pair.split(\"=\") for pair in m.last_request.text.split(\"&\"))\n        assert url_dict[\"newClientOrderId\"].startswith(\"x-HNA2TXFJ\")\n\n\ndef test_spot_market_id():\n    with requests_mock.mock() as m:\n        m.post(\"https://api.binance.com/api/v3/order\", json={}, status_code=200)\n        client.order_market_buy(\n            symbol=\"LTCUSDT\", side=\"BUY\", type=\"MARKET\", quantity=0.1\n        )\n        url_dict = dict(pair.split(\"=\") for pair in m.last_request.text.split(\"&\"))\n        assert url_dict[\"newClientOrderId\"].startswith(\"x-HNA2TXFJ\")\n\n\ndef test_spot_cancel_replace_id():\n    with requests_mock.mock() as m:\n        m.post(\n            \"https://api.binance.com/api/v3/order/cancelReplace\",\n            json={},\n            status_code=200,\n        )\n        client.cancel_replace_order(\n            cancelOrderId=\"orderId\",\n            symbol=\"LTCUSDT\",\n            side=\"BUY\",\n            type=\"MARKET\",\n            quantity=0.1,\n        )\n        url_dict = dict(pair.split(\"=\") for pair in m.last_request.text.split(\"&\"))\n        assert url_dict[\"newClientOrderId\"].startswith(\"x-HNA2TXFJ\")\n\n\ndef test_spot_oco_order_id():\n    with requests_mock.mock() as m:\n        m.post(\"https://api.binance.com/api/v3/orderList/oco\", json={}, status_code=200)\n        client.create_oco_order(\n            symbol=\"LTCUSDT\", side=\"BUY\", aboveType=\"MARKET\", quantity=0.1\n        )\n        url_dict = dict(pair.split(\"=\") for pair in m.last_request.text.split(\"&\"))\n        assert url_dict[\"listClientOrderId\"].startswith(\"x-HNA2TXFJ\")\n\n\ndef test_swap_id():\n    with requests_mock.mock() as m:\n        m.post(\"https://fapi.binance.com/fapi/v1/order\", json={}, status_code=200)\n        client.futures_create_order(\n            symbol=\"LTCUSDT\", side=\"BUY\", type=\"MARKET\", quantity=0.1\n        )\n        url_dict = dict(pair.split(\"=\") for pair in m.last_request.text.split(\"&\"))\n        # why lowercase? check this later\n        assert url_dict[\"symbol\"] == \"LTCUSDT\"\n        assert url_dict[\"side\"] == \"BUY\"\n        assert url_dict[\"type\"] == \"MARKET\"\n        assert url_dict[\"quantity\"] == \"0.1\"\n        assert url_dict[\"newClientOrderId\"].startswith(\"x-Cb7ytekJ\")\n\n\ndef test_swap_batch_id():\n    with requests_mock.mock() as m:\n        m.post(\"https://fapi.binance.com/fapi/v1/batchOrders\", json={}, status_code=200)\n        order = {\"symbol\": \"LTCUSDT\", \"side\": \"BUY\", \"type\": \"MARKET\", \"quantity\": 0.1}\n        orders = [order, order]\n        client.futures_place_batch_order(batchOrders=orders)\n        text = m.last_request.text\n        assert \"x-Cb7ytekJ\" in text\n\n\ndef test_coin_id():\n    with requests_mock.mock() as m:\n        m.post(\"https://dapi.binance.com/dapi/v1/order\", json={}, status_code=200)\n        client.futures_coin_create_order(\n            symbol=\"LTCUSD_PERP\", side=\"BUY\", type=\"MARKET\", quantity=0.1\n        )\n        url_dict = dict(pair.split(\"=\") for pair in m.last_request.text.split(\"&\"))\n        # why lowercase? check this later\n        assert url_dict[\"symbol\"] == \"LTCUSD_PERP\"\n        assert url_dict[\"side\"] == \"BUY\"\n        assert url_dict[\"type\"] == \"MARKET\"\n        assert url_dict[\"quantity\"] == \"0.1\"\n        assert url_dict[\"newClientOrderId\"].startswith(\"x-Cb7ytekJ\")\n\n\ndef test_coin_batch_id():\n    with requests_mock.mock() as m:\n        m.post(\"https://dapi.binance.com/dapi/v1/batchOrders\", json={}, status_code=200)\n        order = {\n            \"symbol\": \"BTCUSD_PERP\",\n            \"side\": \"BUY\",\n            \"type\": \"MARKET\",\n            \"quantity\": 0.1,\n        }\n        orders = [order, order]\n        client.futures_coin_place_batch_order(batchOrders=orders)\n        text = m.last_request.text\n        assert \"x-Cb7ytekJ\" in text\n\n\ndef test_papi_um_id():\n    with requests_mock.mock() as m:\n        m.post(\"https://papi.binance.com/papi/v1/um/order\", json={}, status_code=200)\n        client.papi_create_um_order(\n            symbol=\"LTCUSDT\", side=\"BUY\", type=\"MARKET\", quantity=0.1\n        )\n        url_dict = dict(pair.split(\"=\") for pair in m.last_request.text.split(\"&\"))\n        # why lowercase? check this later\n        assert url_dict[\"symbol\"] == \"LTCUSDT\"\n        assert url_dict[\"side\"] == \"BUY\"\n        assert url_dict[\"type\"] == \"MARKET\"\n        assert url_dict[\"quantity\"] == \"0.1\"\n        assert url_dict[\"newClientOrderId\"].startswith(\"x-Cb7ytekJ\")\n\n\ndef test_papi_cm_id():\n    with requests_mock.mock() as m:\n        m.post(\"https://papi.binance.com/papi/v1/cm/order\", json={}, status_code=200)\n        client.papi_create_cm_order(\n            symbol=\"LTCUSDT\", side=\"BUY\", type=\"MARKET\", quantity=0.1\n        )\n        url_dict = dict(pair.split(\"=\") for pair in m.last_request.text.split(\"&\"))\n        # why lowercase? check this later\n        assert url_dict[\"symbol\"] == \"LTCUSDT\"\n        assert url_dict[\"side\"] == \"BUY\"\n        assert url_dict[\"type\"] == \"MARKET\"\n        assert url_dict[\"quantity\"] == \"0.1\"\n        assert url_dict[\"newClientOrderId\"].startswith(\"x-Cb7ytekJ\")\n\n\n@pytest.mark.asyncio()\nasync def test_spot_id_async():\n    clientAsync = AsyncClient(\n        api_key=\"api_key\", api_secret=\"api_secret\"\n    )  # reuse client later\n    with aioresponses() as m:\n\n        def handler(url, **kwargs):\n            client_order_id = kwargs[\"data\"][0][1]\n            assert client_order_id.startswith(\"x-HNA2TXFJ\")\n\n        m.post(\n            \"https://api.binance.com/api/v3/order\",\n            payload={\"id\": 1},\n            status=200,\n            callback=handler,\n        )\n        await clientAsync.create_order(\n            symbol=\"LTCUSDT\", side=\"BUY\", type=\"MARKET\", quantity=0.1\n        )\n        await clientAsync.close_connection()\n\n\n@pytest.mark.asyncio()\nasync def test_spot_cancel_replace_id_async():\n    clientAsync = AsyncClient(\n        api_key=\"api_key\", api_secret=\"api_secret\"\n    )  # reuse client later\n    with aioresponses() as m:\n\n        def handler(url, **kwargs):\n            client_order_id = kwargs[\"data\"][0][1]\n            assert client_order_id.startswith(\"x-HNA2TXFJ\")\n\n        m.post(\n            \"https://api.binance.com/api/v3/order/cancelReplace\",\n            payload={\"id\": 1},\n            status=200,\n            callback=handler,\n        )\n        await clientAsync.cancel_replace_order(\n            orderId=\"id\", symbol=\"LTCUSDT\", side=\"BUY\", type=\"MARKET\", quantity=0.1\n        )\n        await clientAsync.close_connection()\n\n\n@pytest.mark.asyncio()\nasync def test_swap_id_async():\n    clientAsync = AsyncClient(api_key=\"api_key\", api_secret=\"api_secret\")\n    with aioresponses() as m:\n\n        def handler(url, **kwargs):\n            assert \"x-Cb7ytekJ\" in kwargs[\"data\"][0][1]\n\n        url_pattern = re.compile(r\"https://fapi\\.binance\\.com/fapi/v1/order\")\n        m.post(\n            url_pattern,\n            payload={\"id\": 1},\n            status=200,\n            callback=handler,\n        )\n        await clientAsync.futures_create_order(\n            symbol=\"LTCUSDT\", side=\"BUY\", type=\"MARKET\", quantity=0.1\n        )\n        await clientAsync.close_connection()\n\n@pytest.mark.asyncio()\nasync def test_swap_trigger_id_async():\n    clientAsync = AsyncClient(api_key=\"api_key\", api_secret=\"api_secret\")\n    with aioresponses() as m:\n\n        def handler(url, **kwargs):\n            assert \"x-Cb7ytekJ\" in kwargs[\"data\"][1][1]\n\n        url_pattern = re.compile(r\"https://fapi\\.binance\\.com/fapi/v1/algoOrder\")\n        m.post(\n            url_pattern,\n            payload={\"id\": 1},\n            status=200,\n            callback=handler,\n        )\n        await clientAsync.futures_create_order(\n            symbol=\"LTCUSDT\", side=\"BUY\", type=\"STOP_MARKET\", quantity=0.1\n        )\n        await clientAsync.close_connection()\n\n@pytest.mark.asyncio()\nasync def test_swap_trigger_endpoint_id_async():\n    clientAsync = AsyncClient(api_key=\"api_key\", api_secret=\"api_secret\")\n    with aioresponses() as m:\n\n        def handler(url, **kwargs):\n            # print(kwargs[\"data\"])\n            assert \"x-Cb7ytekJ\" in kwargs[\"data\"][1][1]\n\n        url_pattern = re.compile(r\"https://fapi\\.binance\\.com/fapi/v1/algoOrder\")\n        m.post(\n            url_pattern,\n            payload={\"id\": 1},\n            status=200,\n            callback=handler,\n        )\n        await clientAsync.futures_create_algo_order(\n            symbol=\"LTCUSDT\", side=\"BUY\", type=\"STOP_MARKET\", quantity=0.1\n        )\n        await clientAsync.close_connection()\n\n@pytest.mark.asyncio()\nasync def test_papi_um_id_async():\n    clientAsync = AsyncClient(api_key=\"api_key\", api_secret=\"api_secret\")\n    with aioresponses() as m:\n\n        def handler(url, **kwargs):\n            client_order_id = kwargs[\"data\"][0][1]\n            assert client_order_id.startswith(\"x-Cb7ytekJ\")\n\n        m.post(\n            \"https://papi.binance.com/papi/v1/um/order\",\n            payload={\"id\": 1},\n            status=200,\n            callback=handler,\n        )\n        await clientAsync.papi_create_um_order(\n            symbol=\"LTCUSDT\", side=\"BUY\", type=\"MARKET\", quantity=0.1\n        )\n        await clientAsync.close_connection()\n\n\n@pytest.mark.asyncio()\nasync def test_papi_cm_id_async():\n    clientAsync = AsyncClient(api_key=\"api_key\", api_secret=\"api_secret\")\n    with aioresponses() as m:\n\n        def handler(url, **kwargs):\n            client_order_id = kwargs[\"data\"][0][1]\n            assert client_order_id.startswith(\"x-Cb7ytekJ\")\n\n        m.post(\n            \"https://papi.binance.com/papi/v1/cm/order\",\n            payload={\"id\": 1},\n            status=200,\n            callback=handler,\n        )\n        await clientAsync.papi_create_cm_order(\n            symbol=\"LTCUSDT\", side=\"BUY\", type=\"MARKET\", quantity=0.1\n        )\n        await clientAsync.close_connection()\n\n\n@pytest.mark.asyncio()\nasync def test_coin_id_async():\n    clientAsync = AsyncClient(api_key=\"api_key\", api_secret=\"api_secret\")\n    with aioresponses() as m:\n\n        def handler(url, **kwargs):\n            client_order_id = kwargs[\"data\"][0][1]\n            assert client_order_id.startswith(\"x-Cb7ytekJ\")\n\n        m.post(\n            \"https://dapi.binance.com/dapi/v1/order\",\n            payload={\"id\": 1},\n            status=200,\n            callback=handler,\n        )\n        await clientAsync.futures_coin_create_order(\n            symbol=\"LTCUSD_PERP\", side=\"BUY\", type=\"MARKET\", quantity=0.1\n        )\n        await clientAsync.close_connection()\n\n\n@pytest.mark.asyncio()\nasync def test_spot_oco_id():\n    clientAsync = AsyncClient(api_key=\"api_key\", api_secret=\"api_secret\")\n    with aioresponses() as m:\n\n        def handler(url, **kwargs):\n            client_order_id = kwargs[\"data\"][0][1]\n            assert client_order_id.startswith(\"x-HNA2TXFJ\")\n\n        m.post(\n            \"https://api.binance.com/api/v3/orderList/oco\",\n            payload={\"id\": 1},\n            status=200,\n            callback=handler,\n        )\n        await clientAsync.create_oco_order(\n            symbol=\"BTCUSDT\", side=\"BUY\", type=\"MARKET\", quantity=0.1\n        )\n        await clientAsync.close_connection()\n\n\n@pytest.mark.asyncio()\nasync def test_swap_batch_id_async():\n    with aioresponses() as m:\n        clientAsync = AsyncClient(api_key=\"api_key\", api_secret=\"api_secret\")\n\n        def handler(url, **kwargs):\n            assert \"x-Cb7ytekJ\" in kwargs[\"data\"]\n\n        m.post(\n            \"https://fapi.binance.com/fapi/v1/batchOrders\",\n            payload={\"id\": 1},\n            status=200,\n            callback=handler,\n        )\n        order = {\"symbol\": \"LTCUSDT\", \"side\": \"BUY\", \"type\": \"MARKET\", \"quantity\": 0.1}\n        orders = [order, order]\n        await clientAsync.futures_place_batch_order(batchOrders=orders)\n        await clientAsync.close_connection()\n\n\n@pytest.mark.asyncio()\nasync def test_coin_batch_id_async():\n    with aioresponses() as m:\n        clientAsync = AsyncClient(api_key=\"api_key\", api_secret=\"api_secret\")\n\n        def handler(url, **kwargs):\n            assert \"x-Cb7ytekJ\" in kwargs[\"data\"][0][1]\n\n        m.post(\n            \"https://dapi.binance.com/dapi/v1/batchOrders\",\n            payload={\"id\": 1},\n            status=200,\n            callback=handler,\n        )\n        order = {\n            \"symbol\": \"LTCUSD_PERP\",\n            \"side\": \"BUY\",\n            \"type\": \"MARKET\",\n            \"quantity\": 0.1,\n        }\n        orders = [order, order]\n        await clientAsync.futures_coin_place_batch_order(batchOrders=orders)\n        await clientAsync.close_connection()\n"
  },
  {
    "path": "tests/test_init.py",
    "content": "from binance import (\n    AsyncClient,\n    Client,\n    DepthCacheManager,\n    OptionsDepthCacheManager,\n    ThreadedDepthCacheManager,\n    FuturesDepthCacheManager,\n    BinanceSocketManager,\n    ThreadedWebsocketManager,\n    BinanceSocketType,\n    KeepAliveWebsocket,\n    ReconnectingWebsocket\n)\n\ndef test_version():\n    \"\"\"Test that __version__ is defined\"\"\"\n    from binance import __version__\n    assert isinstance(__version__, str)\n    assert __version__ is not None\n\ndef test_client_import():\n    \"\"\"Test Client class import\"\"\"\n    assert Client is not None\n    assert isinstance(Client, type)\n\ndef test_async_client_import():\n    \"\"\"Test AsyncClient class import\"\"\"\n    assert AsyncClient is not None\n    assert isinstance(AsyncClient, type)\n\ndef test_depth_cache_imports():\n    \"\"\"Test depth cache related imports\"\"\"\n    assert DepthCacheManager is not None\n    assert OptionsDepthCacheManager is not None\n    assert ThreadedDepthCacheManager is not None\n    assert FuturesDepthCacheManager is not None\n    assert isinstance(DepthCacheManager, type)\n    assert isinstance(OptionsDepthCacheManager, type)\n    assert isinstance(ThreadedDepthCacheManager, type)\n    assert isinstance(FuturesDepthCacheManager, type)\n\ndef test_websocket_imports():\n    \"\"\"Test websocket related imports\"\"\"\n    assert BinanceSocketManager is not None\n    assert ThreadedWebsocketManager is not None\n    assert BinanceSocketType is not None\n    assert isinstance(BinanceSocketManager, type)\n    assert isinstance(ThreadedWebsocketManager, type)\n\ndef test_websocket_utility_imports():\n    \"\"\"Test websocket utility imports\"\"\"\n    assert KeepAliveWebsocket is not None\n    assert ReconnectingWebsocket is not None\n    assert isinstance(KeepAliveWebsocket, type)\n    assert isinstance(ReconnectingWebsocket, type)\n"
  },
  {
    "path": "tests/test_keepalive_reconnect.py",
    "content": "\"\"\"\nTest to verify that KeepAliveWebsocket doesn't create duplicate keepalive loops on reconnection.\n\nThis test reproduces the issue where reconnection events create duplicate keepalive loops\nthat continue running indefinitely, leading to resource exhaustion and redundant API calls.\n\"\"\"\n\nimport sys\nimport asyncio\nimport pytest\nfrom unittest.mock import AsyncMock, MagicMock\nfrom binance.async_client import AsyncClient\nfrom binance.ws.keepalive_websocket import KeepAliveWebsocket\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\n@pytest.mark.asyncio\nasync def test_no_duplicate_keepalive_loops_on_reconnect():\n    \"\"\"\n    Test that reconnection doesn't create duplicate keepalive loops.\n\n    The bug occurs when:\n    1. A keepalive loop is running (timer -> keepalive_socket -> timer -> ...)\n    2. Reconnection happens via _after_connect()\n    3. A new keepalive loop is started unconditionally\n    4. The old loop continues running in the background\n    5. Each reconnection adds another orphaned loop\n    \"\"\"\n    # Create a mock client\n    mock_client = MagicMock(spec=AsyncClient)\n    mock_client.futures_stream_get_listen_key = AsyncMock(\n        return_value=\"test_listen_key\"\n    )\n    mock_client.futures_stream_keepalive = AsyncMock()\n\n    # Create the websocket instance\n    ws = KeepAliveWebsocket(\n        client=mock_client,\n        url=\"wss://fstream.binance.com/\",\n        keepalive_type=\"futures\",\n        prefix=\"ws/\",\n        user_timeout=0.1,  # Short timeout for faster test\n    )\n\n    # Track how many times _keepalive_socket is called\n    keepalive_call_count = 0\n    original_keepalive = ws._keepalive_socket\n\n    async def tracked_keepalive():\n        nonlocal keepalive_call_count\n        keepalive_call_count += 1\n        # Call the original method but skip the actual API call\n        # Just track that it was called\n        return\n\n    ws._keepalive_socket = tracked_keepalive\n\n    # Simulate the first connection\n    await ws._before_connect()\n    await ws._after_connect()\n\n    # Wait for the first timer to trigger\n    await asyncio.sleep(0.15)\n    first_call_count = keepalive_call_count\n\n    assert first_call_count >= 1, \"Keepalive should have been called at least once\"\n\n    # Simulate a reconnection (this is where the bug occurs)\n    # In a real scenario, _after_connect() is called again by the reconnection logic\n    await ws._after_connect()\n\n    # Wait for more timer triggers\n    await asyncio.sleep(0.15)\n    second_call_count = keepalive_call_count\n\n    # Calculate how many calls happened after reconnection\n    calls_after_reconnect = second_call_count - first_call_count\n\n    # With the bug: multiple loops are running, so we'd see 2+ calls per timer period\n    # Without the bug: only one loop is running, so we'd see ~1 call per timer period\n    # Allow some margin (up to 2 calls) due to timing\n    assert calls_after_reconnect <= 2, (\n        f\"Too many keepalive calls after reconnection: {calls_after_reconnect}. \"\n        f\"This indicates duplicate keepalive loops are running. \"\n        f\"Total calls: {second_call_count}, calls before reconnect: {first_call_count}\"\n    )\n\n    # Clean up\n    if ws._timer:\n        ws._timer.cancel()\n        ws._timer = None\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\n@pytest.mark.asyncio\nasync def test_keepalive_stops_after_exit():\n    \"\"\"\n    Test that keepalive loop stops properly when the websocket exits.\n\n    The fix should ensure that when __aexit__ sets _timer to None,\n    the finally block in _keepalive_socket doesn't restart the timer.\n    \"\"\"\n    # Create a mock client\n    mock_client = MagicMock(spec=AsyncClient)\n    mock_client.futures_stream_get_listen_key = AsyncMock(\n        return_value=\"test_listen_key\"\n    )\n    mock_client.futures_stream_keepalive = AsyncMock()\n\n    # Create the websocket instance\n    ws = KeepAliveWebsocket(\n        client=mock_client,\n        url=\"wss://fstream.binance.com/\",\n        keepalive_type=\"futures\",\n        prefix=\"ws/\",\n        user_timeout=0.1,  # Short timeout for faster test\n    )\n\n    # Track keepalive calls\n    keepalive_call_count = 0\n\n    async def tracked_keepalive():\n        nonlocal keepalive_call_count\n        keepalive_call_count += 1\n        return\n\n    ws._keepalive_socket = tracked_keepalive\n\n    # Start the keepalive\n    await ws._before_connect()\n    await ws._after_connect()\n\n    # Wait for at least one keepalive call\n    await asyncio.sleep(0.15)\n    calls_before_exit = keepalive_call_count\n    assert calls_before_exit >= 1, \"Keepalive should have been called before exit\"\n\n    # Simulate exit by setting timer to None (this is what __aexit__ does)\n    if ws._timer:\n        ws._timer.cancel()\n        ws._timer = None\n\n    # Wait to see if more keepalive calls happen (they shouldn't)\n    await asyncio.sleep(0.15)\n    calls_after_exit = keepalive_call_count\n\n    # After setting _timer to None, no more calls should happen\n    assert calls_after_exit == calls_before_exit, (\n        f\"Keepalive should not continue after exit. \"\n        f\"Calls before exit: {calls_before_exit}, calls after exit: {calls_after_exit}\"\n    )\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\n@pytest.mark.asyncio\nasync def test_multiple_reconnects_no_loop_accumulation():\n    \"\"\"\n    Test that multiple reconnections don't accumulate keepalive loops.\n\n    This is a stress test to ensure the fix works even with many reconnections.\n    \"\"\"\n    # Create a mock client\n    mock_client = MagicMock(spec=AsyncClient)\n    mock_client.futures_stream_get_listen_key = AsyncMock(\n        return_value=\"test_listen_key\"\n    )\n    mock_client.futures_stream_keepalive = AsyncMock()\n\n    # Create the websocket instance\n    ws = KeepAliveWebsocket(\n        client=mock_client,\n        url=\"wss://fstream.binance.com/\",\n        keepalive_type=\"futures\",\n        prefix=\"ws/\",\n        user_timeout=0.1,  # Short timeout for faster test\n    )\n\n    # Track keepalive calls\n    keepalive_call_count = 0\n\n    async def tracked_keepalive():\n        nonlocal keepalive_call_count\n        keepalive_call_count += 1\n        return\n\n    ws._keepalive_socket = tracked_keepalive\n\n    # Initial connection\n    await ws._before_connect()\n    await ws._after_connect()\n\n    # Wait for initial calls\n    await asyncio.sleep(0.15)\n\n    # Simulate 5 reconnections\n    for i in range(5):\n        await ws._after_connect()\n\n    # Reset counter\n    keepalive_call_count = 0\n\n    # Wait for a timer period\n    await asyncio.sleep(0.15)\n\n    # Should only have ~1 call per timer period, not 6 (one per each connection + reconnections)\n    # Allow margin of 2 due to timing\n    assert keepalive_call_count <= 2, (\n        f\"Too many keepalive calls after 5 reconnections: {keepalive_call_count}. \"\n        f\"This indicates keepalive loops are accumulating.\"\n    )\n\n    # Clean up\n    if ws._timer:\n        ws._timer.cancel()\n        ws._timer = None\n"
  },
  {
    "path": "tests/test_order.py",
    "content": "def assert_contract_order(client, order):\n    assert isinstance(order, dict)\n\n    assert order[\"clientOrderId\"].startswith(client.CONTRACT_ORDER_PREFIX)\n    assert order[\"symbol\"]\n"
  },
  {
    "path": "tests/test_ping.py",
    "content": "import os\nimport pytest\n\n\nproxies = {}\nproxy = os.getenv(\"PROXY\")\n\n\ndef test_papi_ping_sync(client):\n    ping_response = client.papi_ping()\n    assert ping_response is not None\n\n\ndef test_ping_sync(client):\n    ping_response = client.ping()\n    assert ping_response is not None\n\n\ndef test_futures_ping(client):\n    ping_response = client.futures_ping()\n    assert ping_response is not None\n\n\ndef test_coin_ping(client):\n    ping_response = client.futures_coin_ping()\n    assert ping_response is not None\n\n\n@pytest.mark.asyncio()\nasync def test_papi_ping_async(clientAsync):\n    ping_response = await clientAsync.papi_ping()\n    assert ping_response is not None\n\n\n@pytest.mark.asyncio()\nasync def test_ping_async(clientAsync):\n    ping_response = await clientAsync.ping()\n    assert ping_response is not None\n\n\n@pytest.mark.asyncio()\nasync def test_futures_ping_async(clientAsync):\n    ping_response = await clientAsync.futures_ping()\n    assert ping_response is not None\n\n\n@pytest.mark.asyncio()\nasync def test_coin_ping_async(clientAsync):\n    ping_response = await clientAsync.futures_coin_ping()\n    assert ping_response is not None\n"
  },
  {
    "path": "tests/test_reconnecting_websocket.py",
    "content": "import sys\nimport pytest\nimport gzip\nimport json\nfrom unittest.mock import patch, create_autospec, Mock\nfrom binance.ws.reconnecting_websocket import ReconnectingWebsocket\nfrom binance.ws.constants import WSListenerState\nfrom binance.exceptions import BinanceWebsocketUnableToConnect, ReadLoopClosed\nfrom websockets import WebSocketClientProtocol  # type: ignore\nfrom websockets.protocol import State\nimport asyncio\n\ntry:\n    from unittest.mock import AsyncMock  # Python 3.8+\nexcept ImportError:\n    from asynctest import CoroutineMock as AsyncMock  # Python 3.7\n\n\n@pytest.mark.asyncio\nasync def test_init():\n    ws = ReconnectingWebsocket(url=\"wss://test.url\", path=\"/test\")\n    assert ws._url == \"wss://test.url\"\n    assert ws._path == \"/test\"\n    assert ws.ws_state == WSListenerState.INITIALISING\n\n\n@pytest.mark.asyncio\nasync def test_json_dumps():\n    ws = ReconnectingWebsocket(url=\"wss://test.url\")\n    data = {\"key\": \"value\"}\n    dumped = ws.json_dumps(data)\n    assert isinstance(dumped, (str, bytes))\n\n\n@pytest.mark.asyncio\nasync def test_json_loads():\n    ws = ReconnectingWebsocket(url=\"wss://test.url\")\n    data_str = '{\"key\": \"value\"}'\n    loaded = ws.json_loads(data_str)\n    assert loaded == {\"key\": \"value\"}\n\n\n@pytest.mark.asyncio\nasync def test_json_loads_invalid():\n    ws = ReconnectingWebsocket(url=\"wss://test.url\")\n    data_str = \"invalid json\"\n    with pytest.raises(json.JSONDecodeError):\n        ws.json_loads(data_str)\n\n\n@pytest.mark.asyncio\nasync def test_handle_message():\n    ws = ReconnectingWebsocket(url=\"wss://test.url\")\n    message = '{\"key\": \"value\"}'\n    result = ws._handle_message(message)\n    assert result == {\"key\": \"value\"}\n\n\n@pytest.mark.asyncio\nasync def test_handle_message_binary():\n    ws = ReconnectingWebsocket(url=\"wss://test.url\", is_binary=True)\n    data = b'{\"key\": \"value\"}'\n    compressed = gzip.compress(data)\n    result = ws._handle_message(compressed)\n    assert result == {\"key\": \"value\"}\n\n\n@pytest.mark.asyncio\nasync def test_handle_message_invalid_json():\n    ws = ReconnectingWebsocket(url=\"wss://test.url\")\n    message = \"invalid json\"\n    with pytest.raises(Exception):\n        ws._handle_message(message)\n\n\n@pytest.mark.asyncio\nasync def test_recv_message():\n    ws = ReconnectingWebsocket(url=\"wss://test.url\")\n    await ws._queue.put({\"test\": \"data\"})\n    # Simulate the read loop being active\n    ws._handle_read_loop = Mock()\n    result = await ws.recv()\n    assert result == {\"test\": \"data\"}\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"Requires Python 3.8+\")\n@pytest.mark.asyncio\nasync def test_before_reconnect():\n    ws = ReconnectingWebsocket(url=\"wss://test.url\")\n    ws.ws = AsyncMock()\n    ws._conn = AsyncMock()\n    ws._reconnects = 0\n    await ws.before_reconnect()\n    assert ws.ws is None\n    ws._conn.__aexit__.assert_awaited()\n    assert ws._reconnects == 1\n\n\ndef test_get_reconnect_wait():\n    ws = ReconnectingWebsocket(url=\"wss://test.url\")\n    wait_time = ws._get_reconnect_wait(2)\n    assert 1 <= wait_time <= ws.MAX_RECONNECT_SECONDS\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"Requires Python 3.8+\")\n@pytest.mark.asyncio\nasync def test_connect_max_reconnects_exceeded():\n    \"\"\"Test ws.connect exceeds maximum reconnect attempts.\"\"\"\n    ws = ReconnectingWebsocket(url=\"wss://test.url\")\n    ws.MAX_RECONNECTS = 2  # type: ignore # Set max reconnects to a low number for testing\n    ws._before_connect = AsyncMock()\n    ws._after_connect = AsyncMock()\n    ws._conn = AsyncMock()\n    exception = Exception(\"Connection failed\")\n    ws._conn.__aenter__.side_effect = exception\n\n    with patch.object(ws._log, \"error\") as mock_log:\n        with pytest.raises(BinanceWebsocketUnableToConnect):\n            for _ in range(3):  # Exceed MAX_RECONNECTS\n                await ws._run_reconnect()\n        mock_log.assert_called_with(f\"Max reconnections {ws.MAX_RECONNECTS} reached:\")\n\n    assert ws._reconnects == ws.MAX_RECONNECTS\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"Requires Python 3.8+\")\n@pytest.mark.asyncio\nasync def test_recieve_invalid_json():\n    # Create mock WebSocket client\n    mock_socket = create_autospec(WebSocketClientProtocol)\n    mock_socket.recv = AsyncMock(return_value=\"invalid json{\")\n    mock_socket.state = AsyncMock()\n\n    # Mock websockets.connect to return our mock socket\n    with patch(\"websockets.connect\") as mock_connect:\n        mock_connect.return_value.__aenter__.return_value = mock_socket\n\n        ws = ReconnectingWebsocket(url=\"wss://test.url\")\n        async with ws:\n            msg = await ws.recv()\n            assert msg[\"e\"] == \"error\"\n            assert msg[\"type\"] == \"JSONDecodeError\"  # JSON parsing error\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"Requires Python 3.8+\")\n@pytest.mark.asyncio\nasync def test_receive_valid_json():\n    # Create mock WebSocket client\n    msgRecv = '{\"e\": \"value\"}'\n    mock_socket = create_autospec(WebSocketClientProtocol)\n    mock_socket.recv = AsyncMock(return_value=msgRecv)\n    mock_socket.state = AsyncMock()\n\n    # Mock websockets.connect to return our mock socket\n    with patch(\"websockets.connect\") as mock_connect:\n        mock_connect.return_value.__aenter__.return_value = mock_socket\n\n        ws = ReconnectingWebsocket(url=\"wss://test.url\")\n        async with ws:\n            msg = await ws.recv()\n            assert msg == json.loads(msgRecv)\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"Requires Python 3.8+\")\n@pytest.mark.asyncio\nasync def test_connect_fails_to_connect_on_enter_context():\n    \"\"\"Test ws.connect raises a ConnectionClosedError.\"\"\"\n    ws = ReconnectingWebsocket(url=\"wss://test.url\")\n    ws._conn = AsyncMock()\n    exception = Exception(\"Connection closed\")\n    ws._conn.__aenter__.side_effect = exception\n    with pytest.raises(Exception):\n        await ws.__aenter__()\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"Requires Python 3.8+\")\n@pytest.mark.asyncio\nasync def test_connect_fails_to_connect_after_disconnect():\n    # Create mock WebSocket client\n    mock_socket = create_autospec(WebSocketClientProtocol)\n    mock_socket.recv = AsyncMock(side_effect=delayed_return)\n    mock_socket.state = AsyncMock()\n\n    # Create mock connect that succeeds first, then fails\n    mock_connect = AsyncMock()\n    mock_connect.return_value.__aenter__.side_effect = [\n        mock_socket,  # First call succeeds\n        Exception(\"Connection failed\"),  # Subsequent calls fail\n    ]\n\n    with patch(\"websockets.connect\", return_value=mock_connect.return_value):\n        ws = ReconnectingWebsocket(url=\"wss://test.url\")\n        async with ws as ws:\n            assert ws.ws is not None\n            msg = await ws.recv()\n            ws.ws.state = State.CLOSED\n            await ws.ws.close()\n            while msg[\"e\"] != \"error\":\n                msg = await ws.recv()\n            # Receive the closed message attempting to reconnect\n            while msg[\"type\"] == \"BinanceWebsocketClosed\":\n                msg = await ws.recv()\n            # After retrying to reconnect, receive BinanceWebsocketUnableToConnect\n            assert msg[\"e\"] == \"error\"\n            assert msg[\"type\"] == \"BinanceWebsocketUnableToConnect\"\n\n\nasync def delayed_return():\n    await asyncio.sleep(0.1)  # 100 ms delay\n    return '{\"e\": \"value\"}'\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"Requires Python 3.8+\")\n@pytest.mark.asyncio\nasync def test_recv_read_loop_closed():\n    \"\"\"Test that recv() raises ReadLoopClosed when read loop is closed.\"\"\"\n    ws = ReconnectingWebsocket(url=\"wss://test.url\")\n    \n    # Simulate read loop being closed by setting _handle_read_loop to None\n    ws._handle_read_loop = None\n    \n    with pytest.raises(ReadLoopClosed) as exc_info:\n        await ws.recv()\n    \n    assert \"Read loop has been closed\" in str(exc_info.value)\n    assert \"please reset the websocket connection\" in str(exc_info.value)\n"
  },
  {
    "path": "tests/test_region_exception.py",
    "content": "\"\"\"Tests for BinanceRegionException and region validation.\"\"\"\n\nimport pytest\nfrom binance.client import Client\nfrom binance.async_client import AsyncClient\nfrom binance.exceptions import BinanceRegionException\n\n\nclass TestBinanceRegionException:\n    \"\"\"Tests for the BinanceRegionException class itself.\"\"\"\n\n    def test_exception_attributes(self):\n        \"\"\"Test that exception has correct attributes.\"\"\"\n        exc = BinanceRegionException(\"us\", \"com\", \"test_endpoint\")\n        assert exc.required_tld == \"us\"\n        assert exc.actual_tld == \"com\"\n        assert exc.endpoint_name == \"test_endpoint\"\n\n    def test_exception_message_format(self):\n        \"\"\"Test that exception message is properly formatted.\"\"\"\n        exc = BinanceRegionException(\"us\", \"com\", \"get_staking_asset_us\")\n        assert \"binance.us\" in str(exc)\n        assert \"binance.com\" in str(exc)\n        assert \"get_staking_asset_us\" in str(exc)\n\n    def test_exception_default_endpoint_name(self):\n        \"\"\"Test that endpoint_name defaults to 'endpoint'.\"\"\"\n        exc = BinanceRegionException(\"us\", \"com\")\n        assert exc.endpoint_name == \"endpoint\"\n        assert \"endpoint is only available\" in str(exc)\n\n\nclass TestSyncClientRegionValidation:\n    \"\"\"Tests for region validation in synchronous Client.\"\"\"\n\n    def test_get_staking_asset_us_wrong_tld(self):\n        \"\"\"Test that get_staking_asset_us raises exception for non-US client.\"\"\"\n        client = Client(\"test_key\", \"test_secret\", tld=\"com\", ping=False)\n        with pytest.raises(BinanceRegionException) as exc_info:\n            client.get_staking_asset_us()\n        assert exc_info.value.required_tld == \"us\"\n        assert exc_info.value.actual_tld == \"com\"\n        assert exc_info.value.endpoint_name == \"get_staking_asset_us\"\n\n    def test_stake_asset_us_wrong_tld(self):\n        \"\"\"Test that stake_asset_us raises exception for non-US client.\"\"\"\n        client = Client(\"test_key\", \"test_secret\", tld=\"com\", ping=False)\n        with pytest.raises(BinanceRegionException) as exc_info:\n            client.stake_asset_us()\n        assert exc_info.value.required_tld == \"us\"\n        assert exc_info.value.endpoint_name == \"stake_asset_us\"\n\n    def test_unstake_asset_us_wrong_tld(self):\n        \"\"\"Test that unstake_asset_us raises exception for non-US client.\"\"\"\n        client = Client(\"test_key\", \"test_secret\", tld=\"com\", ping=False)\n        with pytest.raises(BinanceRegionException) as exc_info:\n            client.unstake_asset_us()\n        assert exc_info.value.required_tld == \"us\"\n        assert exc_info.value.endpoint_name == \"unstake_asset_us\"\n\n    def test_get_staking_balance_us_wrong_tld(self):\n        \"\"\"Test that get_staking_balance_us raises exception for non-US client.\"\"\"\n        client = Client(\"test_key\", \"test_secret\", tld=\"com\", ping=False)\n        with pytest.raises(BinanceRegionException) as exc_info:\n            client.get_staking_balance_us()\n        assert exc_info.value.required_tld == \"us\"\n        assert exc_info.value.endpoint_name == \"get_staking_balance_us\"\n\n    def test_get_staking_history_us_wrong_tld(self):\n        \"\"\"Test that get_staking_history_us raises exception for non-US client.\"\"\"\n        client = Client(\"test_key\", \"test_secret\", tld=\"com\", ping=False)\n        with pytest.raises(BinanceRegionException) as exc_info:\n            client.get_staking_history_us()\n        assert exc_info.value.required_tld == \"us\"\n        assert exc_info.value.endpoint_name == \"get_staking_history_us\"\n\n    def test_get_staking_rewards_history_us_wrong_tld(self):\n        \"\"\"Test that get_staking_rewards_history_us raises exception for non-US client.\"\"\"\n        client = Client(\"test_key\", \"test_secret\", tld=\"com\", ping=False)\n        with pytest.raises(BinanceRegionException) as exc_info:\n            client.get_staking_rewards_history_us()\n        assert exc_info.value.required_tld == \"us\"\n        assert exc_info.value.endpoint_name == \"get_staking_rewards_history_us\"\n\n\n@pytest.mark.asyncio\nclass TestAsyncClientRegionValidation:\n    \"\"\"Tests for region validation in asynchronous AsyncClient.\"\"\"\n\n    async def test_get_staking_asset_us_wrong_tld_async(self):\n        \"\"\"Test that async get_staking_asset_us raises exception for non-US client.\"\"\"\n        client = AsyncClient(\"test_key\", \"test_secret\", tld=\"com\")\n        try:\n            with pytest.raises(BinanceRegionException) as exc_info:\n                await client.get_staking_asset_us()\n            assert exc_info.value.required_tld == \"us\"\n            assert exc_info.value.actual_tld == \"com\"\n            assert exc_info.value.endpoint_name == \"get_staking_asset_us\"\n        finally:\n            await client.close_connection()\n\n    async def test_stake_asset_us_wrong_tld_async(self):\n        \"\"\"Test that async stake_asset_us raises exception for non-US client.\"\"\"\n        client = AsyncClient(\"test_key\", \"test_secret\", tld=\"com\")\n        try:\n            with pytest.raises(BinanceRegionException) as exc_info:\n                await client.stake_asset_us()\n            assert exc_info.value.required_tld == \"us\"\n            assert exc_info.value.endpoint_name == \"stake_asset_us\"\n        finally:\n            await client.close_connection()\n\n    async def test_unstake_asset_us_wrong_tld_async(self):\n        \"\"\"Test that async unstake_asset_us raises exception for non-US client.\"\"\"\n        client = AsyncClient(\"test_key\", \"test_secret\", tld=\"com\")\n        try:\n            with pytest.raises(BinanceRegionException) as exc_info:\n                await client.unstake_asset_us()\n            assert exc_info.value.required_tld == \"us\"\n            assert exc_info.value.endpoint_name == \"unstake_asset_us\"\n        finally:\n            await client.close_connection()\n\n    async def test_get_staking_balance_us_wrong_tld_async(self):\n        \"\"\"Test that async get_staking_balance_us raises exception for non-US client.\"\"\"\n        client = AsyncClient(\"test_key\", \"test_secret\", tld=\"com\")\n        try:\n            with pytest.raises(BinanceRegionException) as exc_info:\n                await client.get_staking_balance_us()\n            assert exc_info.value.required_tld == \"us\"\n            assert exc_info.value.endpoint_name == \"get_staking_balance_us\"\n        finally:\n            await client.close_connection()\n\n    async def test_get_staking_history_us_wrong_tld_async(self):\n        \"\"\"Test that async get_staking_history_us raises exception for non-US client.\"\"\"\n        client = AsyncClient(\"test_key\", \"test_secret\", tld=\"com\")\n        try:\n            with pytest.raises(BinanceRegionException) as exc_info:\n                await client.get_staking_history_us()\n            assert exc_info.value.required_tld == \"us\"\n            assert exc_info.value.endpoint_name == \"get_staking_history_us\"\n        finally:\n            await client.close_connection()\n\n    async def test_get_staking_rewards_history_us_wrong_tld_async(self):\n        \"\"\"Test that async get_staking_rewards_history_us raises exception for non-US client.\"\"\"\n        client = AsyncClient(\"test_key\", \"test_secret\", tld=\"com\")\n        try:\n            with pytest.raises(BinanceRegionException) as exc_info:\n                await client.get_staking_rewards_history_us()\n            assert exc_info.value.required_tld == \"us\"\n            assert exc_info.value.endpoint_name == \"get_staking_rewards_history_us\"\n        finally:\n            await client.close_connection()\n"
  },
  {
    "path": "tests/test_socket_manager.py",
    "content": "from binance import BinanceSocketManager, AsyncClient\nimport pytest\nfrom .conftest import proxy\n\n\ndef assert_message(msg):\n    assert msg[\"stream\"] == \"!ticker@arr\"\n    assert len(msg[\"data\"]) > 0\n\n\n@pytest.mark.asyncio()\nasync def test_ticker_socket():\n    client = await AsyncClient.create(testnet=True, https_proxy=proxy)\n    bm = BinanceSocketManager(client)\n\n    ts = bm.futures_ticker_socket()\n\n    async with ts as tscm:\n        try:\n            res = await tscm.recv()\n            assert_message(res)\n        except Exception as e:\n            print(f\"An error occurred: {e}\")\n\n    await client.close_connection()\n"
  },
  {
    "path": "tests/test_streams.py",
    "content": "import sys\nfrom binance import BinanceSocketManager\nimport pytest\n\nfrom binance.async_client import AsyncClient\nfrom .conftest import proxy, api_key, api_secret, testnet\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\n@pytest.mark.asyncio\nasync def test_socket_stopped_on_aexit(clientAsync):\n    bm = BinanceSocketManager(clientAsync)\n    ts1 = bm.trade_socket(\"BNBBTC\")\n    async with ts1:\n        pass\n    assert bm._conns == {}, \"socket should be removed from _conn on exit\"\n    ts2 = bm.trade_socket(\"BNBBTC\")\n    assert ts2 is not ts1, \"socket should be removed from _conn on exit\"\n    await clientAsync.close_connection()\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\n@pytest.mark.asyncio\nasync def test_socket_stopped_on_aexit_futures(futuresClientAsync):\n    bm = BinanceSocketManager(futuresClientAsync)\n    ts1 = bm.futures_user_socket()\n    async with ts1:\n        pass\n    assert bm._conns == {}, \"socket should be removed from _conn on exit\"\n    await futuresClientAsync.close_connection()\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\n@pytest.mark.asyncio\nasync def test_socket_spot_market_time_unit_microseconds():\n    clientAsync = AsyncClient(\n        api_key, api_secret, https_proxy=proxy, testnet=testnet, time_unit=\"MICROSECOND\"\n    )\n    bm = BinanceSocketManager(clientAsync)\n    ts1 = bm.symbol_ticker_socket(\"BTCUSDT\")\n    async with ts1:\n        trade = await ts1.recv()\n        assert len(str(trade[\"E\"])) >= 16, \"Time should be in microseconds (16+ digits)\"\n    await clientAsync.close_connection()\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\n@pytest.mark.asyncio\nasync def test_socket_spot_market_time_unit_milliseconds():\n    clientAsync = AsyncClient(\n        api_key, api_secret, https_proxy=proxy, testnet=testnet, time_unit=\"MILLISECOND\"\n    )\n    bm = BinanceSocketManager(clientAsync)\n    ts1 = bm.symbol_ticker_socket(\"BTCUSDT\")\n    async with ts1:\n        trade = await ts1.recv()\n        assert len(str(trade[\"E\"])) == 13, \"Time should be in milliseconds (13 digits)\"\n    await clientAsync.close_connection()\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\n@pytest.mark.asyncio\nasync def test_socket_spot_user_data_time_unit_microseconds():\n    clientAsync = AsyncClient(\n        api_key, api_secret, https_proxy=proxy, testnet=testnet, time_unit=\"MICROSECOND\"\n    )\n    bm = BinanceSocketManager(clientAsync)\n    ts1 = bm.user_socket()\n    async with ts1:\n        await clientAsync.create_order(\n            symbol=\"LTCUSDT\", side=\"BUY\", type=\"MARKET\", quantity=0.1\n        )\n        trade = await ts1.recv()\n        assert len(str(trade[\"E\"])) >= 16, \"Time should be in microseconds (16+ digits)\"\n    await clientAsync.close_connection()\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\n@pytest.mark.asyncio\nasync def test_socket_spot_user_data_time_unit_milliseconds():\n    clientAsync = AsyncClient(\n        api_key, api_secret, https_proxy=proxy, testnet=testnet, time_unit=\"MILLISECOND\"\n    )\n    bm = BinanceSocketManager(clientAsync)\n    ts1 = bm.user_socket()\n    async with ts1:\n        await clientAsync.create_order(\n            symbol=\"LTCUSDT\", side=\"BUY\", type=\"MARKET\", quantity=0.1\n        )\n        trade = await ts1.recv()\n        assert len(str(trade[\"E\"])) == 13, \"Time should be in milliseconds (13 digits)\"\n    await clientAsync.close_connection()\n"
  },
  {
    "path": "tests/test_streams_options.py",
    "content": "import sys\nimport pytest\nimport logging\nfrom binance import BinanceSocketManager\n\npytestmark = [\n    pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\"),\n    pytest.mark.asyncio\n]\n\n# Configure logger for this module\nlogger = logging.getLogger(__name__)\n\n# Test constants\nOPTION_SYMBOL = \"BTC-251226-60000-P\"\nUNDERLYING_SYMBOL = \"BTC\"\nEXPIRATION_DATE = \"251226\"\nINTERVAL = \"1m\"\nDEPTH = \"20\"\n\nasync def test_options_ticker(clientAsync):\n    \"\"\"Test options ticker socket\"\"\"\n    logger.info(f\"Starting options ticker test for symbol: {OPTION_SYMBOL}\")\n    bm = BinanceSocketManager(clientAsync)\n    socket = bm.options_ticker_socket(OPTION_SYMBOL)\n    async with socket as ts:\n        logger.debug(\"Waiting for ticker message...\")\n        msg = await ts.recv()\n        logger.info(f\"Received ticker message: {msg}\")\n        assert msg['e'] == '24hrTicker'\n    logger.info(\"Options ticker test completed successfully\")\n    await clientAsync.close_connection()\n\nasync def test_options_ticker_by_expiration(clientAsync):\n    \"\"\"Test options ticker by expiration socket\"\"\"\n    logger.info(f\"Starting options ticker by expiration test for {UNDERLYING_SYMBOL}, expiration: {EXPIRATION_DATE}\")\n    bm = BinanceSocketManager(clientAsync)\n    socket = bm.options_ticker_by_expiration_socket(UNDERLYING_SYMBOL, EXPIRATION_DATE)\n    async with socket as ts:\n        logger.debug(\"Waiting for ticker by expiration message...\")\n        msg = await ts.recv()\n        logger.info(f\"Received {len(msg)} ticker messages\")\n        assert len(msg) > 0\n    logger.info(\"Options ticker by expiration test completed successfully\")\n    await clientAsync.close_connection()\n\nasync def test_options_recent_trades(clientAsync):\n    \"\"\"Test options recent trades socket\"\"\"\n    logger.info(f\"Starting options recent trades test for {UNDERLYING_SYMBOL}\")\n    bm = BinanceSocketManager(clientAsync)\n    socket = bm.options_recent_trades_socket(UNDERLYING_SYMBOL)\n    async with socket as ts:\n        logger.debug(\"Waiting for trade message...\")\n        msg = await ts.recv()\n        logger.info(f\"Received trade message: {msg}\")\n        assert msg['e'] == 'trade'\n    logger.info(\"Options recent trades test completed successfully\")\n    await clientAsync.close_connection()\n\nasync def test_options_kline(clientAsync):\n    \"\"\"Test options kline socket\"\"\"\n    logger.info(f\"Starting options kline test for {OPTION_SYMBOL}, interval: {INTERVAL}\")\n    bm = BinanceSocketManager(clientAsync)\n    socket = bm.options_kline_socket(OPTION_SYMBOL, INTERVAL)\n    async with socket as ts:\n        logger.debug(\"Waiting for kline message...\")\n        msg = await ts.recv()\n        logger.info(f\"Received kline message: {msg}\")\n        assert msg['e'] == 'kline'\n    logger.info(\"Options kline test completed successfully\")\n    await clientAsync.close_connection()\n\nasync def test_options_depth(clientAsync):\n    \"\"\"Test options depth socket\"\"\"\n    logger.info(f\"Starting options depth test for {OPTION_SYMBOL}, depth: {DEPTH}\")\n    bm = BinanceSocketManager(clientAsync)\n    socket = bm.options_depth_socket(OPTION_SYMBOL, DEPTH)\n    async with socket as ts:\n        logger.debug(\"Waiting for depth message...\")\n        msg = await ts.recv()\n        logger.info(f\"Received depth message: {msg}\")\n        assert msg['e'] == 'depth'\n    logger.info(\"Options depth test completed successfully\")\n    await clientAsync.close_connection()\n\nasync def test_options_multiplex(clientAsync):\n    \"\"\"Test options multiplex socket\"\"\"\n    streams = [\n        f\"{OPTION_SYMBOL}@ticker\",\n        f\"{OPTION_SYMBOL}@trade\",\n    ]\n    logger.info(f\"Starting options multiplex test with streams: {streams}\")\n    bm = BinanceSocketManager(clientAsync)\n    socket = bm.options_multiplex_socket(streams)\n    async with socket as ts:\n        logger.debug(\"Waiting for multiplex message...\")\n        msg = await ts.recv()\n        logger.info(f\"Received multiplex message: {msg}\")\n        assert 'stream' in msg\n    logger.info(\"Options multiplex test completed successfully\")\n    await clientAsync.close_connection()\n\nasync def test_options_open_interest(clientAsync):\n    \"\"\"Test options open interest socket\"\"\"\n    logger.info(f\"Starting options open interest test for {UNDERLYING_SYMBOL}, expiration: {EXPIRATION_DATE}\")\n    bm = BinanceSocketManager(clientAsync)\n    socket = bm.options_open_interest_socket(UNDERLYING_SYMBOL, EXPIRATION_DATE)\n    async with socket as ts:\n        logger.debug(\"Waiting for open interest message...\")\n        msg = await ts.recv()\n        logger.info(f\"Received open interest message with {len(msg)} items\")\n        assert len(msg) > 0\n    logger.info(\"Options open interest test completed successfully\")\n    await clientAsync.close_connection()\n\nasync def test_options_mark_price(clientAsync):\n    \"\"\"Test options mark price socket\"\"\"\n    logger.info(f\"Starting options mark price test for {UNDERLYING_SYMBOL}\")\n    bm = BinanceSocketManager(clientAsync)\n    socket = bm.options_mark_price_socket(UNDERLYING_SYMBOL)\n    async with socket as ts:\n        logger.debug(\"Waiting for mark price message...\")\n        msg = await ts.recv()\n        logger.info(f\"Received mark price message with {len(msg)} items\")\n        assert len(msg) > 0\n    logger.info(\"Options mark price test completed successfully\")\n    await clientAsync.close_connection()\n\nasync def test_options_index_price(clientAsync):\n    \"\"\"Test options index price socket\"\"\"\n    symbol = 'ETHUSDT'\n    logger.info(f\"Starting options index price test for {symbol}\")\n    bm = BinanceSocketManager(clientAsync)\n    socket = bm.options_index_price_socket(symbol)\n    async with socket as ts:\n        logger.debug(\"Waiting for index price message...\")\n        msg = await ts.recv()\n        logger.info(f\"Received index price message: {msg}\")\n        assert msg['e'] == 'index'\n    logger.info(\"Options index price test completed successfully\")\n    await clientAsync.close_connection()\n"
  },
  {
    "path": "tests/test_threaded_socket_manager.py",
    "content": "from binance import ThreadedWebsocketManager\nfrom binance.client import Client\nimport asyncio\nimport time\nfrom .conftest import proxies, api_key, api_secret, proxy\nimport pytest\nimport sys\nimport logging\n\npytestmark = pytest.mark.skipif(\n    sys.version_info <= (3, 8),\n    reason=\"These tests require Python 3.8+ for proper websocket proxy support\"\n)\n\nreceived_ohlcv = False\nreceived_depth = False\n\ntwm: ThreadedWebsocketManager\n\n# Add logger definition before using it\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n\n# Get real symbols from Binance API\nclient = Client(api_key, api_secret, {\"proxies\": proxies})\nexchange_info = client.get_exchange_info()\nsymbols = [info['symbol'].lower() for info in exchange_info['symbols']]\nstreams = [f\"{symbol}@bookTicker\" for symbol in symbols][0:100]  # Take first 800 symbols\n\ndef test_threaded_socket_manager():\n    logger.debug(\"Starting test_threaded_socket_manager\")\n    global twm\n    twm = ThreadedWebsocketManager(api_key, api_secret, https_proxy=proxy, testnet=True)\n\n    symbol = \"BTCUSDT\"\n\n    def handle_socket_message(msg):\n        global received_ohlcv, received_depth\n        if \"e\" in msg:\n            if msg[\"e\"] == \"depthUpdate\":\n                logger.debug(\"Received depth update message\")\n                received_depth = True\n            if msg[\"e\"] == \"kline\":\n                logger.debug(\"Received kline message\")\n                received_ohlcv = True\n        if received_depth and received_ohlcv:\n            logger.debug(\"Received both depth and OHLCV messages, stopping\")\n            twm.stop()\n\n    try:\n        logger.debug(\"Starting ThreadedWebsocketManager\")\n        twm.start()\n        logger.debug(\"Starting kline socket for %s\", symbol)\n        twm.start_kline_socket(callback=handle_socket_message, symbol=symbol)\n        logger.debug(\"Starting depth socket for %s\", symbol)\n        twm.start_depth_socket(callback=handle_socket_message, symbol=symbol)\n        twm.join()\n    finally:\n        logger.debug(\"Cleaning up test_threaded_socket_manager\")\n        twm.stop()\n        time.sleep(2)\n\n\ndef test_many_symbols_small_queue():\n    logger.debug(\"Starting test_many_symbols_small_queue with queue size 1\")\n    twm = ThreadedWebsocketManager(api_key, api_secret, https_proxy=proxy, testnet=True, max_queue_size=1)\n    \n    error_received = False\n    msg_received = False\n    \n    def handle_message(msg):\n        nonlocal error_received, msg_received\n        if msg.get(\"e\") == \"error\":\n            error_received = True\n            logger.debug(\"Received WebSocket error: %s\", msg.get('m', 'Unknown error'))\n            return\n        msg_received = True\n        logger.debug(\"Received valid message\")\n    \n    try:\n        logger.debug(\"Starting ThreadedWebsocketManager\")\n        twm.start()\n        logger.debug(\"Starting multiplex socket with %d streams\", len(streams))\n        twm.start_multiplex_socket(callback=handle_message, streams=streams)\n        logger.debug(\"Waiting 10 seconds for messages\")\n        time.sleep(10)\n        \n        assert msg_received, \"Should have received messages\"\n    finally:\n        logger.debug(\"Cleaning up test_many_symbols_small_queue\")\n        twm.stop()\n        time.sleep(2)\n\n\ndef test_many_symbols_adequate_queue():\n    logger.debug(\"Starting test_many_symbols_adequate_queue with queue size 200\")\n    twm = ThreadedWebsocketManager(api_key, api_secret, https_proxy=proxy, testnet=True, max_queue_size=200)\n    \n    messages_received = 0\n    error_received = False\n    \n    def handle_message(msg):\n        nonlocal messages_received, error_received\n        if msg.get(\"e\") == \"error\":\n            error_received = True\n            logger.debug(\"Received WebSocket error: %s\", msg.get('m', 'Unknown error'))\n            return\n            \n        messages_received += 1\n        if messages_received % 10 == 0:  # Log every 10th message\n            logger.debug(\"Processed %d messages\", messages_received)\n    \n    try:\n        logger.debug(\"Starting ThreadedWebsocketManager\")\n        twm.start()\n        logger.debug(\"Starting futures multiplex socket with %d streams\", len(streams))\n        twm.start_futures_multiplex_socket(callback=handle_message, streams=streams)\n        logger.debug(\"Waiting 10 seconds for messages\")\n        time.sleep(10)\n        \n        logger.debug(\"Test completed. Messages received: %d, Errors: %s\", messages_received, error_received)\n        assert messages_received > 0, \"Should have received some messages\"\n        assert not error_received, \"Should not have received any errors\"\n    finally:\n        logger.debug(\"Cleaning up test_many_symbols_adequate_queue\")\n        twm.stop()\n        time.sleep(2)\n\n\ndef test_slow_async_callback_no_error():\n    logger.debug(\"Starting test_slow_async_callback_no_error with queue size 400\")\n    twm = ThreadedWebsocketManager(api_key, api_secret, https_proxy=proxy, testnet=True, max_queue_size=400)\n    \n    messages_processed = 0\n    error_received = False\n    \n    async def slow_async_callback(msg):\n        nonlocal messages_processed, error_received\n        if msg.get(\"e\") == \"error\":\n            error_received = True\n            logger.debug(\"Received WebSocket error: %s\", msg.get('m', 'Unknown error'))\n            return\n            \n        logger.debug(\"Processing message with 2 second delay\")\n        await asyncio.sleep(2)\n        messages_processed += 1\n        logger.debug(\"Message processed. Total processed: %d\", messages_processed)\n    \n    try:\n        logger.debug(\"Starting ThreadedWebsocketManager\")\n        twm.start()\n        logger.debug(\"Starting futures multiplex socket with %d streams\", len(streams))\n        twm.start_futures_multiplex_socket(callback=slow_async_callback, streams=streams)\n        logger.debug(\"Waiting 10 seconds for messages\")\n        time.sleep(10)\n        \n        logger.debug(\"Test completed. Messages processed: %d, Errors: %s\", messages_processed, error_received)\n        assert messages_processed > 0, \"Should have processed some messages\"\n        assert not error_received, \"Should not have received any errors\"\n    finally:\n        logger.debug(\"Cleaning up test_slow_async_callback_no_error\")\n        twm.stop()\n        time.sleep(2)\n\n\ndef test_no_internet_connection():\n    \"\"\"Test that socket manager times out when there's no internet connection\"\"\"\n    logger.debug(\"Starting test_no_internet_connection\")\n    invalid_proxy = \"http://invalid.proxy:1234\"\n    logger.debug(\"Using invalid proxy: %s\", invalid_proxy)\n    \n    with pytest.raises(RuntimeError, match=\"Binance Socket Manager failed to initialize after 5 seconds\"):\n        twm = ThreadedWebsocketManager(\n            api_key, \n            api_secret, \n            https_proxy=invalid_proxy, \n            testnet=True\n        )\n        \n        try:\n            logger.debug(\"Attempting to start ThreadedWebsocketManager with invalid proxy\")\n            twm.start()\n            logger.debug(\"Attempting to start kline socket (should fail)\")\n            twm.start_kline_socket(\n                callback=lambda x: print(x), \n                symbol=\"BTCUSDT\"\n            )\n        finally:\n            logger.debug(\"Cleaning up test_no_internet_connection\")\n            twm.stop()\n            time.sleep(2)\n"
  },
  {
    "path": "tests/test_threaded_stream.py",
    "content": "import pytest\nimport asyncio\n\nimport websockets\nfrom binance.ws.threaded_stream import ThreadedApiManager\nfrom unittest.mock import Mock\n\n# For Python 3.7 compatibility\ntry:\n    from unittest.mock import AsyncMock\nexcept ImportError:\n    # Create our own AsyncMock for Python 3.7\n    class AsyncMock(Mock):\n        async def __call__(self, *args, **kwargs):\n            return super(AsyncMock, self).__call__(*args, **kwargs)\n\n        async def __aenter__(self):\n            return self\n\n        async def __aexit__(self, *args):\n            return None\n\n        async def __aiter__(self):\n            return self\n\n        async def __anext__(self):\n            raise StopAsyncIteration\n\n\n@pytest.mark.asyncio\nasync def test_initialization():\n    \"\"\"Test that manager initializes with correct parameters\"\"\"\n    manager = ThreadedApiManager(\n        api_key=\"test_key\",\n        api_secret=\"test_secret\",\n        tld=\"com\",\n        testnet=True,\n        requests_params={\"timeout\": 10},\n        session_params={\"trust_env\": True},\n    )\n\n    assert manager._running is True\n    assert manager._socket_running == {}\n    assert manager._client_params == {\n        \"api_key\": \"test_key\",\n        \"api_secret\": \"test_secret\",\n        \"requests_params\": {\"timeout\": 10},\n        \"tld\": \"com\",\n        \"testnet\": True,\n        \"session_params\": {\"trust_env\": True},\n        \"https_proxy\": None,\n        \"verbose\": False,\n    }\n\n\n@pytest.mark.asyncio\nasync def test_start_and_stop_socket(manager):\n    \"\"\"Test starting and stopping a socket\"\"\"\n    socket_name = \"test_socket\"\n\n    # AsyncMock socket creation\n    mock_socket = AsyncMock()\n    mock_socket.__aenter__ = AsyncMock(return_value=mock_socket)\n    mock_socket.__aexit__ = AsyncMock(return_value=None)\n\n    # Track number of recv calls\n    recv_count = 0\n\n    async def controlled_recv():\n        nonlocal recv_count\n        recv_count += 1\n        # If we've stopped the socket or read enough times, simulate connection closing\n        if not manager._socket_running.get(socket_name) or recv_count > 2:\n            raise websockets.exceptions.ConnectionClosed(None, None)\n        await asyncio.sleep(0.1)\n        return '{\"e\": \"value\"}'\n\n    mock_socket.recv = controlled_recv\n\n    # AsyncMock callback\n    callback = AsyncMock()\n\n    # Start socket listener\n    manager._socket_running[socket_name] = True\n    listener_task = asyncio.create_task(\n        manager.start_listener(mock_socket, socket_name, callback)\n    )\n\n    # Give some time for the listener to start and receive a message\n    await asyncio.sleep(0.2)\n\n    # Stop the socket\n    manager.stop_socket(socket_name)\n\n    # Wait for the listener task to complete\n    try:\n        await asyncio.wait_for(listener_task, timeout=1.0)\n    except (asyncio.TimeoutError, websockets.exceptions.ConnectionClosed):\n        pass  # These exceptions are expected during shutdown\n\n    assert socket_name not in manager._socket_running\n\n\n@pytest.mark.asyncio\nasync def test_socket_listener_timeout(manager):\n    \"\"\"Test socket listener handling timeout\"\"\"\n    socket_name = \"test_socket\"\n\n    # AsyncMock socket that times out every time\n    mock_socket = AsyncMock()\n    mock_socket.__aenter__ = AsyncMock(return_value=mock_socket)\n    mock_socket.__aexit__ = AsyncMock(return_value=None)\n\n    async def controlled_recv():\n        await asyncio.sleep(0.1)\n        raise asyncio.TimeoutError(\"Simulated Timeout\")\n\n    mock_socket.recv = controlled_recv\n\n    callback = AsyncMock()\n\n    # Start socket listener\n    manager._socket_running[socket_name] = True\n    listener_task = asyncio.create_task(\n        manager.start_listener(mock_socket, socket_name, callback)\n    )\n\n    # Give some time for a few timeout cycles\n    await asyncio.sleep(0.3)\n\n    # Stop the socket\n    manager.stop_socket(socket_name)\n\n    # Wait for the listener to finish\n    try:\n        await asyncio.wait_for(listener_task, timeout=1.0)\n    except (asyncio.TimeoutError, websockets.exceptions.ConnectionClosed):\n        listener_task.cancel()\n\n    # Callback should not have been called (no successful messages)\n    callback.assert_not_called()\n    assert socket_name not in manager._socket_running\n\n\n@pytest.mark.asyncio\nasync def test_stop_client(manager):\n    \"\"\"Test stopping the client\"\"\"\n    # AsyncMock AsyncClient\n    mock_client = AsyncMock()\n    mock_client.close_connection = AsyncMock()\n    manager._client = mock_client\n\n    await manager.stop_client()\n    mock_client.close_connection.assert_called_once()\n\n\n@pytest.mark.asyncio\nasync def test_stop(manager):\n    \"\"\"Test stopping the manager\"\"\"\n    socket_name = \"test_socket\"\n    manager._socket_running[socket_name] = True\n\n    manager.stop()\n\n    assert manager._running is False\n    assert manager._socket_running[socket_name] is False\n\n\n@pytest.mark.asyncio\nasync def test_multiple_sockets(manager):\n    \"\"\"Test managing multiple sockets\"\"\"\n    socket_names = [\"socket1\", \"socket2\", \"socket3\"]\n\n    # Start multiple sockets\n    for name in socket_names:\n        manager._socket_running[name] = True\n\n    # Stop all sockets\n    manager.stop()\n\n    # Verify all sockets are stopped\n    for name in socket_names:\n        assert manager._socket_running[name] is False\n\n\n@pytest.mark.asyncio\nasync def test_stop_client_when_not_initialized(manager):\n    \"\"\"Test stopping client when it hasn't been initialized\"\"\"\n    manager._client = None\n    await manager.stop_client()  # Should not raise any exception\n\n\n@pytest.mark.asyncio\nasync def test_stop_when_already_stopped(manager):\n    \"\"\"Test stopping manager when it's already stopped\"\"\"\n    manager._running = False\n    manager.stop()  # Should not raise any exception or change state\n    assert manager._running is False\n"
  },
  {
    "path": "tests/test_user_socket_integration.py",
    "content": "\"\"\"\nIntegration tests for user socket with ws_api subscription routing.\n\nThese tests verify that the user socket correctly:\n1. Uses ws_api for subscription (not creating its own connection)\n2. Has its own queue for receiving events (not sharing ws_api's queue)\n3. Does not start its own read loop (ws_api handles reading)\n4. Properly cleans up subscriptions on exit\n\nRequirements:\n- Binance testnet API credentials (configured in conftest.py)\n- Network connectivity to testnet\n\nRun with: pytest tests/test_user_socket_integration.py -v\n\"\"\"\nimport asyncio\nimport pytest\nimport pytest_asyncio\n\nfrom binance import BinanceSocketManager\n\n\n@pytest_asyncio.fixture\nasync def socket_manager(clientAsync):\n    \"\"\"Create a BinanceSocketManager using the clientAsync fixture from conftest.\"\"\"\n    return BinanceSocketManager(clientAsync)\n\n\nclass TestUserSocketArchitecture:\n    \"\"\"Tests verifying the user socket architecture is correct.\"\"\"\n\n    @pytest.mark.asyncio\n    async def test_user_socket_has_separate_queue(self, clientAsync, socket_manager):\n        \"\"\"User socket should have its own queue, not share ws_api's queue.\"\"\"\n        user_socket = socket_manager.user_socket()\n\n        async with user_socket:\n            # Queues should be different objects\n            assert user_socket._queue is not clientAsync.ws_api._queue, \\\n                \"user_socket should have its own queue, not share ws_api's queue\"\n\n    @pytest.mark.asyncio\n    async def test_user_socket_uses_ws_api_subscription(self, clientAsync, socket_manager):\n        \"\"\"User socket should use ws_api subscription mechanism.\"\"\"\n        user_socket = socket_manager.user_socket()\n\n        async with user_socket:\n            # Should be marked as using ws_api subscription\n            assert user_socket._uses_ws_api_subscription is True, \\\n                \"user_socket should be marked as using ws_api subscription\"\n\n            # Should have a subscription ID\n            assert user_socket._subscription_id is not None, \\\n                \"user_socket should have a subscription ID\"\n\n    @pytest.mark.asyncio\n    async def test_user_socket_no_read_loop(self, clientAsync, socket_manager):\n        \"\"\"User socket should NOT have its own read loop (ws_api handles reading).\"\"\"\n        user_socket = socket_manager.user_socket()\n\n        async with user_socket:\n            # user_socket should not have started its own read loop\n            assert user_socket._handle_read_loop is None, \\\n                \"user_socket should not have its own read loop\"\n\n            # ws_api should have a read loop\n            assert clientAsync.ws_api._handle_read_loop is not None, \\\n                \"ws_api should have a read loop\"\n\n    @pytest.mark.asyncio\n    async def test_user_socket_queue_registered_with_ws_api(self, clientAsync, socket_manager):\n        \"\"\"User socket's queue should be registered with ws_api for event routing.\"\"\"\n        user_socket = socket_manager.user_socket()\n\n        async with user_socket:\n            sub_id = user_socket._subscription_id\n\n            # Subscription should be registered in ws_api\n            assert sub_id in clientAsync.ws_api._subscription_queues, \\\n                \"Subscription should be registered with ws_api\"\n\n            # Registered queue should be user_socket's queue\n            registered_queue = clientAsync.ws_api._subscription_queues[sub_id]\n            assert registered_queue is user_socket._queue, \\\n                \"Registered queue should be user_socket's queue\"\n\n    @pytest.mark.asyncio\n    async def test_user_socket_cleanup_on_exit(self, clientAsync, socket_manager):\n        \"\"\"User socket should unregister from ws_api on exit.\"\"\"\n        user_socket = socket_manager.user_socket()\n\n        async with user_socket:\n            sub_id = user_socket._subscription_id\n            # Verify it's registered while connected\n            assert sub_id in clientAsync.ws_api._subscription_queues\n\n        # After exit, subscription should be unregistered\n        assert sub_id not in clientAsync.ws_api._subscription_queues, \\\n            \"Subscription should be unregistered after exit\"\n\n\nclass TestUserSocketFunctionality:\n    \"\"\"Tests verifying user socket functionality works correctly.\"\"\"\n\n    @pytest.mark.asyncio\n    async def test_user_socket_recv_timeout(self, clientAsync, socket_manager):\n        \"\"\"User socket recv() should timeout gracefully when no events.\"\"\"\n        user_socket = socket_manager.user_socket()\n\n        async with user_socket:\n            # recv() should timeout without errors (no events on quiet account)\n            with pytest.raises(asyncio.TimeoutError):\n                await asyncio.wait_for(user_socket.recv(), timeout=2)\n\n    @pytest.mark.asyncio\n    async def test_user_socket_context_manager(self, clientAsync, socket_manager):\n        \"\"\"User socket should work as async context manager.\"\"\"\n        user_socket = socket_manager.user_socket()\n\n        # Should not be connected initially\n        assert user_socket._subscription_id is None\n\n        async with user_socket:\n            # Should be connected inside context\n            assert user_socket._subscription_id is not None\n            assert user_socket._uses_ws_api_subscription is True\n\n        # Subscription ID is cleared after unsubscribe\n        assert user_socket._subscription_id is None\n\n\nclass TestNonUserSockets:\n    \"\"\"Tests verifying other socket types still work normally.\"\"\"\n\n    @pytest.mark.asyncio\n    async def test_margin_socket_not_using_ws_api_subscription(self, clientAsync, socket_manager):\n        \"\"\"Non-user KeepAliveWebsockets (like margin socket) should not use ws_api subscription.\"\"\"\n        # margin_socket is a KeepAliveWebsocket with keepalive_type=\"margin\"\n        # Create it but don't connect - just check the flag\n        margin_socket = socket_manager.margin_socket()\n\n        # Before connecting, the flag should be False (default)\n        assert margin_socket._uses_ws_api_subscription is False, \\\n            \"Margin socket should not use ws_api subscription\"\n\n        # The _keepalive_type should be \"margin\", not \"user\"\n        assert margin_socket._keepalive_type == \"margin\"\n\n\nclass TestWsApiSubscriptionRouting:\n    \"\"\"Tests verifying ws_api correctly routes subscription events.\"\"\"\n\n    @pytest.mark.asyncio\n    async def test_ws_api_has_subscription_queues(self, clientAsync):\n        \"\"\"ws_api should have subscription queues dict.\"\"\"\n        # Ensure ws_api is initialized\n        await clientAsync.ws_api._ensure_ws_connection()\n\n        assert hasattr(clientAsync.ws_api, '_subscription_queues'), \\\n            \"ws_api should have _subscription_queues attribute\"\n        assert isinstance(clientAsync.ws_api._subscription_queues, dict), \\\n            \"_subscription_queues should be a dict\"\n\n    @pytest.mark.asyncio\n    async def test_ws_api_register_unregister_queue(self, clientAsync):\n        \"\"\"ws_api should be able to register and unregister queues.\"\"\"\n        await clientAsync.ws_api._ensure_ws_connection()\n\n        test_queue = asyncio.Queue()\n        test_sub_id = \"test_subscription_123\"\n\n        # Register\n        clientAsync.ws_api.register_subscription_queue(test_sub_id, test_queue)\n        assert test_sub_id in clientAsync.ws_api._subscription_queues\n        assert clientAsync.ws_api._subscription_queues[test_sub_id] is test_queue\n\n        # Unregister\n        clientAsync.ws_api.unregister_subscription_queue(test_sub_id)\n        assert test_sub_id not in clientAsync.ws_api._subscription_queues\n\n    @pytest.mark.asyncio\n    async def test_ws_api_unregister_nonexistent_is_safe(self, clientAsync):\n        \"\"\"Unregistering a non-existent subscription should not raise.\"\"\"\n        await clientAsync.ws_api._ensure_ws_connection()\n\n        # Should not raise\n        clientAsync.ws_api.unregister_subscription_queue(\"nonexistent_sub_id\")\n\n\nif __name__ == \"__main__\":\n    pytest.main([__file__, \"-v\"])\n"
  },
  {
    "path": "tests/test_verbose_mode.py",
    "content": "\"\"\"Tests for verbose mode functionality\"\"\"\n\nimport pytest\nimport logging\nfrom binance.client import Client\nfrom binance.async_client import AsyncClient\n\n\ndef test_client_verbose_initialization():\n    \"\"\"Test that Client can be initialized with verbose mode\"\"\"\n    client = Client(verbose=True, ping=False)\n    assert client.verbose is True\n    assert client.logger is not None\n    assert client.logger.level == logging.DEBUG\n\n\ndef test_client_non_verbose_initialization():\n    \"\"\"Test that Client defaults to non-verbose mode\"\"\"\n    client = Client(verbose=False, ping=False)\n    assert client.verbose is False\n    assert client.logger is not None\n    # When verbose=False, we don't set the logger level (respects external config)\n\n\ndef test_client_default_verbose():\n    \"\"\"Test that Client defaults to verbose=False\"\"\"\n    client = Client(ping=False)\n    assert client.verbose is False\n\n\n@pytest.mark.asyncio()\nasync def test_async_client_verbose_initialization():\n    \"\"\"Test that AsyncClient can be initialized with verbose mode\"\"\"\n    client = AsyncClient(verbose=True)\n    assert client.verbose is True\n    assert client.logger is not None\n    assert client.logger.level == logging.DEBUG\n    await client.close_connection()\n\n\n@pytest.mark.asyncio()\nasync def test_async_client_non_verbose_initialization():\n    \"\"\"Test that AsyncClient defaults to non-verbose mode\"\"\"\n    client = AsyncClient(verbose=False)\n    assert client.verbose is False\n    assert client.logger is not None\n    # When verbose=False, we don't set the logger level (respects external config)\n    await client.close_connection()\n\n\n@pytest.mark.asyncio()\nasync def test_async_client_default_verbose():\n    \"\"\"Test that AsyncClient defaults to verbose=False\"\"\"\n    client = AsyncClient()\n    assert client.verbose is False\n    await client.close_connection()\n"
  },
  {
    "path": "tests/test_websocket_verbose.py",
    "content": "\"\"\"Tests for WebSocket verbose logging\"\"\"\n\nimport logging\nimport pytest\n\n\ndef test_websocket_logger_exists():\n    \"\"\"Test that WebSocket loggers can be configured\"\"\"\n    # Test main WebSocket logger\n    ws_logger = logging.getLogger(\"binance.ws\")\n    assert ws_logger is not None\n\n    # Test WebSocket API logger\n    ws_api_logger = logging.getLogger(\"binance.ws.websocket_api\")\n    assert ws_api_logger is not None\n\n    # Test reconnecting WebSocket logger\n    ws_reconnect_logger = logging.getLogger(\"binance.ws.reconnecting_websocket\")\n    assert ws_reconnect_logger is not None\n\n    # Test streams logger\n    ws_streams_logger = logging.getLogger(\"binance.ws.streams\")\n    assert ws_streams_logger is not None\n\n\ndef test_websocket_logger_level_configuration():\n    \"\"\"Test that WebSocket logger levels can be set\"\"\"\n    ws_logger = logging.getLogger(\"binance.ws.test_config\")\n\n    # Set to DEBUG\n    ws_logger.setLevel(logging.DEBUG)\n    assert ws_logger.level == logging.DEBUG\n\n    # Set to INFO\n    ws_logger.setLevel(logging.INFO)\n    assert ws_logger.level == logging.INFO\n\n    # Set to WARNING\n    ws_logger.setLevel(logging.WARNING)\n    assert ws_logger.level == logging.WARNING\n\n\ndef test_combined_logging_configuration():\n    \"\"\"Test that both REST and WebSocket logging can be configured together\"\"\"\n    # Configure REST verbose logging\n    from binance.client import Client\n\n    # This should work without errors\n    client = Client(verbose=True, ping=False)\n    assert client.verbose is True\n    assert client.logger is not None\n\n    # Configure WebSocket logging\n    ws_logger = logging.getLogger(\"binance.ws\")\n    ws_logger.setLevel(logging.DEBUG)\n    assert ws_logger.level == logging.DEBUG\n\n    # Both should be independently configurable\n    assert client.logger.level == logging.DEBUG\n    assert ws_logger.level == logging.DEBUG\n\n\n@pytest.mark.asyncio()\nasync def test_binance_socket_manager_verbose():\n    \"\"\"Test that BinanceSocketManager can be initialized with verbose mode\"\"\"\n    from binance import AsyncClient, BinanceSocketManager\n\n    client = AsyncClient()\n\n    # Test with verbose=True\n    bm_verbose = BinanceSocketManager(client, verbose=True)\n    assert bm_verbose.verbose is True\n\n    # Test with verbose=False (default)\n    bm_quiet = BinanceSocketManager(client, verbose=False)\n    assert bm_quiet.verbose is False\n\n    # Test default\n    bm_default = BinanceSocketManager(client)\n    assert bm_default.verbose is False\n\n    await client.close_connection()\n\n\ndef test_threaded_websocket_manager_verbose():\n    \"\"\"Test that ThreadedApiManager can be initialized with verbose mode\"\"\"\n    from binance.ws.threaded_stream import ThreadedApiManager\n\n    # Test with verbose=True\n    twm_verbose = ThreadedApiManager(verbose=True)\n    assert twm_verbose.verbose is True\n\n    # Test with verbose=False (default)\n    twm_quiet = ThreadedApiManager(verbose=False)\n    assert twm_quiet.verbose is False\n\n    # Test default\n    twm_default = ThreadedApiManager()\n    assert twm_default.verbose is False\n\n\ndef test_websocket_manager_sets_logging_level():\n    \"\"\"Test that verbose mode sets the logging level for WebSocket managers\"\"\"\n    from binance.ws.threaded_stream import ThreadedApiManager\n\n    # Get initial logging level\n    ws_logger = logging.getLogger(\"binance.ws\")\n    initial_level = ws_logger.level\n\n    # Create manager with verbose=True\n    twm = ThreadedApiManager(verbose=True)\n\n    # Check that logging level was set to DEBUG\n    assert ws_logger.level == logging.DEBUG\n\n    # Restore initial level\n    ws_logger.setLevel(initial_level)\n"
  },
  {
    "path": "tests/test_ws_api.py",
    "content": "import json\nimport sys\nimport pytest\nimport asyncio\nfrom binance import AsyncClient\n\nfrom binance.exceptions import BinanceAPIException, BinanceWebsocketUnableToConnect\nfrom binance.ws.constants import WSListenerState\nfrom .test_get_order_book import assert_ob\nfrom .conftest import proxy\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\n@pytest.mark.asyncio\nasync def test_ws_api_public_endpoint(clientAsync):\n    \"\"\"Test normal order book request\"\"\"\n    order_book = await clientAsync.ws_get_order_book(symbol=\"BTCUSDT\")\n    assert_ob(order_book)\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\n@pytest.mark.asyncio\nasync def test_ws_api_private_endpoint(clientAsync):\n    \"\"\"Test normal order book request\"\"\"\n    orders = await clientAsync.ws_get_all_orders(symbol=\"BTCUSDT\")\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\n@pytest.mark.asyncio\nasync def test_ws_futures_public_endpoint(futuresClientAsync):\n    \"\"\"Test normal order book request\"\"\"\n    order_book = await futuresClientAsync.ws_futures_get_order_book(symbol=\"BTCUSDT\")\n    assert_ob(order_book)\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\n@pytest.mark.asyncio\nasync def test_ws_futures_private_endpoint(futuresClientAsync):\n    \"\"\"Test normal order book request\"\"\"\n    await futuresClientAsync.ws_futures_v2_account_position(symbol=\"BTCUSDT\")\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\n@pytest.mark.asyncio\nasync def test_ws_get_symbol_ticker(clientAsync):\n    \"\"\"Test symbol ticker request\"\"\"\n    ticker = await clientAsync.ws_get_symbol_ticker(symbol=\"BTCUSDT\")\n    assert \"symbol\" in ticker\n    assert ticker[\"symbol\"] == \"BTCUSDT\"\n\n\n@pytest.mark.asyncio\nasync def test_invalid_request(clientAsync):\n    pass\n    # \"\"\"Test error handling for invalid symbol\"\"\"\n    # with pytest.raises(\n    #     BinanceAPIException,\n    #     match=re.escape(\n    #         \"APIError(code=-1100): Illegal characters found in parameter 'symbol'; legal range is \\'^[\\\\\\\\w\\\\\\\\-._&&[^a-z]]{1,50}$\\'.\"\n    #     ),\n    # ):\n        \n    #     # {'id': 'a2790cf96b11a8add71ebf', 'status': 400, 'error': {'code': -1100...:-1100,\"msg\":\"Illegal characters found in parameter \\'symbol\\'; legal range is \\'^[\\\\\\\\w\\\\\\\\-._&&[^a-z]]{1,50}$\\'.\"}'\n    #     await clientAsync.ws_get_order_book(symbol=\"send error\")\n\n\n@pytest.mark.asyncio\nasync def test_connection_handling(clientAsync):\n    \"\"\"Test connection handling and reconnection\"\"\"\n    # First request should establish connection\n    await clientAsync.ws_get_order_book(symbol=\"BTCUSDT\")\n    assert clientAsync.ws_api.ws_state == WSListenerState.STREAMING\n\n    # Force connection close\n    await clientAsync.close_connection()\n    assert clientAsync.ws_api.ws_state == WSListenerState.EXITING\n    assert clientAsync.ws_api.ws is None\n\n    # Next request should reconnect\n    order_book = await clientAsync.ws_get_order_book(symbol=\"LTCUSDT\")\n    assert_ob(order_book)\n    assert clientAsync.ws_api.ws_state == WSListenerState.STREAMING\n\n\n@pytest.mark.asyncio\nasync def test_timeout_handling(clientAsync):\n    \"\"\"Test request timeout handling\"\"\"\n    # Set very short timeout to force timeout error\n    original_timeout = clientAsync.ws_api.TIMEOUT\n    clientAsync.ws_api.TIMEOUT = 0.0001\n\n    try:\n        with pytest.raises(BinanceWebsocketUnableToConnect, match=\"Request timed out\"):\n            await clientAsync.ws_get_order_book(symbol=\"BTCUSDT\")\n    finally:\n        clientAsync.ws_api.TIMEOUT = original_timeout\n\n\n@pytest.mark.asyncio\nasync def test_multiple_requests(clientAsync):\n    \"\"\"Test multiple concurrent requests\"\"\"\n    symbols = [\"BTCUSDT\", \"ETHUSDT\", \"BNBUSDT\"]\n    tasks = [clientAsync.ws_get_order_book(symbol=symbol) for symbol in symbols]\n    results = await asyncio.gather(*tasks)\n    assert len(results) == len(symbols)\n    for result in results:\n        assert_ob(result)\n\n\n@pytest.mark.asyncio\nasync def test_testnet_url():\n    \"\"\"Test testnet URL configuration\"\"\"\n    testnet_client = AsyncClient(testnet=True, https_proxy=proxy)\n    try:\n        assert testnet_client.ws_api._url == testnet_client.WS_API_TESTNET_URL\n        order_book = await testnet_client.ws_get_order_book(symbol=\"BTCUSDT\")\n        assert_ob(order_book)\n    finally:\n        await testnet_client.close_connection()\n\n\n@pytest.mark.asyncio\nasync def test_message_handling(clientAsync):\n    \"\"\"Test message handling with various message types\"\"\"\n    try:\n        # Test valid message\n        future = asyncio.Future()\n        clientAsync.ws_api._responses[\"123\"] = future\n        valid_msg = {\"id\": \"123\", \"status\": 200, \"result\": {\"test\": \"data\"}}\n        clientAsync.ws_api._handle_message(json.dumps(valid_msg))\n        result = await clientAsync.ws_api._responses[\"123\"]\n        assert result == valid_msg\n    finally:\n        await clientAsync.close_connection()\n\n@pytest.mark.asyncio\nasync def test_message_handling_raise_exception(clientAsync):\n    try:\n        with pytest.raises(BinanceAPIException):\n            future = asyncio.Future()\n            clientAsync.ws_api._responses[\"123\"] = future\n            valid_msg = {\"id\": \"123\", \"status\": 400, \"error\": {\"code\": \"0\", \"msg\": \"error message\"}}\n            clientAsync.ws_api._handle_message(json.dumps(valid_msg))\n            await future\n    finally:\n        await clientAsync.close_connection()\n\n@pytest.mark.asyncio\nasync def test_message_handling_raise_exception_without_id(clientAsync):\n    try:\n        with pytest.raises(BinanceAPIException):\n            future = asyncio.Future()\n            clientAsync.ws_api._responses[\"123\"] = future\n            valid_msg = {\"id\": \"123\", \"status\": 400, \"error\": {\"code\": \"0\", \"msg\": \"error message\"}}\n            clientAsync.ws_api._handle_message(json.dumps(valid_msg))\n            await future\n    finally:\n        await clientAsync.close_connection()\n\n\n@pytest.mark.asyncio\nasync def test_message_handling_invalid_json(clientAsync):\n    try:\n        with pytest.raises(json.JSONDecodeError):\n            clientAsync.ws_api._handle_message(\"invalid json\")\n\n        with pytest.raises(json.JSONDecodeError):\n            clientAsync.ws_api._handle_message(\"invalid json\")\n    finally:\n        # Ensure cleanup\n        await clientAsync.close_connection()\n\n\n@pytest.mark.asyncio(scope=\"function\")\nasync def test_connection_failure(clientAsync):\n    \"\"\"Test handling of connection failures\"\"\"\n    # Set invalid URL\n    clientAsync.ws_api._url = \"wss://invalid.url\"\n\n    with pytest.raises(BinanceWebsocketUnableToConnect, match=\"Connection failed\"):\n        await clientAsync.ws_get_order_book(symbol=\"BTCUSDT\")\n\n\n@pytest.mark.asyncio(scope=\"function\")\nasync def test_cleanup_on_exit(clientAsync):\n    \"\"\"Test cleanup of resources on exit\"\"\"\n    # Create some pending requests\n    future = asyncio.Future()\n    clientAsync.ws_api._responses[\"test\"] = future\n\n    # Close connection\n    await clientAsync.close_connection()\n\n    # Check cleanup\n    assert \"test\" not in clientAsync.ws_api._responses\n    assert future.exception() is not None\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\n@pytest.mark.asyncio\nasync def test_ws_queue_overflow(clientAsync):\n    \"\"\"WebSocket API should not overflow queue\"\"\"\n    #\n    original_size = clientAsync.ws_api.max_queue_size\n    clientAsync.ws_api.max_queue_size = 1\n\n    try:\n        # Request multiple order books concurrently\n        symbols = [\"BTCUSDT\", \"ETHUSDT\", \"BNBUSDT\"]\n        tasks = [clientAsync.ws_get_order_book(symbol=symbol) for symbol in symbols]\n\n        # Execute all requests concurrently and wait for results\n        results = await asyncio.gather(*tasks, return_exceptions=True)\n\n        # Check that we got valid responses or expected overflow errors\n        valid_responses = [r for r in results if not isinstance(r, Exception)]\n        assert len(valid_responses) == len(symbols), \"Should get at least one valid response\"\n\n        for result in valid_responses:\n            assert_ob(result)\n\n    finally:\n        # Restore original queue size\n        clientAsync.ws_api.MAX_QUEUE_SIZE = original_size\n\n\n@pytest.mark.skipif(sys.version_info < (3, 8), reason=\"websockets_proxy Python 3.8+\")\n@pytest.mark.asyncio\nasync def test_ws_api_with_stream(clientAsync):\n    \"\"\"Test combining WebSocket API requests with stream listening\"\"\"\n    from binance import BinanceSocketManager\n\n    # Create socket manager and trade socket\n    bm = BinanceSocketManager(clientAsync)\n    ts = bm.trade_socket(\"BTCUSDT\")\n\n    async with ts:\n        # Make WS API request while stream is active\n        order_book = await clientAsync.ws_get_order_book(symbol=\"BTCUSDT\")\n        assert_ob(order_book)\n\n        # Verify we can still receive stream data\n        trade = await ts.recv()\n        assert \"s\" in trade  # Symbol\n        assert \"p\" in trade  # Price\n        assert \"q\" in trade  # Quantity\n"
  },
  {
    "path": "tests/utils.py",
    "content": "def test_multiple_objects(obj_list, assertion_func):\n    \"\"\"\n    Generic test function for validating multiple objects\n\n    Args:\n        client_response: List or iterator of objects to validate\n        assertion_func: Function to use for asserting each object's structure\n    \"\"\"\n    assert obj_list is not None, \"Response should not be None\"\n\n    # Handle both lists and iterators\n    objects = list(obj_list)\n\n    # Validate each object\n    for obj in objects:\n        assertion_func(obj)\n"
  },
  {
    "path": "tox.ini",
    "content": "[tox]\nenvlist = py38, py39, py310, py311, py312\n\n[testenv]\ndeps =\n  -rtest-requirements.txt\n  -rrequirements.txt\npassenv =\n    PROXY\n    TEST_TESTNET\n    TEST_API_KEY\n    TEST_API_SECRET\n    TEST_FUTURES_API_KEY\n    TEST_FUTURES_API_SECRET\ncommands = pytest -n 5 -v tests/ --timeout=90 --doctest-modules --cov binance --cov-report term-missing --cov-report xml --reruns 3 --reruns-delay 30\n\n[pep8]\nignore = E501\n"
  }
]