diff --git a/Endpoints.md b/Endpoints.md new file mode 100644 index 000000000..b5ff16188 --- /dev/null +++ b/Endpoints.md @@ -0,0 +1,778 @@ +> :warning: **Disclaimer**: + + > * 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. + + > * 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. + + > * This documentation only includes methods in client.py file. Websocket methods haven't (yet) been covered. + +### [Spot/Margin/Saving/Mining Endpoints](https://binance-docs.github.io/apidocs/spot/en/) +- *Wallet Endpoints* + - **GET /wapi/v3/systemStatus.html** (Fetch system status.) + ```python + client.get_system_status() + ``` + - **GET /sapi/v1/capital/config/getall (HMAC SHA256)** (Get information of coins (available for deposit and withdraw) for user.) + + > :warning: Not yet implemented + - **GET /sapi/v1/accountSnapshot (HMAC SHA256)** (Daily Account Snapshot (USER_DATA).) + + > :warning: Not yet implemented + - **POST /sapi/v1/account/disableFastWithdrawSwitch (HMAC SHA256)** (Disable Fast Withdraw Switch (USER_DATA).) + + > :warning: Not yet implemented + - **POST /sapi/v1/account/enableFastWithdrawSwitch (HMAC SHA256)** (Enable Fast Withdraw Switch (USER_DATA).) + + > :warning: Not yet implemented + - **POST /sapi/v1/capital/withdraw/apply (HMAC SHA256)** (Withdraw [SAPI]: Submit a withdraw request.) + + > :warning: Not yet implemented + - **POST /wapi/v3/withdraw.html (HMAC SHA256)** (Withdraw: Submit a withdraw request.) + ```python + client.withdraw(asset, + withdrawOrderId, + network, + address, + addressTag, + amount, + transactionFeeFlag, + name, + recvWindow) + ``` + - **GET /sapi/v1/capital/deposit/hisrec (HMAC SHA256)** (Fetch Deposit History(supporting network) (USER_DATA).) + + > :warning: Not yet implemented + - **GET /wapi/v3/depositHistory.html (HMAC SHA256)** (Fetch Deposit History (USER_DATA).) + ```python + client.get_deposit_history(asset, status, startTime, endTime, recvWindow) + ``` + - **GET /sapi/v1/capital/withdraw/history (HMAC SHA256)** (Fetch Withdraw History (supporting network) (USER_DATA).) + + > :warning: Not yet implemented + - **GET /wapi/v3/withdrawHistory.html (HMAC SHA256)** (Fetch Withdraw History (USER_DATA)) + ```python + client.get_withdraw_history(asset, status, startTime, endTime, recvWindow) + ``` + - **GET /sapi/v1/capital/deposit/address (HMAC SHA256)** (Fetch deposit address with network.) + + > :warning: Not yet implemented + - **GET /wapi/v3/depositAddress.html (HMAC SHA256)** (Fetch deposit address.) + ```python + client.get_deposit_address(asset, status, recvWindow) + ``` + - **GET /wapi/v3/accountStatus.html** (Fetch account status detail.) + ```python + client.get_account_status(recvWindow) + ``` + - **GET /wapi/v3/apiTradingStatus.html** (Fetch account api trading status detail.) + + > :warning: Not yet implemented + - **GET /wapi/v3/userAssetDribbletLog.html (HMAC SHA256)** (DustLog: Fetch small amounts of assets exchanged BNB records.) + ```python + client.get_dust_log(recvWindow) + ``` + - **Post /sapi/v1/asset/dust (HMAC SHA256)** (Dust Transfer: Convert dust assets to BNB.) + ```python + client.transfer_dust(asset, recvWindow) + ``` + - **Get /sapi/v1/asset/assetDividend (HMAC SHA256)** (Query asset dividend record.) + ```python + client.get_asset_dividend_history(asset, startTime, endTime, limit, recvWindow) + ``` + - **GET /wapi/v3/assetDetail.html (HMAC SHA256)** (Fetch details of assets supported on Binance.) + ```python + client.get_asset_details(recvWindow) + ``` + - **GET /wapi/v3/tradeFee.html (HMAC SHA256)** (Fetch trade fee, values in percentage.) + ```python + client.get_trade_fee(symbol, recvWindow) + ``` +- *Market Data Endpoints* + - **GET /api/v3/ping** (Test connectivity to the Rest API.) + ```python + client.ping() + ``` + - **GET /api/v3/time** (Test connectivity to the Rest API and get the current server time.) + ```python + client.get_server_time() + ``` + - **GET /api/v3/exchangeInfo** (Current exchange trading rules and symbol information.) + ```python + client.get_exchange_info() + ``` + - **GET /api/v3/depth** (Get the Order Book for the market.) + ```python + client.get_order_book(symbol, limit) + ``` + - **GET /api/v3/trades** (Get recent trades (up to last 500)) + ```python + client.get_recent_trades(symbol, limit) + ``` + - **GET /api/v3/historicalTrades** (Get older market trades.) + ```python + client.get_historical_trades(symbol, limit, fromId) + ``` + - **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.) + ```python + client.get_aggregate_trades(symbol, fromId, startTime, endTime, limit) + + # Wrapper function: Iterate over aggregate trade data from (start_time or last_id) the end of the history so far: + client.aggregate_trade_iter(symbol, start_str, last_id) + ``` + - **GET /api/v3/klines** (Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time.) + ```python + client.get_klines(symbol, interval, startTime, endTime, limit) + + # Wrapper function: Iterate over klines data from client.get_klines() + client.get_historical_klines(symbol, interval, start_str, end_str, limit) + ``` + - **GET /api/v3/avgPrice** (Current average price for a symbol.) + ```python + client.get_avg_price(symbol) + ``` + - **GET /api/v3/ticker/24hr** (24 hour rolling window price change statistics. **Careful** when accessing this with no symbol.) + ```python + client.get_ticker(symbol) + ``` + - **GET /api/v3/ticker/price** (Latest price for a symbol or symbols.) + ```python + client.get_symbol_ticker(symbol) + ``` + - **GET /api/v3/ticker/bookTicker** (Best price/qty on the order book for a symbol or symbols.) + ```python + client.get_orderbook_ticker(symbol) + ``` +- *Spot Account/Trade Endpoints* + - **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.) + ```python + client.create_test_order(symbol, + side, + type, + timeInForce, + quantity, + quoteOrderQty, + price, + newClientOrderId, + stopPrice, + icebergQty, + newOrderRespType, + recvWindow) + ``` + - **POST /api/v3/order (HMAC SHA256)** (Send in a new order.) + ```python + client.create_order(symbol, + side, + type, + timeInForce, + quantity, + quoteOrderQty, + price, + newClientOrderId, + stopPrice, + icebergQty, + newOrderRespType, + recvWindow) + + ## Wrapper functions: + # Send in a new limit order. + # Default parameters: timeInForce=Client.TIME_IN_FORCE_GTC, type=Client.ORDER_TYPE_LIMIT + client.order_limit(symbol, + side, + quantity, + price, + newClientOrderId, + stopPrice, + icebergQty, + newOrderRespType, + recvWindow) + + # Send in a new limit buy order. + # Default parameters: timeInForce=Client.TIME_IN_FORCE_GTC, type=Client.ORDER_TYPE_LIMIT, side=Client.SIDE_BUY + client.order_limit_buy(symbol, + quantity, + price, + newClientOrderId, + stopPrice, + icebergQty, + newOrderRespType, + recvWindow) + + # Send in a new limit sell order. + # Default parameters: timeInForce=Client.TIME_IN_FORCE_GTC, type=Client.ORDER_TYPE_LIMIT, side= Client.SIDE_SELL + client.order_limit_sell(symbol, + quantity, + price, + newClientOrderId, + stopPrice, + icebergQty, + newOrderRespType, + recvWindow) + + # Send in a new market order. + # Default parameters: type=Client.ORDER_TYPE_MARKET + client.order_market(symbol, + side, + quantity, + quoteOrderQty, + newClientOrderId, + newOrderRespType, + recvWindow) + + # Send in a new market buy order. + # Default parameters: type=Client.ORDER_TYPE_MARKET, side=Client.SIDE_BUY + client.order_market_buy(symbol, + quantity, + quoteOrderQty, + newClientOrderId, + newOrderRespType, + recvWindow) + + # Send in a new market sell order. + # Default parameters: type=Client.ORDER_TYPE_MARKET, side=Client.SIDE_SELL + client.order_market_sell(symbol, + quantity, + quoteOrderQty, + newClientOrderId, + newOrderRespType, + recvWindow) + ``` + - **DELETE /api/v3/order (HMAC SHA256)** (Cancel an active order.) + ```python + client.cancel_order(symbol, orderId, origClientOrderId, newClientOrderId, recvWindow) + ``` + - **DELETE api/v3/openOrders** (Cancels all active orders on a symbol. This includes OCO orders.) + + > :warning: Not yet implemented + - **GET /api/v3/order (HMAC SHA256)** (Check an order's status.) + ```python + client.get_order(symbol, orderId, origClientOrderId, recvWindow) + ``` + - **GET /api/v3/openOrders (HMAC SHA256)** (Get all open orders on a symbol. **Careful** when accessing this with no symbol.) + ```python + client.get_open_orders(symbol, recvWindow) + ``` + - **GET /api/v3/allOrders (HMAC SHA256)** (Get all account orders; active, canceled, or filled.) + ```python + client.get_all_orders(symbol, orderId, startTime, endTime, limit, recvWindow) + ``` + - **POST /api/v3/order/oco (HMAC SHA256)** (Send in a new OCO order) + ```python + client.create_oco_order(symbol, + listClientOrderId, + side, + quantity, + limitClientOrderId, + price, + limitIcebergQty, + stopClientOrderId, + stopPrice, + stopLimitPrice, + stopIcebergQty, + stopLimitTimeInForce, + newOrderRespType, + recvWindow) + + ## Wrapper Functions: + + # Send in a new OCO buy order. Default parameter: type=Client.SIDE_BUY + client.order_oco_buy(symbol, + listClientOrderId, + quantity, + limitClientOrderId, + price, + limitIcebergQty, + stopClientOrderId, + stopPrice, + stopLimitPrice, + stopIcebergQty, + stopLimitTimeInForce, + newOrderRespType, + recvWindow) + + # Send in a new OCO sell order. Default parameter: type=Client.SIDE_SELL + client.order_oco_sell(symbol, + listClientOrderId, + quantity, + limitClientOrderId, + price, + limitIcebergQty, + stopClientOrderId, + stopPrice, + stopLimitPrice, + stopIcebergQty, + stopLimitTimeInForce, + newOrderRespType, + recvWindow) + ``` + - **DELETE /api/v3/orderList (HMAC SHA256)** (Cancel OCO: Cancel an entire Order List) + + > :warning: Not yet implemented + - **GET /api/v3/orderList (HMAC SHA256)** (Query OCO: Retrieves a specific OCO based on provided optional parameters) + + > :warning: Not yet implemented + - **GET /api/v3/allOrderList (HMAC SHA256)** (Retrieves all OCO based on provided optional parameters) + + > :warning: Not yet implemented + - **GET /api/v3/openOrderList (HMAC SHA256)** (Query Open OCO (USER_DATA)) + + > :warning: Not yet implemented + - **GET /api/v3/account (HMAC SHA256)** (Get current account information.) + ```python + client.get_account(recvWindow) + ``` + - **GET /api/v3/myTrades (HMAC SHA256)** (Get trades for a specific account and symbol.) + ```python + client.get_my_trades(symbol, startTime, endTime, fromId, limit, recvWindow) + ``` +- *Margin Account/Trade* + - **POST /sapi/v1/margin/transfer (HMAC SHA256)** (Execute transfer between margin account and spot account(MARGIN).) + ```python + client.transfer_margin_to_spot(asset, amount, recvWindow) + client.transfer_spot_to_margin(asset, amount, recvWindow) + ``` + - **POST /sapi/v1/margin/loan (HMAC SHA256)** (Apply for a loan(MARGIN).) + ```python + client.create_margin_loan(asset, isIsolated, symbol, amount, recvWindow) + ``` + - **POST /sapi/v1/margin/repay (HMAC SHA256)** (Repay loan for margin account (MARGIN).) + ```python + client.repay_margin_loan(asset, isIsolated, symbol, amount, recvWindow) + ``` + - **GET /sapi/v1/margin/asset** (Query Margin Asset (MARKET_DATA).) + ```python + client.get_margin_asset(asset) + ``` + - **GET /sapi/v1/margin/pair** (Query Cross Margin Pair (MARKET_DATA).) + ```python + client.get_margin_symbol(symbol) + ``` + - **GET /sapi/v1/margin/allAssets** (Get All Cross Margin Assets (MARKET_DATA).) + + > :warning: Not yet implemented + - **GET /sapi/v1/margin/allPairs** (Get All Cross Margin Pairs (MARKET_DATA).) + + > :warning: Not yet implemented + - **GET /sapi/v1/margin/priceIndex** (Query Margin PriceIndex (MARKET_DATA).) + ```python + client.get_margin_price_index(symbol) + ``` + - **POST /sapi/v1/margin/order (HMAC SHA256)** (Post a new order for margin account.) + ```python + client.create_margin_order(symbol, + isIsolated, + side, + type, + quantity, + price, + stopPrice, + newClientOrderId, + icebergQty, + newOrderRespType, + sideEffectType, + timeInForce, + recvWindow) + ``` + - **DELETE /sapi/v1/margin/order (HMAC SHA256)** (Cancel an active order for margin account.) + ```python + client.cancel_margin_order(symbol, + isIsolated, + orderId, + origClientOrderId, + newClientOrderId, + recvWindow) + ``` + - **GET /sapi/v1/margin/transfer (HMAC SHA256)** (Get Cross Margin Transfer History (USER_DATA).) + + > :warning: Not yet implemented + - **GET /sapi/v1/margin/loan (HMAC SHA256)** (Query Loan Record (USER_DATA).) + ```python + client.get_margin_loan_details(asset, isolatedSymbol, txId, startTime, endTime, current, size, recvWindow) + ``` + - **GET /sapi/v1/margin/repay (HMAC SHA256)** (Query repay record (USER_DATA).) + ```python + client.get_margin_repay_details(asset, isolatedSymbol, txId, startTime, endTime, current, size, recvWindow) + ``` + - **GET /sapi/v1/margin/interestHistory (HMAC SHA256)** (Get Interest History (USER_DATA).) + + > :warning: Not yet implemented + - **GET /sapi/v1/margin/forceLiquidationRec (HMAC SHA256)** (Get Force Liquidation Record (USER_DATA).) + + > :warning: Not yet implemented + - **GET /sapi/v1/margin/account (HMAC SHA256)** (Query Cross Margin Account Details (USER_DATA).) + ```python + client.get_margin_account(recvWindow) + ``` + - **GET /sapi/v1/margin/order (HMAC SHA256)** (Query Margin Account's Order (USER_DATA).) + ```python + client.get_margin_order(symbol, isIsolated, orderId, origClientOrderId, recvWindow) + ``` + - **GET /sapi/v1/margin/openOrders (HMAC SHA256)** (Query Margin Account's Open Order (USER_DATA).) + ```python + client.get_open_margin_orders(symbol, isIsolated, recvWindow) + ``` + - **GET /sapi/v1/margin/allOrders (HMAC SHA256)** (Query Margin Account's All Order (USER_DATA).) + ```python + client.get_all_margin_orders(symbol, isIsolated, orderId, startTime, endTime, limit, recvWindow) + ``` + - **GET /sapi/v1/margin/myTrades (HMAC SHA256)** (Query Margin Account's Trade List (USER_DATA).) + ```python + client.get_margin_trades(symbol, isIsolated, startTime, endTime, fromId, limit, recvWindow) + ``` + - **GET /sapi/v1/margin/maxBorrowable (HMAC SHA256)** (Query Max Borrow amount for an asset (USER_DATA).) + ```python + client.get_max_margin_loan(asset, isolatedSymbol, recvWindow) + ``` + - **GET /sapi/v1/margin/maxTransferable (HMAC SHA256)** (Query Max Transfer-Out Amount (USER_DATA).) + ```python + client.get_max_margin_transfer(asset, isolatedSymbol, recvWindow) + ``` + - **POST /sapi/v1/margin/isolated/create (HMAC SHA256)** (Create Isolated Margin Account (MARGIN).) + ```python + client.create_isolated_margin_account(base, quote, recvWindow) + ``` + - **POST /sapi/v1/margin/isolated/transfer (HMAC SHA256)** (Isolated Margin Account Transfer (MARGIN).) + ```python + client.transfer_spot_to_isolated_margin(asset, symbol, amount, recvWindow) + client.transfer_isolated_margin_to_spot(asset, symbol, amount, recvWindow) + ``` + - **GET /sapi/v1/margin/isolated/transfer (HMAC SHA256)** (Get Isolated Margin Transfer History (USER_DATA).) + + > :warning: Not yet implemented + - **GET /sapi/v1/margin/isolated/account (HMAC SHA256)** (Query Isolated Margin Account Info (USER_DATA).) + + > :warning: Not yet implemented + - **GET /sapi/v1/margin/isolated/pair (HMAC SHA256)** (Query Isolated Margin Symbol (USER_DATA).) + ```python + client.get_isolated_margin_symbol(symbol, recvWindow) + ``` + - **GET /sapi/v1/margin/isolated/allPairs (HMAC SHA256)** (Get All Isolated Margin Symbol (USER_DATA).) + ```python + client.get_all_isolated_margin_symbols(recvWindow) + ``` +- *User Data Streams* + - **POST /api/v3/userDataStream** (Create a ListenKey (Spot) (USER_STREAM): Start a new user data stream.) + ```python + client.stream_get_listen_key() + ``` + - **PUT /api/v3/userDataStream** (Ping/Keep-alive a ListenKey (Spot) (USER_STREAM).) + ```python + client.stream_keepalive(listenKey) + ``` + - **DELETE /api/v3/userDataStream** (Close a ListenKey (Spot) (USER_STREAM).) + ```python + client.stream_close(listenKey) + ``` + - **POST /sapi/v1/userDataStream** (Create a ListenKey (Margin).) + ```python + client.margin_stream_get_listen_key() + ``` + - **PUT /sapi/v1/userDataStream** (Ping/Keep-alive a ListenKey (Margin).) + ```python + client.margin_stream_keepalive(listenKey) + ``` + - **DELETE /sapi/v1/userDataStream** (Close a ListenKey (Margin).) + ```python + client.margin_stream_close(listenKey) + ``` + - **POST /sapi/v1/userDataStream/isolated** (Create a ListenKey (Isolated).) + ```python + client.isolated_margin_stream_get_listen_key(symbol) + ``` + - **PUT /sapi/v1/userDataStream/isolated** (Ping/Keep-alive a ListenKey (Isolated).) + ```python + client.isolated_margin_stream_keepalive(symbol, listenKey) + ``` + - **DELETE /sapi/v1/userDataStream/isolated** (Close a ListenKey (Isolated).) + ```python + client.isolated_margin_stream_close(symbol, listenKey) + ``` +- *Savings Endpoints* + - **GET /sapi/v1/lending/daily/product/list (HMAC SHA256)** (Get Flexible Product List (USER_DATA).) + ```python + client.get_lending_product_list(status, featured, recvWindow) + ``` + - **GET /sapi/v1/lending/daily/userLeftQuota (HMAC SHA256)** (Get Left Daily Purchase Quota of Flexible Product (USER_DATA).) + ```python + client.get_lending_daily_quota_left(productId, recvWindow) + ``` + - **POST /sapi/v1/lending/daily/purchase (HMAC SHA256)** (Purchase Flexible Product (USER_DATA).) + ```python + client.purchase_lending_product(productId, amount, recvWindow) + ``` + - **GET /sapi/v1/lending/daily/userRedemptionQuota (HMAC SHA256)** (Get Left Daily Redemption Quota of Flexible Product (USER_DATA).) + ```python + client.get_lending_daily_redemption_quota(productId, type, recvWindow) + ``` + - **POST /sapi/v1/lending/daily/redeem (HMAC SHA256)** (Redeem Flexible Product (USER_DATA).) + ```python + client.redeem_lending_product(productId, amount, type, recvWindow) + ``` + - **GET /sapi/v1/lending/daily/token/position (HMAC SHA256)** (Get Flexible Product Position (USER_DATA).) + ```python + client.get_lending_position(asset, recvWindow) + ``` + - **GET /sapi/v1/lending/project/list (HMAC SHA256)** (Get Fixed and Activity Project List (USER_DATA).) + + > :warning: Not yet implemented + - **POST /sapi/v1/lending/customizedFixed/purchase (HMAC SHA256)** (Purchase Fixed/Activity Project (USER_DATA).) + + > :warning: Not yet implemented + - **GET /sapi/v1/lending/project/position/list (HMAC SHA256)** (Get Fixed/Activity Project Position (USER_DATA).) + + > :warning: Not yet implemented + - **GET /sapi/v1/lending/union/account (HMAC SHA256)** (Lending Account (USER_DATA).) + ```python + client.get_lending_account(recvWindow) + ``` + - **GET /sapi/v1/lending/union/purchaseRecord (HMAC SHA256)** (Get Purchase Record (USER_DATA).) + ```python + client.get_lending_purchase_history(lendingType, asset, startTime, endTime, current, size, recvWindow) + ``` + - **GET /sapi/v1/lending/union/redemptionRecord (HMAC SHA256)** (Get Redemption Record (USER_DATA).) + ```python + client.get_lending_redemption_history(lendingType, asset, startTime, endTime, current, size, recvWindow) + ``` + - **GET /sapi/v1/lending/union/interestHistory (HMAC SHA256)** (Get Interest History (USER_DATA).) + ```python + client.get_lending_interest_history(lendingType, asset, startTime, endTime, current, size, recvWindow) + ``` + - **POST /sapi/v1/lending/positionChanged (HMAC SHA256)** (Change Fixed/Activity Position to Daily Position (USER_DATA).) + + > :warning: Not yet implemented +- *Mining Endpoints* + > :warning: Not yet implemented +- *Sub-Account Endpoints* + - **GET /wapi/v3/sub-account/list.html (HMAC SHA256)** (Query Sub-account List (For Master Account).) + ```python + client.get_sub_account_list(email, startTime, endTime, page, limit, recvWindow) + ``` + - **GET /wapi/v3/sub-account/transfer/history.html (HMAC SHA256)** (Query Sub-account Spot Asset Transfer History (For Master Account).) + ```python + client.get_sub_account_transfer_history(email, startTime, endTime, page, limit, recvWindow) + ``` + - **POST /wapi/v3/sub-account/transfer.html (HMAC SHA256)** (Execute Sub-account Spot Asset Transfer (For Master Account).) + ```python + client.create_sub_account_transfer(fromEmail, toEmail, asset, amount, recvWindow) + ``` + - **GET /wapi/v3/sub-account/assets.html (HMAC SHA256)** (Query Sub-account Assets (For Master Account).) + ```python + client.get_sub_account_assets(email, recvWindow) + ``` + > :warning: The rest of methods for Sub-Account Endpoints are not yet implemented +- *BLVT Endpoints* + > :warning: Not yet implemented +- *BSwap Endpoints* + > :warning: Not yet implemented +### [USDT-M Futures](https://binance-docs.github.io/apidocs/futures/en/) +- *Market Data Endpoints* + - **GET /fapi/v1/ping** (Test connectivity to the Rest API.) + ```python + client.futures_ping() + ``` + - **GET /fapi/v1/time** (Test connectivity to the Rest API and get the current server time.) + ```python + client.futures_time() + ``` + - **GET /fapi/v1/exchangeInfo** (Current exchange trading rules and symbol information.) + ```python + client.futures_exchange_info() + ``` + - **GET /fapi/v1/depth** (Get the Order Book for the market.) + ```python + client.futures_order_book(symbol, limit) + ``` + - **GET /fapi/v1/trades** (Get recent trades.) + ```python + client.futures_recent_trades(symbol, limit) + ``` + - **GET /fapi/v1/historicalTrades** (Get older market historical trades (MARKET_DATA).) + ```python + client.futures_historical_trades(symbol, limit, fromId) + ``` + - **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.) + ```python + client.futures_aggregate_trades(symbol, fromId, startTime, endTime, limit) + ``` + - **GET /fapi/v1/klines** (Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time.) + ```python + client.futures_klines(symbol, interval, startTime, endTime, limit) + ``` + - **GET /fapi/v1/premiumIndex** (Get Mark Price and Funding Rate.) + ```python + client.futures_mark_price(symbol) + ``` + - **GET /fapi/v1/fundingRate** (Get Funding Rate History.) + ```python + client.futures_funding_rate(symbol, startTime, endTime, limit) + ``` + - **GET /fapi/v1/ticker/24hr** (24 hour rolling window price change statistics. **Careful** when accessing this with no symbol.) + ```python + client.futures_ticker(symbol) + ``` + - **GET /fapi/v1/ticker/price** (Latest price for a symbol or symbols.) + ```python + client.futures_symbol_ticker(symbol) + ``` + - **GET /fapi/v1/ticker/bookTicker** (Best price/qty on the order book for a symbol or symbols.) + ```python + client.futures_orderbook_ticker(symbol) + ``` + - **GET /fapi/v1/allForceOrders** (Get all Liquidation Orders.) + > :warning: Probably broken, python code below is implemented on v1/ticker/allForceOrders endpoint. + ```python + client.futures_liquidation_orders(symbol, startTime, endTime, limit) + ``` + - **GET /fapi/v1/openInterest** (Get present open interest of a specific symbol.) + > :warning: Probably broken, python code below is implemented on v1/ticker/openInterest endpoint. + ```python + client.futures_open_interest(symbol) + ``` + - **GET /futures/data/openInterestHist** (Open Interest Statistics.) + + > :warning: Not yet implemented + - **GET /futures/data/topLongShortAccountRatio** (Top Trader Long/Short Ratio (Accounts) (MARKET_DATA).) + + > :warning: Not yet implemented + - **GET /futures/data/topLongShortPositionRatio** (Top Trader Long/Short Ratio (Positions).) + + > :warning: Not yet implemented + - **GET /futures/data/globalLongShortAccountRatio** (Long/Short Ratio.) + + > :warning: Not yet implemented + - **GET /futures/data/takerlongshortRatio** (Taker Buy/Sell Volume.) + + > :warning: Not yet implemented + - **GET /fapi/v1/lvtKlines** (Historical BLVT NAV Kline/Candlestick.) + + > :warning: Not yet implemented + - **GET /fapi/v1/indexInfo** (Composite Index Symbol Information.) + + > :warning: Not yet implemented +- *Account/trades Endpoints* + - **POST /sapi/v1/futures/transfer (HMAC SHA256)** (New Future Account Transfer (FUTURES): Execute transfer between spot account and futures account.) + + > :warning: Not yet implemented + - **GET /sapi/v1/futures/transfer (HMAC SHA256)** (Get Future Account Transaction History List (USER_DATA).) + ```python + client.transfer_history(asset, startTime, endTime, current, size, recvWindow) + ``` + - **POST /fapi/v1/positionSide/dual (HMAC SHA256)** (Change user's position mode (Hedge Mode or One-way Mode ) on _**EVERY symbol**_.) + + > :warning: Not yet implemented + - **GET /fapi/v1/positionSide/dual (HMAC SHA256)** (Get user's position mode (Hedge Mode or One-way Mode ) on _**EVERY symbol**_.) + + > :warning: Not yet implemented + - **POST /fapi/v1/order (HMAC SHA256)** (Send in a new order (TRADE).) + ```python + client.futures_create_order(symbol, + side, + positionSide, + type, + timeInForce, + quantity, + reduceOnly, + price, + newClientOrderId, + stopPrice, + closePosition, + activationPrice, + callbackRate, + workingType, + priceProtect, + newOrderRespType, + recvWindow) + ``` + - **POST /fapi/v1/batchOrders (HMAC SHA256)** (Place Multiple Orders (TRADE).) + + > :warning: Not yet implemented + - **GET /fapi/v1/order (HMAC SHA256)** (Query Order (USER_DATA): Check an order's status.) + ```python + client.futures_get_order(symbol, orderId, origClientOrderId, recvWindow) + ``` + - **DELETE /fapi/v1/order (HMAC SHA256)** (Cancel an active order (TRADE).) + ```python + client.futures_cancel_order(symbol, orderId, origClientOrderId, recvWindow) + ``` + - **DELETE /fapi/v1/allOpenOrders (HMAC SHA256)** (Cancel All Open Orders (TRADE).) + ```python + client.futures_cancel_all_open_orders(symbol, recvWindow) + ``` + - **DELETE /fapi/v1/batchOrders (HMAC SHA256)** (Cancel Multiple Orders (TRADE).) + ```python + client.futures_cancel_orders(symbol, orderIdList, origClientOrderIdList, recvWindow) + ``` + - **POST /fapi/v1/countdownCancelAll (HMAC SHA256)** (Cancel all open orders of the specified symbol at the end of the specified countdown (TRADE).) + + > :warning: Not yet implemented + - **GET /fapi/v1/openOrder (HMAC SHA256)** (Query Current Open Order (USER_DATA).) + + > :warning: Not yet implemented + - **GET /fapi/v1/openOrders (HMAC SHA256)** (Get all open orders on a symbol. **Careful** when accessing this with no symbol (USER_DATA).) + ```python + client.futures_get_open_orders(symbol, recvWindow) + ``` + - **GET /fapi/v1/allOrders (HMAC SHA256)** (Get all account orders; active, canceled, or filled (USER_DATA).) + ```python + client.futures_get_all_orders(symbol, orderId, startTime, endTime, limit, recvWindow) + ``` + - **GET /fapi/v2/balance (HMAC SHA256)** (Futures Account Balance V2 (USER_DATA).) + > :warning: Probably broken, python code below is implemented on v1 endpoint. + ```python + client.futures_account_balance(recvWindow) + ``` + - **GET /fapi/v2/account (HMAC SHA256)** (Account Information V2: Get current account information (USER_DATA).) + > :warning: Probably broken, python code below is implemented on v1 endpoint. + ```python + client.futures_account(recvWindow) + ``` + - **POST /fapi/v1/leverage (HMAC SHA256)** (Change user's initial leverage of specific symbol market (TRADE).) + ```python + client.futures_change_leverage(symbol, leverage, recvWindow) + ``` + - **POST /fapi/v1/marginType (HMAC SHA256)** (Change the margin type for a symbol (TRADE).) + ```python + client.futures_change_margin_type(symbol, marginType, recvWindow) + ``` + - **POST /fapi/v1/positionMargin (HMAC SHA256)** (Modify Isolated Position Margin (TRADE).) + ```python + client.futures_change_position_margin(symbol, positionSide, amount, type, recvWindow) + ``` + - **GET /fapi/v1/positionMargin/history (HMAC SHA256)** (Get Position Margin Change History (TRADE).) + ```python + client.futures_position_margin_history(symbol, type, startTime, endTime, limit, recvWindow) + ``` + - **GET /fapi/v2/positionRisk (HMAC SHA256)** (Position Information V2: Get current position information (USER_DATA).) + > :warning: Probably broken, python code below is implemented on v1 endpoint. + ```python + client.futures_position_information(symbol, recvWindow) + ``` + - **GET /fapi/v1/userTrades (HMAC SHA256)** (Account Trade List: Get trades for a specific account and symbol (USER_DATA).) + ```python + client.futures_account_trades(symbol, startTime, endTime, fromId, limit, recvWindow) + ``` + - **GET /fapi/v1/income (HMAC SHA256)** (Get Income History (USER_DATA).) + ```python + client.futures_income_history(symbol, incomeType, startTime, endTime, limit, recvWindow) + ``` + - **GET /fapi/v1/leverageBracket** (Notional and Leverage Brackets (USER_DATA).) + > :warning: Probably broken, python code below is implemented on ticker/leverageBracket endpoint. + ```python + client.futures_leverage_bracket(symbol, recvWindow) + ``` + - **GET /fapi/v1/adlQuantile** (Position ADL Quantile Estimation (USER_DATA).) + + > :warning: Not yet implemented + - **GET /fapi/v1/forceOrders** (User's Force Orders (USER_DATA).) + + > :warning: Not yet implemented + - **GET /fapi/v1/apiTradingStatus** (User API Trading Quantitative Rules Indicators (USER_DATA).) + + > :warning: Not yet implemented +- *User Data Streams* + > :warning: Not yet implemented +### [COIN-M Futures](https://binance-docs.github.io/apidocs/delivery/en/) +> :warning: Not yet implemented +### [USDT-M Futures testnet](https://binance-docs.github.io/apidocs/testnet/en/) +> :warning: Not yet implemented +### [COIN-M Futures testnet](https://binance-docs.github.io/apidocs/delivery_testnet/en/) +> :warning: Not yet implemented diff --git a/README.rst b/README.rst index 26308e070..00521b007 100644 --- a/README.rst +++ b/README.rst @@ -1,14 +1,11 @@ ================================ -Welcome to python-binance v0.7.5 +Welcome to python-binance v0.7.8 ================================ Note ---- -I am working on a python3 version with async support to remove legacy dependencies and their related issues. - -I would appreciate if you could try out the `feature/asyncio `_ branch and give your feedback. - +this library is not under active development by sammchardy. however, the community has been actively contributing lots of PRs. If you find missing features please submit a PR. please keep PRs small and non-breaking. .. image:: https://img.shields.io/pypi/v/python-binance.svg :target: https://pypi.python.org/pypi/python-binance @@ -28,7 +25,7 @@ I would appreciate if you could try out the `feature/asyncio `_. I am in no way affiliated with Binance, use at your own risk. +This is an unofficial Python wrapper for the `Binance exchange REST API v3 `_. I am in no way affiliated with Binance, use at your own risk. If you came here looking for the `Binance exchange `_ to purchase cryptocurrencies, then `go here `_. If you want to automate interactions with Binance stick around. diff --git a/binance/client.py b/binance/client.py index 432a53a30..734adeea5 100644 --- a/binance/client.py +++ b/binance/client.py @@ -257,8 +257,7 @@ def get_products(self): :raises: BinanceRequestException, BinanceAPIException """ - - products = self._request_website('get', 'exchange/public/product') + products = self._request_website('get', 'exchange-api/v1/public/asset-service/product/get-products') return products def get_exchange_info(self): @@ -323,7 +322,7 @@ def get_exchange_info(self): """ - return self._get('exchangeInfo') + return self._get('exchangeInfo', version=self.PRIVATE_API_VERSION) def get_symbol_info(self, symbol): """Return information about a symbol @@ -366,7 +365,7 @@ def get_symbol_info(self, symbol): """ - res = self._get('exchangeInfo') + res = self._get('exchangeInfo', version=self.PRIVATE_API_VERSION) for item in res['symbols']: if item['symbol'] == symbol.upper(): @@ -379,7 +378,7 @@ def get_symbol_info(self, symbol): def ping(self): """Test connectivity to the Rest API. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#test-connectivity + https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#test-connectivity :returns: Empty array @@ -390,12 +389,12 @@ def ping(self): :raises: BinanceRequestException, BinanceAPIException """ - return self._get('ping') + return self._get('ping', version=self.PRIVATE_API_VERSION) def get_server_time(self): """Test connectivity to the Rest API and get the current server time. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#check-server-time + https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#check-server-time :returns: Current server time @@ -408,7 +407,7 @@ def get_server_time(self): :raises: BinanceRequestException, BinanceAPIException """ - return self._get('time') + return self._get('time', version=self.PRIVATE_API_VERSION) # Market Data Endpoints @@ -435,7 +434,7 @@ def get_all_tickers(self): :raises: BinanceRequestException, BinanceAPIException """ - return self._get('ticker/allPrices') + return self._get('ticker/price', version=self.PRIVATE_API_VERSION) def get_orderbook_tickers(self): """Best price/qty on the order book for all symbols. @@ -466,12 +465,12 @@ def get_orderbook_tickers(self): :raises: BinanceRequestException, BinanceAPIException """ - return self._get('ticker/allBookTickers') + return self._get('ticker/bookTicker', version=self.PRIVATE_API_VERSION) def get_order_book(self, **params): """Get the Order Book for the market - https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#order-book + https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#order-book :param symbol: required :type symbol: str @@ -503,12 +502,12 @@ def get_order_book(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._get('depth', data=params) + return self._get('depth', data=params, version=self.PRIVATE_API_VERSION) def get_recent_trades(self, **params): """Get recent trades (up to last 500). - https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#recent-trades-list + https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#recent-trades-list :param symbol: required :type symbol: str @@ -538,7 +537,7 @@ def get_recent_trades(self, **params): def get_historical_trades(self, **params): """Get older trades. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#recent-trades-list + https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#recent-trades-list :param symbol: required :type symbol: str @@ -565,13 +564,13 @@ def get_historical_trades(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._get('historicalTrades', data=params) + return self._get('historicalTrades', data=params, version=self.PRIVATE_API_VERSION) def get_aggregate_trades(self, **params): """Get compressed, aggregate trades. Trades that fill at the time, from the same order, with the same price will have the quantity aggregated. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#compressedaggregate-trades-list + https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#compressedaggregate-trades-list :param symbol: required :type symbol: str @@ -604,7 +603,7 @@ def get_aggregate_trades(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._get('aggTrades', data=params) + return self._get('aggTrades', data=params, version=self.PRIVATE_API_VERSION) def aggregate_trade_iter(self, symbol, start_str=None, last_id=None): """Iterate over aggregate trade data from (start_time or last_id) to @@ -630,7 +629,7 @@ def aggregate_trade_iter(self, symbol, start_str=None, last_id=None): return the first trade occurring later than this time. :type start_str: str|int :param last_id: aggregate trade ID of the last known aggregate trade. - Not a regular trade ID. See https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#compressedaggregate-trades-list. + Not a regular trade ID. See https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#compressedaggregate-trades-list. :returns: an iterator of JSON objects, one per trade. The format of each object is identical to Client.aggregate_trades(). @@ -695,7 +694,7 @@ def aggregate_trade_iter(self, symbol, start_str=None, last_id=None): def get_klines(self, **params): """Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#klinecandlestick-data + https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#klinecandlestick-data :param symbol: required :type symbol: str @@ -732,7 +731,7 @@ def get_klines(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._get('klines', data=params) + return self._get('klines', data=params, version=self.PRIVATE_API_VERSION) def _get_earliest_valid_timestamp(self, symbol, interval): """Get earliest valid open timestamp from Binance @@ -921,7 +920,7 @@ def get_historical_klines_generator(self, symbol, interval, start_str, end_str=N def get_avg_price(self, **params): """Current average price for a symbol. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#current-average-price + https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#current-average-price :param symbol: :type symbol: str @@ -940,7 +939,7 @@ def get_avg_price(self, **params): def get_ticker(self, **params): """24 hour price change statistics. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#24hr-ticker-price-change-statistics + https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#24hr-ticker-price-change-statistics :param symbol: :type symbol: str @@ -996,12 +995,12 @@ def get_ticker(self, **params): :raises: BinanceRequestException, BinanceAPIException """ - return self._get('ticker/24hr', data=params) + return self._get('ticker/24hr', data=params, version=self.PRIVATE_API_VERSION) def get_symbol_ticker(self, **params): """Latest price for a symbol or symbols. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#24hr-ticker-price-change-statistics + https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#24hr-ticker-price-change-statistics :param symbol: :type symbol: str @@ -1038,7 +1037,7 @@ def get_symbol_ticker(self, **params): def get_orderbook_ticker(self, **params): """Latest price for a symbol or symbols. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#symbol-order-book-ticker + https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#symbol-order-book-ticker :param symbol: :type symbol: str @@ -1088,7 +1087,7 @@ def create_order(self, **params): Any order with an icebergQty MUST have timeInForce set to GTC. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#new-order--trade + https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#new-order--trade :param symbol: required :type symbol: str @@ -1397,7 +1396,7 @@ def order_market_sell(self, **params): def create_oco_order(self, **params): """Send in a new OCO order - https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#new-oco-trade + https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#new-oco-trade :param symbol: required :type symbol: str @@ -1543,7 +1542,7 @@ def order_oco_sell(self, **params): def create_test_order(self, **params): """Test new order creation and signature/recvWindow long. Creates and validates a new order but does not send it into the matching engine. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#test-new-order-trade + https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#test-new-order-trade :param symbol: required :type symbol: str @@ -1581,7 +1580,7 @@ def create_test_order(self, **params): def get_order(self, **params): """Check an order's status. Either orderId or origClientOrderId must be sent. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#query-order-user_data + https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#query-order-user_data :param symbol: required :type symbol: str @@ -1620,7 +1619,7 @@ def get_order(self, **params): def get_all_orders(self, **params): """Get all account orders; active, canceled, or filled. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#all-orders-user_data + https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#all-orders-user_data :param symbol: required :type symbol: str @@ -1661,7 +1660,7 @@ def get_all_orders(self, **params): def cancel_order(self, **params): """Cancel an active order. Either orderId or origClientOrderId must be sent. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#cancel-order-trade + https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#cancel-order-trade :param symbol: required :type symbol: str @@ -1693,7 +1692,7 @@ def cancel_order(self, **params): def get_open_orders(self, **params): """Get all open orders on a symbol. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#current-open-orders-user_data + https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#current-open-orders-user_data :param symbol: optional :type symbol: str @@ -1731,7 +1730,7 @@ def get_open_orders(self, **params): def get_account(self, **params): """Get current account information. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#account-information-user_data + https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#account-information-user_data :param recvWindow: the number of milliseconds the request is valid for :type recvWindow: int @@ -1770,7 +1769,7 @@ def get_account(self, **params): def get_asset_balance(self, asset, **params): """Get current asset balance. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#account-information-user_data + https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#account-information-user_data :param asset: required :type asset: str @@ -1801,7 +1800,7 @@ def get_asset_balance(self, asset, **params): def get_my_trades(self, **params): """Get trades for a specific symbol. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#account-trade-list-user_data + https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#account-trade-list-user_data :param symbol: required :type symbol: str @@ -1838,7 +1837,7 @@ def get_my_trades(self, **params): def get_system_status(self): """Get system status detail. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/wapi-api.md#system-status-system + https://binance-docs.github.io/apidocs/spot/en/#system-status-system :returns: API response @@ -1857,7 +1856,7 @@ def get_system_status(self): def get_account_status(self, **params): """Get account status detail. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/wapi-api.md#account-status-user_data + https://binance-docs.github.io/apidocs/spot/en/#account-status-user_data :param recvWindow: the number of milliseconds the request is valid for :type recvWindow: int @@ -1885,7 +1884,7 @@ def get_account_status(self, **params): def get_dust_log(self, **params): """Get log of small amounts exchanged for BNB. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/wapi-api.md#dustlog-user_data + https://binance-docs.github.io/apidocs/spot/en/#dustlog-user_data :param recvWindow: the number of milliseconds the request is valid for :type recvWindow: int @@ -1966,7 +1965,7 @@ def get_dust_log(self, **params): def transfer_dust(self, **params): """Convert dust assets to BNB. - https://github.com/binance-exchange/binance-official-api-docs/blob/9dbe0e961b80557bb19708a707c7fad08842b28e/wapi-api.md#dust-transfer-user_data + https://binance-docs.github.io/apidocs/spot/en/#dust-transfer-user_data :param asset: The asset being converted. e.g: 'ONE' :type asset: str @@ -2004,7 +2003,7 @@ def transfer_dust(self, **params): def get_asset_dividend_history(self, **params): """Query asset dividend record. - https://github.com/binance-exchange/binance-official-api-docs/blob/9dbe0e961b80557bb19708a707c7fad08842b28e/wapi-api.md#asset-dividend-record-user_data + https://binance-docs.github.io/apidocs/spot/en/#asset-dividend-record-user_data :param asset: optional :type asset: str @@ -2051,7 +2050,7 @@ def get_asset_dividend_history(self, **params): def get_trade_fee(self, **params): """Get trade fee. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/wapi-api.md#trade-fee-user_data + https://binance-docs.github.io/apidocs/spot/en/#trade-fee-user_data :param symbol: optional :type symbol: str @@ -2088,7 +2087,7 @@ def get_trade_fee(self, **params): def get_asset_details(self, **params): """Fetch details on assets. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/wapi-api.md#asset-detail-user_data + https://binance-docs.github.io/apidocs/spot/en/#asset-detail-user_data :param recvWindow: the number of milliseconds the request is valid for :type recvWindow: int @@ -2288,7 +2287,7 @@ def stream_get_listen_key(self): Can be used to keep the user stream alive. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#start-user-data-stream-user_stream + https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#start-user-data-stream-user_stream :returns: API response @@ -2301,13 +2300,13 @@ def stream_get_listen_key(self): :raises: BinanceRequestException, BinanceAPIException """ - res = self._post('userDataStream', False, data={}) + res = self._post('userDataStream', False, data={}, version=self.PRIVATE_API_VERSION) return res['listenKey'] def stream_keepalive(self, listenKey): """PING a user data stream to prevent a time out. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#keepalive-user-data-stream-user_stream + https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#keepalive-user-data-stream-user_stream :param listenKey: required :type listenKey: str @@ -2324,12 +2323,12 @@ def stream_keepalive(self, listenKey): params = { 'listenKey': listenKey } - return self._put('userDataStream', False, data=params) + return self._put('userDataStream', False, data=params, version=self.PRIVATE_API_VERSION) def stream_close(self, listenKey): """Close out a user data stream. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#close-user-data-stream-user_stream + https://github.com/binance/binance-spot-api-docs/blob/master/rest-api.md#close-user-data-stream-user_stream :param listenKey: required :type listenKey: str @@ -2346,14 +2345,14 @@ def stream_close(self, listenKey): params = { 'listenKey': listenKey } - return self._delete('userDataStream', False, data=params) + return self._delete('userDataStream', False, data=params, version=self.PRIVATE_API_VERSION) # Margin Trading Endpoints def get_margin_account(self, **params): - """Query margin account details + """Query cross-margin account details - https://github.com/binance-exchange/binance-official-api-docs/blob/master/margin-api.md#query-margin-account-details-user_data + https://binance-docs.github.io/apidocs/spot/en/#query-cross-margin-account-details-user_data :returns: API response @@ -2408,10 +2407,121 @@ def get_margin_account(self, **params): """ return self._request_margin_api('get', 'margin/account', True, data=params) + def get_isolated_margin_account(self, **params): + """Query isolated margin account details + + https://binance-docs.github.io/apidocs/spot/en/#query-isolated-margin-account-info-user_data + + :param symbols: optional up to 5 margin pairs as a comma separated string + :type asset: str + + .. code:: python + + account_info = client.get_isolated_margin_account() + account_info = client.get_isolated_margin_account(symbols="BTCUSDT,ETHUSDT") + + :returns: API response + + .. code-block:: python + + If "symbols" is not sent: + + { + "assets":[ + { + "baseAsset": + { + "asset": "BTC", + "borrowEnabled": true, + "borrowed": "0.00000000", + "free": "0.00000000", + "interest": "0.00000000", + "locked": "0.00000000", + "netAsset": "0.00000000", + "netAssetOfBtc": "0.00000000", + "repayEnabled": true, + "totalAsset": "0.00000000" + }, + "quoteAsset": + { + "asset": "USDT", + "borrowEnabled": true, + "borrowed": "0.00000000", + "free": "0.00000000", + "interest": "0.00000000", + "locked": "0.00000000", + "netAsset": "0.00000000", + "netAssetOfBtc": "0.00000000", + "repayEnabled": true, + "totalAsset": "0.00000000" + }, + "symbol": "BTCUSDT" + "isolatedCreated": true, + "marginLevel": "0.00000000", + "marginLevelStatus": "EXCESSIVE", // "EXCESSIVE", "NORMAL", "MARGIN_CALL", "PRE_LIQUIDATION", "FORCE_LIQUIDATION" + "marginRatio": "0.00000000", + "indexPrice": "10000.00000000" + "liquidatePrice": "1000.00000000", + "liquidateRate": "1.00000000" + "tradeEnabled": true + } + ], + "totalAssetOfBtc": "0.00000000", + "totalLiabilityOfBtc": "0.00000000", + "totalNetAssetOfBtc": "0.00000000" + } + + If "symbols" is sent: + + { + "assets":[ + { + "baseAsset": + { + "asset": "BTC", + "borrowEnabled": true, + "borrowed": "0.00000000", + "free": "0.00000000", + "interest": "0.00000000", + "locked": "0.00000000", + "netAsset": "0.00000000", + "netAssetOfBtc": "0.00000000", + "repayEnabled": true, + "totalAsset": "0.00000000" + }, + "quoteAsset": + { + "asset": "USDT", + "borrowEnabled": true, + "borrowed": "0.00000000", + "free": "0.00000000", + "interest": "0.00000000", + "locked": "0.00000000", + "netAsset": "0.00000000", + "netAssetOfBtc": "0.00000000", + "repayEnabled": true, + "totalAsset": "0.00000000" + }, + "symbol": "BTCUSDT" + "isolatedCreated": true, + "marginLevel": "0.00000000", + "marginLevelStatus": "EXCESSIVE", // "EXCESSIVE", "NORMAL", "MARGIN_CALL", "PRE_LIQUIDATION", "FORCE_LIQUIDATION" + "marginRatio": "0.00000000", + "indexPrice": "10000.00000000" + "liquidatePrice": "1000.00000000", + "liquidateRate": "1.00000000" + "tradeEnabled": true + } + ] + } + + """ + return self._request_margin_api('get', 'margin/isolated/account', True, data=params) + def get_margin_asset(self, **params): - """Query margin asset + """Query cross-margin asset - https://github.com/binance-exchange/binance-official-api-docs/blob/master/margin-api.md#query-margin-asset-market_data + https://binance-docs.github.io/apidocs/spot/en/#query-margin-asset-market_data :param asset: name of the asset :type asset: str @@ -2439,9 +2549,9 @@ def get_margin_asset(self, **params): return self._request_margin_api('get', 'margin/asset', data=params) def get_margin_symbol(self, **params): - """Query margin symbol info + """Query cross-margin symbol info - https://github.com/binance-exchange/binance-official-api-docs/blob/master/margin-api.md#query-margin-pair-market_data + https://binance-docs.github.io/apidocs/spot/en/#query-cross-margin-pair-market_data :param symbol: name of the symbol pair :type symbol: str @@ -2470,17 +2580,116 @@ def get_margin_symbol(self, **params): """ return self._request_margin_api('get', 'margin/pair', data=params) + def create_isolated_margin_account(self, **params): + """Create isolated margin account for symbol + + https://binance-docs.github.io/apidocs/spot/en/#create-isolated-margin-account-margin + + :param base: Base asset of symbol + :type base: str + :param quote: Quote asset of symbol + :type quote: str + + .. code:: python + + pair_details = client.create_isolated_margin_account(base='USDT', quote='BTC') + + :returns: API response + + .. code-block:: python + + { + "success": true, + "symbol": "BTCUSDT" + } + + + :raises: BinanceRequestException, BinanceAPIException + + """ + return self._request_margin_api('post', 'margin/isolated/create', signed=True, data=params) + + + def get_isolated_margin_symbol(self, **params): + """Query isolated margin symbol info + + https://binance-docs.github.io/apidocs/spot/en/#query-isolated-margin-symbol-user_data + + :param symbol: name of the symbol pair + :type symbol: str + + .. code:: python + + pair_details = client.get_isolated_margin_symbol(symbol='BTCUSDT') + + :returns: API response + + .. code-block:: python + + { + "symbol":"BTCUSDT", + "base":"BTC", + "quote":"USDT", + "isMarginTrade":true, + "isBuyAllowed":true, + "isSellAllowed":true + } + + + :raises: BinanceRequestException, BinanceAPIException + + """ + return self._request_margin_api('get', 'margin/isolated/pair', signed=True, data=params) + + def get_all_isolated_margin_symbols(self, **params): + """Query isolated margin symbol info for all pairs + + https://binance-docs.github.io/apidocs/spot/en/#get-all-isolated-margin-symbol-user_data + + .. code:: python + + pair_details = client.get_all_isolated_margin_symbols() + + :returns: API response + + .. code-block:: python + + [ + { + "base": "BNB", + "isBuyAllowed": true, + "isMarginTrade": true, + "isSellAllowed": true, + "quote": "BTC", + "symbol": "BNBBTC" + }, + { + "base": "TRX", + "isBuyAllowed": true, + "isMarginTrade": true, + "isSellAllowed": true, + "quote": "BTC", + "symbol": "TRXBTC" + } + ] + + + :raises: BinanceRequestException, BinanceAPIException + + """ + return self._request_margin_api('get', 'margin/isolated/allPairs', signed=True, data=params) + def get_margin_price_index(self, **params): """Query margin priceIndex - https://github.com/binance-exchange/binance-official-api-docs/blob/master/margin-api.md#query-margin-priceindex-market_data + https://binance-docs.github.io/apidocs/spot/en/#query-margin-priceindex-market_data :param symbol: name of the symbol pair :type symbol: str .. code:: python - price_index_details = client.get_margin_pair(symbol='BTCUSDT') + price_index_details = client.get_margin_price_index(symbol='BTCUSDT') :returns: API response @@ -2498,9 +2707,9 @@ def get_margin_price_index(self, **params): return self._request_margin_api('get', 'margin/priceIndex', data=params) def transfer_margin_to_spot(self, **params): - """Execute transfer between margin account and spot account. + """Execute transfer between cross-margin account and spot account. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/margin-api.md#margin-account-transfer-margin + https://binance-docs.github.io/apidocs/spot/en/#cross-margin-account-transfer-margin :param asset: name of the asset :type asset: str @@ -2528,9 +2737,9 @@ def transfer_margin_to_spot(self, **params): return self._request_margin_api('post', 'margin/transfer', signed=True, data=params) def transfer_spot_to_margin(self, **params): - """Execute transfer between spot account and margin account. + """Execute transfer between spot account and cross-margin account. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/margin-api.md#margin-account-transfer-margin + https://binance-docs.github.io/apidocs/spot/en/#cross-margin-account-transfer-margin :param asset: name of the asset :type asset: str @@ -2557,15 +2766,88 @@ def transfer_spot_to_margin(self, **params): params['type'] = 1 return self._request_margin_api('post', 'margin/transfer', signed=True, data=params) + + def transfer_isolated_margin_to_spot(self, **params): + """Execute transfer between isolated margin account and spot account. + + https://binance-docs.github.io/apidocs/spot/en/#isolated-margin-account-transfer-margin + + :param asset: name of the asset + :type asset: str + :param symbol: pair symbol + :type symbol: str + :param amount: amount to transfer + :type amount: str + :param recvWindow: the number of milliseconds the request is valid for + :type recvWindow: int + + .. code:: python + + transfer = client.transfer_isolated_margin_to_spot(asset='BTC', + symbol='ETHBTC', amount='1.1') + + :returns: API response + + .. code-block:: python + + { + "tranId": 100000001 + } + + :raises: BinanceRequestException, BinanceAPIException + + """ + params['transFrom'] = "ISOLATED_MARGIN" + params['transTo'] = "SPOT" + return self._request_margin_api('post', 'margin/isolated/transfer', signed=True, data=params) + + def transfer_spot_to_isolated_margin(self, **params): + """Execute transfer between spot account and isolated margin account. + + https://binance-docs.github.io/apidocs/spot/en/#isolated-margin-account-transfer-margin + + :param asset: name of the asset + :type asset: str + :param symbol: pair symbol + :type symbol: str + :param amount: amount to transfer + :type amount: str + :param recvWindow: the number of milliseconds the request is valid for + :type recvWindow: int + + .. code:: python + + transfer = client.transfer_spot_to_isolated_margin(asset='BTC', + symbol='ETHBTC', amount='1.1') + + :returns: API response + + .. code-block:: python + + { + "tranId": 100000001 + } + + :raises: BinanceRequestException, BinanceAPIException + + """ + params['transFrom'] = "SPOT" + params['transTo'] = "ISOLATED_MARGIN" + return self._request_margin_api('post', 'margin/isolated/transfer', signed=True, data=params) + def create_margin_loan(self, **params): - """Apply for a loan. + """Apply for a loan in cross-margin or isolated-margin account. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/margin-api.md#margin-account-borrow-margin + https://binance-docs.github.io/apidocs/spot/en/#margin-account-borrow-margin :param asset: name of the asset :type asset: str :param amount: amount to transfer :type amount: str + :param isIsolated: set to 'TRUE' for isolated margin (default 'FALSE') + :type isIsolated: str + :param symbol: Isolated margin symbol (default blank for cross-margin) + :type symbol: str :param recvWindow: the number of milliseconds the request is valid for :type recvWindow: int @@ -2573,6 +2855,9 @@ def create_margin_loan(self, **params): transaction = client.margin_create_loan(asset='BTC', amount='1.1') + transaction = client.margin_create_loan(asset='BTC', amount='1.1', + isIsolated='TRUE', symbol='ETHBTC') + :returns: API response .. code-block:: python @@ -2587,14 +2872,20 @@ def create_margin_loan(self, **params): return self._request_margin_api('post', 'margin/loan', signed=True, data=params) def repay_margin_loan(self, **params): - """Repay loan for margin account. + """Repay loan in cross-margin or isolated-margin account. + + If amount is more than the amount borrowed, the full loan will be repaid. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/margin-api.md#margin-account-repay-margin + https://binance-docs.github.io/apidocs/spot/en/#margin-account-repay-margin :param asset: name of the asset :type asset: str :param amount: amount to transfer :type amount: str + :param isIsolated: set to 'TRUE' for isolated margin (default 'FALSE') + :type isIsolated: str + :param symbol: Isolated margin symbol (default blank for cross-margin) + :type symbol: str :param recvWindow: the number of milliseconds the request is valid for :type recvWindow: int @@ -2602,6 +2893,9 @@ def repay_margin_loan(self, **params): transaction = client.margin_repay_loan(asset='BTC', amount='1.1') + transaction = client.margin_repay_loan(asset='BTC', amount='1.1', + isIsolated='TRUE', symbol='ETHBTC') + :returns: API response .. code-block:: python @@ -2618,10 +2912,12 @@ def repay_margin_loan(self, **params): def create_margin_order(self, **params): """Post a new order for margin account. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/margin-api.md#margin-account-new-order-trade + https://binance-docs.github.io/apidocs/spot/en/#margin-account-new-order-trade :param symbol: required :type symbol: str + :param isIsolated: set to 'TRUE' for isolated margin (default 'FALSE') + :type isIsolated: str :param side: required :type side: str :param type: required @@ -2739,10 +3035,12 @@ def cancel_margin_order(self, **params): Either orderId or origClientOrderId must be sent. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/margin-api.md#margin-account-cancel-order-trade + https://binance-docs.github.io/apidocs/spot/en/#margin-account-cancel-order-trade :param symbol: required :type symbol: str + :param isIsolated: set to 'TRUE' for isolated margin (default 'FALSE') + :type isIsolated: str :param orderId: :type orderId: str :param origClientOrderId: @@ -2780,13 +3078,15 @@ def get_margin_loan_details(self, **params): txId or startTime must be sent. txId takes precedence. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/margin-api.md#margin-account-cancel-order-trade + https://binance-docs.github.io/apidocs/spot/en/#query-loan-record-user_data :param asset: required :type asset: str + :param isolatedSymbol: isolated symbol (if querying isolated margin) + :type isolatedSymbol: str :param txId: the tranId in of the created loan :type txId: str - :param startTime: + :param startTime: earliest timestamp to filter transactions :type startTime: str :param endTime: Used to uniquely identify this cancel. Automatically generated by default. :type endTime: str @@ -2822,10 +3122,12 @@ def get_margin_repay_details(self, **params): txId or startTime must be sent. txId takes precedence. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/margin-api.md#margin-account-cancel-order-trade + https://binance-docs.github.io/apidocs/spot/en/#query-repay-record-user_data :param asset: required :type asset: str + :param isolatedSymbol: isolated symbol (if querying isolated margin) + :type isolatedSymbol: str :param txId: the tranId in of the created loan :type txId: str :param startTime: @@ -2872,10 +3174,12 @@ def get_margin_order(self, **params): For some historical orders cummulativeQuoteQty will be < 0, meaning the data is not available at this time. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/margin-api.md#query-margin-accounts-order-user_data + https://binance-docs.github.io/apidocs/spot/en/#query-margin-account-39-s-order-user_data :param symbol: required :type symbol: str + :param isIsolated: set to 'TRUE' for isolated margin (default 'FALSE') + :type isIsolated: str :param orderId: :type orderId: str :param origClientOrderId: @@ -2912,15 +3216,19 @@ def get_margin_order(self, **params): def get_open_margin_orders(self, **params): """Query margin accounts open orders - If the symbol is not sent, orders for all symbols will be returned in an array. + If the symbol is not sent, orders for all symbols will be returned in an array (cross-margin only). + + If querying isolated margin orders, both the isIsolated='TRUE' and symbol=symbol_name must be set. When all symbols are returned, the number of requests counted against the rate limiter is equal to the number of symbols currently trading on the exchange. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/margin-api.md#query-margin-accounts-open-order-user_data + https://binance-docs.github.io/apidocs/spot/en/#query-margin-account-39-s-open-order-user_data :param symbol: optional :type symbol: str + :param isIsolated: set to 'TRUE' for isolated margin (default 'FALSE') + :type isIsolated: str :param recvWindow: the number of milliseconds the request is valid for :type recvWindow: int @@ -2959,10 +3267,12 @@ def get_all_margin_orders(self, **params): For some historical orders cummulativeQuoteQty will be < 0, meaning the data is not available at this time. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/margin-api.md#query-margin-accounts-open-order-user_data + https://binance-docs.github.io/apidocs/spot/en/#query-margin-account-39-s-all-order-user_data :param symbol: required :type symbol: str + :param isIsolated: set to 'TRUE' for isolated margin (default 'FALSE') + :type isIsolated: str :param orderId: optional :type orderId: str :param startTime: optional @@ -3014,10 +3324,12 @@ def get_margin_trades(self, **params): If fromId is set, it will get orders >= that fromId. Otherwise most recent orders are returned. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/margin-api.md#query-margin-accounts-trade-list-user_data + https://binance-docs.github.io/apidocs/spot/en/#query-margin-account-39-s-trade-list-user_data :param symbol: required :type symbol: str + :param isIsolated: set to 'TRUE' for isolated margin (default 'FALSE') + :type isIsolated: str :param fromId: optional :type fromId: str :param startTime: optional @@ -3068,10 +3380,12 @@ def get_margin_trades(self, **params): def get_max_margin_loan(self, **params): """Query max borrow amount for an asset - https://github.com/binance-exchange/binance-official-api-docs/blob/master/margin-api.md#query-max-borrow-user_data + https://binance-docs.github.io/apidocs/spot/en/#query-max-borrow-user_data :param asset: required :type asset: str + :param isolatedSymbol: isolated symbol (if querying isolated margin) + :type isolatedSymbol: str :param recvWindow: the number of milliseconds the request is valid for :type recvWindow: int @@ -3089,10 +3403,12 @@ def get_max_margin_loan(self, **params): def get_max_margin_transfer(self, **params): """Query max transfer-out amount - https://github.com/binance-exchange/binance-official-api-docs/blob/master/margin-api.md#query-max-transfer-out-amount-user_data + https://binance-docs.github.io/apidocs/spot/en/#query-max-transfer-out-amount-user_data :param asset: required :type asset: str + :param isolatedSymbol: isolated symbol (if querying isolated margin) + :type isolatedSymbol: str :param recvWindow: the number of milliseconds the request is valid for :type recvWindow: int @@ -3107,14 +3423,16 @@ def get_max_margin_transfer(self, **params): """ return self._request_margin_api('get', 'margin/maxTransferable', signed=True, data=params) + # Cross-margin + def margin_stream_get_listen_key(self): - """Start a new margin data stream and return the listen key + """Start a new cross-margin data stream and return the listen key If a stream already exists it should return the same key. If the stream becomes invalid a new key is returned. - Can be used to keep the user stream alive. + Can be used to keep the stream alive. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/margin-api.md#start-user-data-stream-for-margin-account-user_stream + https://binance-docs.github.io/apidocs/spot/en/#listen-key-margin :returns: API response @@ -3127,13 +3445,13 @@ def margin_stream_get_listen_key(self): :raises: BinanceRequestException, BinanceAPIException """ - res = self._request_margin_api('post', 'userDataStream', signed=True, data={}) + res = self._request_margin_api('post', 'userDataStream', signed=False, data={}) return res['listenKey'] def margin_stream_keepalive(self, listenKey): - """PING a margin data stream to prevent a time out. + """PING a cross-margin data stream to prevent a time out. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/margin-api.md#ping-user-data-stream-for-margin-account--user_stream + https://binance-docs.github.io/apidocs/spot/en/#listen-key-margin :param listenKey: required :type listenKey: str @@ -3150,13 +3468,68 @@ def margin_stream_keepalive(self, listenKey): params = { 'listenKey': listenKey } - return self._request_margin_api('put', 'userDataStream', signed=True, data=params) + return self._request_margin_api('put', 'userDataStream', signed=False, data=params) def margin_stream_close(self, listenKey): - """Close out a margin data stream. + """Close out a cross-margin data stream. + + https://binance-docs.github.io/apidocs/spot/en/#listen-key-margin + + :param listenKey: required + :type listenKey: str + + :returns: API response + + .. code-block:: python + + {} + + :raises: BinanceRequestException, BinanceAPIException + + """ + params = { + 'listenKey': listenKey + } + return self._request_margin_api('delete', 'userDataStream', signed=False, data=params) + + # Isolated margin + + def isolated_margin_stream_get_listen_key(self, symbol): + """Start a new isolated margin data stream and return the listen key + If a stream already exists it should return the same key. + If the stream becomes invalid a new key is returned. + + Can be used to keep the stream alive. + + https://binance-docs.github.io/apidocs/spot/en/#listen-key-isolated-margin + + :param symbol: required - symbol for the isolated margin account + :type symbol: str + + :returns: API response + + .. code-block:: python - https://github.com/binance-exchange/binance-official-api-docs/blob/master/margin-api.md#delete-user-data-stream-for-margin-account--user_stream + { + "listenKey": "T3ee22BIYuWqmvne0HNq2A2WsFlEtLhvWCtItw6ffhhdmjifQ2tRbuKkTHhr" + } + + :raises: BinanceRequestException, BinanceAPIException + + """ + params = { + 'symbol': symbol + } + res = self._request_margin_api('post', 'userDataStream/isolated', signed=False, data=params) + return res['listenKey'] + + def isolated_margin_stream_keepalive(self, symbol, listenKey): + """PING an isolated margin data stream to prevent a time out. + + https://binance-docs.github.io/apidocs/spot/en/#listen-key-isolated-margin + :param symbol: required - symbol for the isolated margin account + :type symbol: str :param listenKey: required :type listenKey: str @@ -3170,9 +3543,35 @@ def margin_stream_close(self, listenKey): """ params = { + 'symbol': symbol, 'listenKey': listenKey } - return self._request_margin_api('delete', 'userDataStream', signed=True, data=params) + return self._request_margin_api('put', 'userDataStream/isolated', signed=False, data=params) + + def isolated_margin_stream_close(self, symbol, listenKey): + """Close out an isolated margin data stream. + + https://binance-docs.github.io/apidocs/spot/en/#listen-key-isolated-margin + + :param symbol: required - symbol for the isolated margin account + :type symbol: str + :param listenKey: required + :type listenKey: str + + :returns: API response + + .. code-block:: python + + {} + + :raises: BinanceRequestException, BinanceAPIException + + """ + params = { + 'symbol': symbol, + 'listenKey': listenKey + } + return self._request_margin_api('delete', 'userDataStream/isolated', signed=False, data=params) # Lending Endpoints @@ -3182,7 +3581,7 @@ def get_lending_product_list(self, **params): https://binance-docs.github.io/apidocs/spot/en/#get-flexible-product-list-user_data """ - return self._request_margin_api('get', 'lending/daily/product/list ', signed=True, data=params) + return self._request_margin_api('get', 'lending/daily/product/list', signed=True, data=params) def get_lending_daily_quota_left(self, **params): """Get Left Daily Purchase Quota of Flexible Product. @@ -3224,6 +3623,56 @@ def get_lending_position(self, **params): """ return self._request_margin_api('get', 'lending/daily/token/position', signed=True, data=params) + def get_fixed_activity_project_list(self, **params): + """Get Fixed and Activity Project List + + https://binance-docs.github.io/apidocs/spot/en/#get-fixed-and-activity-project-list-user_data + + :param asset: optional + :type asset: str + :param type: required - "ACTIVITY", "CUSTOMIZED_FIXED" + :type type: str + :param status: optional - "ALL", "SUBSCRIBABLE", "UNSUBSCRIBABLE"; default "ALL" + :type status: str + :param sortBy: optional - "START_TIME", "LOT_SIZE", "INTEREST_RATE", "DURATION"; default "START_TIME" + :type sortBy: str + :param current: optional - Currently querying page. Start from 1. Default:1 + :type current: int + :param size: optional - Default:10, Max:100 + :type size: int + :param recvWindow: the number of milliseconds the request is valid for + :type recvWindow: int + + :returns: API response + + .. code-block:: python + + [ + { + "asset": "USDT", + "displayPriority": 1, + "duration": 90, + "interestPerLot": "1.35810000", + "interestRate": "0.05510000", + "lotSize": "100.00000000", + "lotsLowLimit": 1, + "lotsPurchased": 74155, + "lotsUpLimit": 80000, + "maxLotsPerUser": 2000, + "needKyc": False, + "projectId": "CUSDT90DAYSS001", + "projectName": "USDT", + "status": "PURCHASING", + "type": "CUSTOMIZED_FIXED", + "withAreaLimitation": False + } + ] + + :raises: BinanceRequestException, BinanceAPIException + + """ + return self._request_margin_api('get', 'lending/project/list', signed=True, data=params) + def get_lending_account(self, **params): """Get Lending Account Details @@ -3261,7 +3710,7 @@ def get_lending_interest_history(self, **params): def get_sub_account_list(self, **params): """Query Sub-account List. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/wapi-api.md#query-sub-account-listfor-master-account + https://binance-docs.github.io/apidocs/spot/en/#query-sub-account-list-for-master-account :param email: optional :type email: str @@ -3310,7 +3759,7 @@ def get_sub_account_list(self, **params): def get_sub_account_transfer_history(self, **params): """Query Sub-account Transfer History. - https://github.com/binance-exchange/binance-official-api-docs/blob/master/wapi-api.md#query-sub-account-transfer-historyfor-master-account + https://binance-docs.github.io/apidocs/spot/en/#query-sub-account-spot-asset-transfer-history-for-master-account :param email: required :type email: str @@ -3357,7 +3806,7 @@ def get_sub_account_transfer_history(self, **params): def create_sub_account_transfer(self, **params): """Execute sub-account transfer - https://github.com/binance-exchange/binance-official-api-docs/blob/9dbe0e961b80557bb19708a707c7fad08842b28e/wapi-api.md#sub-account-transferfor-master-account + https://binance-docs.github.io/apidocs/spot/en/#sub-account-spot-asset-transfer-for-master-account :param fromEmail: required - Sender email :type fromEmail: str @@ -3383,11 +3832,93 @@ def create_sub_account_transfer(self, **params): """ return self._request_withdraw_api('post', 'sub-account/transfer.html', True, data=params) + + def get_sub_account_futures_transfer_history(self, **params): + """Query Sub-account Futures Transfer History. + + https://binance-docs.github.io/apidocs/spot/en/#query-sub-account-futures-asset-transfer-history-for-master-account + + :param email: required + :type email: str + :param futuresType: required + :type futuresType: int + :param startTime: optional + :type startTime: int + :param endTime: optional + :type endTime: int + :param page: optional + :type page: int + :param limit: optional + :type limit: int + :param recvWindow: optional + :type recvWindow: int + + :returns: API response + + .. code-block:: python + + { + "success":true, + "futuresType": 2, + "transfers":[ + { + "from":"aaa@test.com", + "to":"bbb@test.com", + "asset":"BTC", + "qty":"1", + "time":1544433328000 + }, + { + "from":"bbb@test.com", + "to":"ccc@test.com", + "asset":"ETH", + "qty":"2", + "time":1544433328000 + } + ] + } + + :raises: BinanceRequestException, BinanceAPIException + + """ + return self._request_margin_api('get', 'sub-account/futures/internalTransfer', True, data=params) + + def create_sub_account_futures_transfer(self, **params): + """Execute sub-account Futures transfer + + https://github.com/binance-exchange/binance-official-api-docs/blob/9dbe0e961b80557bb19708a707c7fad08842b28e/wapi-api.md#sub-account-transferfor-master-account + + :param fromEmail: required - Sender email + :type fromEmail: str + :param toEmail: required - Recipient email + :type toEmail: str + :param futuresType: required + :type futuresType: int + :param asset: required + :type asset: str + :param amount: required + :type amount: decimal + :param recvWindow: optional + :type recvWindow: int + + :returns: API response + + .. code-block:: python + + { + "success":true, + "txnId":"2934662589" + } + + :raises: BinanceRequestException, BinanceAPIException + + """ + return self._request_margin_api('post', 'sub-account/futures/internalTransfer', True, data=params) def get_sub_account_assets(self, **params): """Fetch sub-account assets - https://github.com/binance-exchange/binance-official-api-docs/blob/9dbe0e961b80557bb19708a707c7fad08842b28e/wapi-api.md#query-sub-account-assetsfor-master-account + https://binance-docs.github.io/apidocs/spot/en/#query-sub-account-assets-for-master-account :param email: required :type email: str @@ -3565,7 +4096,7 @@ def futures_leverage_bracket(self, **params): https://binance-docs.github.io/apidocs/futures/en/#notional-and-leverage-brackets-market_data """ - return self._request_futures_api('get', 'ticker/leverageBracket', data=params) + return self._request_futures_api('get', 'leverageBracket', True, data=params) def transfer_history(self, **params): """Get future account transaction history list @@ -3702,3 +4233,19 @@ def futures_income_history(self, **params): """ return self._request_futures_api('get', 'income', True, data=params) + + def futures_change_position_mode(self, **params): + """Change position mode for authenticated account + + https://binance-docs.github.io/apidocs/futures/en/#change-position-mode-trade + + """ + return self._request_futures_api('post', 'positionSide/dual', True, data=params) + + def futures_get_position_mode(self, **params): + """Get position mode for authenticated account + + https://binance-docs.github.io/apidocs/futures/en/#get-current-position-mode-user_data + + """ + return self._request_futures_api('get', 'positionSide/dual', True, data=params) \ No newline at end of file diff --git a/binance/depthcache.py b/binance/depthcache.py index be665332b..273002615 100644 --- a/binance/depthcache.py +++ b/binance/depthcache.py @@ -121,7 +121,7 @@ class DepthCacheManager(object): _default_refresh = 60 * 30 # 30 minutes - def __init__(self, client, symbol, callback=None, refresh_interval=_default_refresh, bm=None, limit=500): + def __init__(self, client, symbol, callback=None, refresh_interval=_default_refresh, bm=None, limit=500, ws_interval=None): """Initialise the DepthCacheManager :param client: Binance API client @@ -134,6 +134,8 @@ def __init__(self, client, symbol, callback=None, refresh_interval=_default_refr :type refresh_interval: int :param limit: Optional number of orders to get from orderbook :type limit: int + :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). + :type ws_interval: int """ self._client = client @@ -146,6 +148,7 @@ def __init__(self, client, symbol, callback=None, refresh_interval=_default_refr self._depth_cache = DepthCache(self._symbol) self._refresh_interval = refresh_interval self._conn_key = None + self._ws_interval = ws_interval self._start_socket() self._init_cache() @@ -188,7 +191,7 @@ def _start_socket(self): if self._bm is None: self._bm = BinanceSocketManager(self._client) - self._conn_key = self._bm.start_depth_socket(self._symbol, self._depth_event) + self._conn_key = self._bm.start_depth_socket(self._symbol, self._depth_event, interval=self._ws_interval) if not self._bm.is_alive(): self._bm.start() @@ -271,3 +274,10 @@ def close(self, close_socket=False): self._bm.close() time.sleep(1) self._depth_cache = None + + def get_symbol(self): + """Get the symbol + + :return: symbol + """ + return self._symbol diff --git a/binance/websockets.py b/binance/websockets.py index 42ad33065..cfc4c05c1 100644 --- a/binance/websockets.py +++ b/binance/websockets.py @@ -64,6 +64,7 @@ def clientConnectionLost(self, connector, reason): class BinanceSocketManager(threading.Thread): STREAM_URL = 'wss://stream.binance.com:9443/' + FSTREAM_URL = 'wss://fstream.binance.com/' WEBSOCKET_DEPTH_5 = '5' WEBSOCKET_DEPTH_10 = '10' @@ -84,9 +85,10 @@ def __init__(self, client, user_timeout=DEFAULT_USER_TIMEOUT): self._conns = {} self._client = client self._user_timeout = user_timeout - self._timers = {'user': None, 'margin': None} + self._timers = {'user': None, 'margin': None} self._listen_keys = {'user': None, 'margin': None} self._account_callbacks = {'user': None, 'margin': None} + # Isolated margin sockets will be opened under the 'symbol' name def _start_socket(self, path, callback, prefix='ws/'): if path in self._conns: @@ -102,7 +104,21 @@ def _start_socket(self, path, callback, prefix='ws/'): self._conns[path] = connectWS(factory, context_factory) return path - def start_depth_socket(self, symbol, callback, depth=None): + def _start_futures_socket(self, path, callback, prefix='stream?streams='): + if path in self._conns: + return False + + factory_url = self.FSTREAM_URL + prefix + path + factory = BinanceClientFactory(factory_url) + factory.protocol = BinanceClientProtocol + factory.callback = callback + factory.reconnect = True + context_factory = ssl.ClientContextFactory() + + self._conns[path] = connectWS(factory, context_factory) + return path + + def start_depth_socket(self, symbol, callback, depth=None, interval=None): """Start a websocket for symbol market depth returning either a diff or a partial book https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#partial-book-depth-streams @@ -113,6 +129,8 @@ def start_depth_socket(self, symbol, callback, depth=None): :type callback: function :param depth: optional Number of depth entries to return, default None. If passed returns a partial book instead of a diff :type depth: str + :param interval: optional interval for updates, default None. If not set, updates happen every second. Must be 0, None (1s) or 100 (100ms) + :type interval: int :returns: connection key string if successful, False otherwise @@ -169,6 +187,11 @@ def start_depth_socket(self, symbol, callback, depth=None): socket_name = symbol.lower() + '@depth' if depth and depth != '1': socket_name = '{}{}'.format(socket_name, depth) + if interval: + if interval in [0, 100]: + socket_name = '{}@{}ms'.format(socket_name, interval) + else: + raise ValueError("Websocket interval value not allowed. Allowed values are [0, 100]") return self._start_socket(socket_name, callback) def start_kline_socket(self, symbol, callback, interval=Client.KLINE_INTERVAL_1MINUTE): @@ -406,6 +429,99 @@ def start_ticker_socket(self, callback): """ return self._start_socket('!ticker@arr', callback) + def start_symbol_mark_price_socket(self, symbol, callback, fast=True): + """Start a websocket for a symbol's futures mark price + https://binance-docs.github.io/apidocs/futures/en/#mark-price-stream + :param symbol: required + :type symbol: str + :param callback: callback function to handle messages + :type callback: function + :returns: connection key string if successful, False otherwise + Message Format + .. code-block:: python + { + "e": "markPriceUpdate", // Event type + "E": 1562305380000, // Event time + "s": "BTCUSDT", // Symbol + "p": "11185.87786614", // Mark price + "r": "0.00030000", // Funding rate + "T": 1562306400000 // Next funding time + } + """ + stream_name = '@markPrice@1s' if fast else '@markPrice' + return self._start_futures_socket(symbol.lower() + stream_name, callback) + + def start_all_mark_price_socket(self, callback, fast=True): + """Start a websocket for all futures mark price data + By default all symbols are included in an array. + https://binance-docs.github.io/apidocs/futures/en/#mark-price-stream-for-all-market + :param callback: callback function to handle messages + :type callback: function + :returns: connection key string if successful, False otherwise + Message Format + .. code-block:: python + + [ + { + "e": "markPriceUpdate", // Event type + "E": 1562305380000, // Event time + "s": "BTCUSDT", // Symbol + "p": "11185.87786614", // Mark price + "r": "0.00030000", // Funding rate + "T": 1562306400000 // Next funding time + } + ] + """ + stream_name = '!markPrice@arr@1s' if fast else '!markPrice@arr' + return self._start_futures_socket(stream_name, callback) + + def start_symbol_ticker_futures_socket(self, symbol, callback): + """Start a websocket for a symbol's ticker data + By default all markets are included in an array. + https://binance-docs.github.io/apidocs/futures/en/#individual-symbol-book-ticker-streams + :param symbol: required + :type symbol: str + :param callback: callback function to handle messages + :type callback: function + :returns: connection key string if successful, False otherwise + .. code-block:: python + [ + { + "u":400900217, // order book updateId + "s":"BNBUSDT", // symbol + "b":"25.35190000", // best bid price + "B":"31.21000000", // best bid qty + "a":"25.36520000", // best ask price + "A":"40.66000000" // best ask qty + } + ] + """ + return self._start_futures_socket(symbol.lower() + '@bookTicker', callback) + + def start_all_ticker_futures_socket(self, callback): + """Start a websocket for all ticker data + By default all markets are included in an array. + https://binance-docs.github.io/apidocs/futures/en/#all-book-tickers-stream + :param callback: callback function to handle messages + :type callback: function + :returns: connection key string if successful, False otherwise + Message Format + .. code-block:: python + [ + { + "u":400900217, // order book updateId + "s":"BNBUSDT", // symbol + "b":"25.35190000", // best bid price + "B":"31.21000000", // best bid qty + "a":"25.36520000", // best ask price + "A":"40.66000000" // best ask qty + } + ] + """ + + + return self._start_futures_socket('!bookTicker', callback) + def start_symbol_book_ticker_socket(self, symbol, callback): """Start a websocket for the best bid or ask's price or quantity for a specified symbol. @@ -482,6 +598,7 @@ def start_user_socket(self, callback): """Start a websocket for user data https://github.com/binance-exchange/binance-official-api-docs/blob/master/user-data-stream.md + https://binance-docs.github.io/apidocs/spot/en/#listen-key-spot :param callback: callback function to handle messages :type callback: function @@ -496,9 +613,9 @@ def start_user_socket(self, callback): return self._start_account_socket('user', user_listen_key, callback) def start_margin_socket(self, callback): - """Start a websocket for margin data + """Start a websocket for cross-margin data - https://github.com/binance-exchange/binance-official-api-docs/blob/master/user-data-stream.md + https://binance-docs.github.io/apidocs/spot/en/#listen-key-margin :param callback: callback function to handle messages :type callback: function @@ -512,6 +629,25 @@ def start_margin_socket(self, callback): # and start the socket with this specific key return self._start_account_socket('margin', margin_listen_key, callback) + def start_isolated_margin_socket(self, symbol, callback): + """Start a websocket for isolated margin data + + https://binance-docs.github.io/apidocs/spot/en/#listen-key-isolated-margin + + :param symbol: required - symbol for the isolated margin account + :type symbol: str + :param callback: callback function to handle messages + :type callback: function + + :returns: connection key string if successful, False otherwise + + Message Format - see Binance API docs for all types + """ + # Get the isolated margin listen key + isolated_margin_listen_key = self._client.isolated_margin_stream_get_listen_key(symbol) + # and start the socket with this specific kek + return self._start_account_socket(symbol, isolated_margin_listen_key, callback) + def _start_account_socket(self, socket_type, listen_key, callback): """Starts one of user or margin socket""" self._check_account_socket_open(listen_key) @@ -542,10 +678,15 @@ def _keepalive_account_socket(self, socket_type): if socket_type == 'user': listen_key_func = self._client.stream_get_listen_key callback = self._account_callbacks[socket_type] - else: + listen_key = listen_key_func() + elif socket_type == 'margin': # cross-margin listen_key_func = self._client.margin_stream_get_listen_key callback = self._account_callbacks[socket_type] - listen_key = listen_key_func() + listen_key = listen_key_func() + else: # isolated margin + listen_key_func = self._client.isolated_margin_stream_get_listen_key + callback = self._account_callbacks.get(socket_type, None) + listen_key = listen_key_func(socket_type) # Passing symbol for islation margin if listen_key != self._listen_keys[socket_type]: self._start_account_socket(socket_type, listen_key, callback) @@ -565,18 +706,26 @@ def stop_socket(self, conn_key): self._conns[conn_key].disconnect() del(self._conns[conn_key]) - # check if we have a user stream socket - if len(conn_key) >= 60 and conn_key[:60] == self._listen_keys['user']: - self._stop_account_socket('user') + # OBSOLETE - removed when adding isolated margin. Loop over keys instead + # # check if we have a user stream socket + # if len(conn_key) >= 60 and conn_key[:60] == self._listen_keys['user']: + # self._stop_account_socket('user') + + # # or a margin stream socket + # if len(conn_key) >= 60 and conn_key[:60] == self._listen_keys['margin']: + # self._stop_account_socket('margin') + + # NEW - Loop over keys in _listen_keys dictionary to find a match on + # user, cross-margin and isolated margin: + for key, value in self._listen_keys.items(): + if len(conn_key) >= 60 and conn_key[:60] == value: + self._stop_account_socket(key) - # or a margin stream socket - if len(conn_key) >= 60 and conn_key[:60] == self._listen_keys['margin']: - self._stop_account_socket('margin') def _stop_account_socket(self, socket_type): - if not self._listen_keys[socket_type]: + if not self._listen_keys.get(socket_type, None): return - if self._timers[socket_type]: + if self._timers.get(socket_type, None): self._timers[socket_type].cancel() self._timers[socket_type] = None self._listen_keys[socket_type] = None diff --git a/docs/account.rst b/docs/account.rst index 2eb815da4..5344e5bda 100644 --- a/docs/account.rst +++ b/docs/account.rst @@ -9,7 +9,7 @@ Order Validation Binance has a number of rules around symbol pair orders with validation on minimum price, quantity and total order value. -Read more about their specifics in the `Filters `_ +Read more about their specifics in the `Filters `_ section of the official API. It can be helpful to format the output using the following snippet diff --git a/docs/changelog.rst b/docs/changelog.rst index a3d1fac96..505555a8e 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -1,6 +1,11 @@ Changelog ========= +v0.7.5.dev +^^^^^^^^^^ +**Changed** +- Stock json lib to ujson (https://github.com/sammchardy/python-binance/pull/383) + v0.7.5 - 2020-02-06 ^^^^^^^^^^^^^^^^^^^ diff --git a/docs/margin.rst b/docs/margin.rst index 5f259c8ca..11cbc1626 100644 --- a/docs/margin.rst +++ b/docs/margin.rst @@ -1,23 +1,45 @@ Margin Trading Endpoints ======================== +.. note :: + + **Cross-margin vs isolated margin trading** + + 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. + + 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. + Market Data ----------- -`Get margin asset info `_ +`Get cross-margin asset info `_ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. code:: python info = client.get_margin_asset(asset='BNB') -`Get margin symbol info `_ +`Get cross-margin symbol info `_ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. code:: python info = client.get_margin_symbol(symbol='BTCUSDT') +`Get isolated margin symbol info `_ +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. code:: python + + info = client.get_isolated_margin_symbol(symbol='BTCUSDT') + +`Get all isolated margin symbols `_ +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. code:: python + + info = client.get_all_isolated_margin_symbols() + `Get margin price index `_ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -28,12 +50,19 @@ Market Data Orders ------ +Cross-margin vs isolated margin orders +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +By default, these trade execution endpoints will create an order using the *cross-margin* account. + +To 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. + Order Validation ^^^^^^^^^^^^^^^^ Binance has a number of rules around symbol pair orders with validation on minimum price, quantity and total order value. -Read more about their specifics in the `Filters `_ +Read more about their specifics in the `Filters `_ section of the official API. It can be helpful to format the output using the following snippet @@ -56,8 +85,6 @@ It can be helpful to format the output using the following snippet `Place a margin order `_ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -**Place an order** - Use the `create_margin_order` function to have full control over creating an order .. code:: python @@ -99,6 +126,8 @@ Use the `create_margin_order` function to have full control over creating an ord orders = client.get_open_margin_orders(symbol='BNBBTC') +For isolated margin, add the ``isIsolated='TRUE'`` parameter. + `Get all margin orders `_ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -106,31 +135,62 @@ Use the `create_margin_order` function to have full control over creating an ord orders = client.get_all_margin_orders(symbol='BNBBTC') +For isolated margin, add the ``isIsolated='TRUE'`` parameter. Account ------- -`Get margin account info `_ -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +`Get cross-margin account info `_ +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. code:: python info = client.get_margin_account() -`Transfer spot to margin `_ -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +`Create isolated margin account `_ +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. code:: python + + account = client.create_isolated_margin_account(base='BTC', quote='ETH') + +`Get isolated margin account info `_ +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. code:: python + + info = client.get_isolated_margin_account() + +`Transfer spot to cross-margin account `_ +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. code:: python transaction = client.transfer_spot_to_margin(asset='BTC', amount='1.1') -`Transfer margin to spot `_ -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +`Transfer cross-margin account to spot `_ +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. code:: python transaction = client.transfer_margin_to_spot(asset='BTC', amount='1.1') +`Transfer spot to isolated margin account `_ +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. code:: python + + transaction = client.transfer_spot_to_isolated_margin(asset='BTC', + symbol='ETHBTC', amount='1.1') + +`Transfer isolated margin account to spot `_ +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. code:: python + + transaction = client.transfer_isolated_margin_to_spot(asset='BTC', + symbol='ETHBTC', amount='1.1') + `Get max transfer amount `_ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -138,6 +198,7 @@ Account details = client.get_max_margin_transfer(asset='BTC') +This max transfer is for the cross-margin account by default. For isolated margin records, add the ``isolatedSymbol=symbol_name`` parameter. Trades ----- @@ -149,10 +210,12 @@ Trades trades = client.get_margin_trades(symbol='BNBBTC') +For isolated margin trades, add the ``isIsolated='TRUE'`` parameter. + + Loans ----- - `Create loan `_ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -160,6 +223,8 @@ Loans transaction = client.create_margin_loan(asset='BTC', amount='1.1') +This for the cross-margin account by default. For isolated margin, add the ``isIsolated='TRUE'`` and the ``symbol=symbol_name`` parameters. + `Repay loan `_ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -167,6 +232,8 @@ Loans transaction = client.repay_margin_loan(asset='BTC', amount='1.1') +This for the cross-margin account by default. For isolated margin, add the ``isIsolated='TRUE'`` and the ``symbol=symbol_name`` parameters. + `Get loan details `_ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -174,6 +241,8 @@ Loans details = client.get_margin_loan_details(asset='BTC', txId='100001') +This for the cross-margin account by default. For isolated margin records, add the ``isolatedSymbol=symbol_name`` parameter. + `Get repay details `_ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -181,9 +250,13 @@ Loans details = client.get_margin_repay_details(asset='BTC', txId='100001') +This for the cross-margin account by default. For isolated margin records, add the ``isolatedSymbol=symbol_name`` parameter. + `Get max loan amount `_ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ .. code:: python details = client.get_max_margin_loan(asset='BTC') + +The max loan is for the cross-margin account by default. For isolated margin records, add the ``isolatedSymbol=symbol_name`` parameter. diff --git a/docs/websockets.rst b/docs/websockets.rst index 8bb364658..556fcea40 100644 --- a/docs/websockets.rst +++ b/docs/websockets.rst @@ -153,8 +153,8 @@ Valid interval values are `defined as enums `_. # set as 5000 to receive updates every 5 seconds conn_key = bm.start_miniticker_socket(process_message, 5000) -`User Socket `_ -+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +User Socket ++++++++++++ This watches for 3 different user events @@ -164,11 +164,33 @@ This watches for 3 different user events The Manager handles keeping the socket alive. +There are separate sockets for Spot, Cross-margin and separate Isolated margin accounts. + +`Spot trading `_ +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + .. code:: python bm.start_user_socket(process_message) +`Cross-margin `_ +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: python + + bm.start_margin_socket(process_message) + + +`Isolated margin `_ +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code:: python + + bm.start_isolated_margin_socket(symbol, process_message) + + + `Close a Socket `_ ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ diff --git a/requirements.txt b/requirements.txt index 1ca94f930..642a8d006 100644 --- a/requirements.txt +++ b/requirements.txt @@ -6,3 +6,4 @@ pyOpenSSL==19.0.0 requests==2.22.0 service-identity==17.0.0 Twisted==19.7.0 +ujson diff --git a/setup.py b/setup.py index dc5502716..9f61aa1e9 100644 --- a/setup.py +++ b/setup.py @@ -3,14 +3,15 @@ setup( name='python-binance', - version='0.7.5', + version='0.7.8', packages=['binance'], description='Binance REST API python implementation', url='https://github.com/sammchardy/python-binance', author='Sam McHardy', license='MIT', author_email='', - install_requires=['requests', 'six', 'Twisted', 'pyOpenSSL', 'autobahn', 'service-identity', 'dateparser', 'urllib3', 'certifi', 'cryptography', ], + install_requires=['requests', 'six', 'Twisted', 'pyOpenSSL', 'autobahn', 'service-identity', 'dateparser', + 'urllib3', 'certifi', 'cryptography', 'ujson'], keywords='binance exchange rest api bitcoin ethereum btc eth neo', classifiers=[ 'Intended Audience :: Developers',