### Install python-binance Source: https://github.com/sammchardy/python-binance/blob/master/PYPIREADME.rst Installs the python-binance library using pip. This is the first step to using the wrapper. ```bash pip install python-binance ``` -------------------------------- ### Manage Orders with Python Binance Source: https://context7.com/sammchardy/python-binance/llms.txt Provides examples for querying, cancelling, and managing orders using the python-binance library. This includes getting the status of a specific order, retrieving all open orders, fetching all historical orders, cancelling a single order, and cancelling all open orders for a symbol. Requires API key, secret, and order/symbol details. ```python from binance import Client client = Client(api_key='your_api_key', api_secret='your_api_secret') # Get specific order status order = client.get_order(symbol='BTCUSDT', orderId=12345678) print(f"Status: {order['status']}") print(f"Executed Qty: {order['executedQty']}") # Get all open orders open_orders = client.get_open_orders(symbol='BTCUSDT') for order in open_orders: print(f"Order {order['orderId']}: {order['side']} {order['origQty']} @ {order['price']}") # Get all orders (open, filled, cancelled) all_orders = client.get_all_orders(symbol='BTCUSDT', limit=50) # Cancel specific order result = client.cancel_order(symbol='BTCUSDT', orderId=12345678) print(f"Cancelled order status: {result['status']}") # Cancel all open orders for a symbol cancelled = client.cancel_all_open_orders(symbol='BTCUSDT') ``` -------------------------------- ### Start Sockets with ThreadedWebsocketManager Source: https://github.com/sammchardy/python-binance/blob/master/docs/websockets.rst Initialize ThreadedWebsocketManager with API keys if needed, start its internal loop, and then start individual or multiplexed sockets with a callback function. Use join() to keep the manager running. ```python import time from binance import ThreadedWebsocketManager api_key = '' api_secret = '' def main(): symbol = 'BNBBTC' twm = ThreadedWebsocketManager(api_key=api_key, api_secret=api_secret) # start is required to initialise its internal loop twm.start() def handle_socket_message(msg): print(f"message type: {msg['e']}") print(msg) twm.start_kline_socket(callback=handle_socket_message, symbol=symbol) # multiple sockets can be started twm.start_depth_socket(callback=handle_socket_message, symbol=symbol) # or a multiplex socket can be started like this # see Binance docs for stream names streams = ['bnbbtc@miniTicker', 'bnbbtc@bookTicker'] twm.start_multiplex_socket(callback=handle_socket_message, streams=streams) twm.join() if __name__ == "__main__": main() ``` -------------------------------- ### Initialize DepthCacheManager Source: https://github.com/sammchardy/python-binance/blob/master/docs/depth_cache.rst Examples of initializing the DepthCacheManager. One example sets a 1-hour refresh interval, while the other disables refreshing. ```python # 1 hour interval refresh dcm = DepthCacheManager(client, 'BNBBTC', refresh_interval=60*60) # disable refreshing dcm = DepthCacheManager(client, 'BNBBTC', refresh_interval=0) ``` -------------------------------- ### Start ThreadedDepthCacheManager and Handle Depth Cache Updates Source: https://github.com/sammchardy/python-binance/blob/master/docs/depth_cache.rst Initializes and starts the ThreadedDepthCacheManager, then sets up a callback to handle depth cache updates for specified symbols. Requires calling start() before initiating streams and join() to keep the manager running. ```python from binance import ThreadedDepthCacheManager def main(): dcm = ThreadedDepthCacheManager() # start is required to initialise its internal loop dcm.start() def handle_depth_cache(depth_cache): print(f"symbol {depth_cache.symbol}") print("top 5 bids") print(depth_cache.get_bids()[:5]) print("top 5 asks") print(depth_cache.get_asks()[:5]) print("last update time {}".format(depth_cache.update_time)) dcm_name = dcm.start_depth_cache(handle_depth_cache, symbol='BNBBTC') # multiple depth caches can be started dcm_name = dcm.start_depth_cache(handle_depth_cache, symbol='ETHBTC') dcm.join() if __name__ == "__main__": main() ``` -------------------------------- ### Start Kline Websocket Source: https://github.com/sammchardy/python-binance/blob/master/README.rst Starts a websocket connection to receive kline data for a specified symbol, using a provided callback function. ```python twm.start_kline_socket(callback=handle_socket_message, symbol='BNBBTC') ``` -------------------------------- ### Start Options Depth Cache Websocket Source: https://github.com/sammchardy/python-binance/blob/master/README.rst Starts a websocket connection to manage the depth cache for an options symbol, using a provided callback function. ```python # replace with a current options symbol options_symbol = 'BTC-241227-41000-C' dcm.start_options_depth_cache(callback=handle_dcm_message, symbol=options_symbol) ``` -------------------------------- ### Get Account API Trading Status Source: https://github.com/sammchardy/python-binance/blob/master/docs/account.rst Retrieve the trading status for your Binance API key. No specific setup is required beyond initializing the client. ```python status = client.get_account_api_trading_status() ``` -------------------------------- ### Get Historical Klines Source: https://github.com/sammchardy/python-binance/blob/master/llms.txt Fetch historical candlestick data (klines) for a given symbol, interval, and start time. The data includes open, high, low, close prices, and volume. ```python klines = client.get_historical_klines("BTCUSDT", Client.KLINE_INTERVAL_1HOUR, "1 day ago UTC") # Each kline: [open_time, open, high, low, close, volume, close_time, ...] ``` -------------------------------- ### Initialize Binance Client and Basic Operations Source: https://github.com/sammchardy/python-binance/blob/master/PYPIREADME.rst Demonstrates how to initialize the Binance API client with your API key and secret. It includes examples for fetching market depth, placing a test market order, retrieving all ticker prices, and handling potential API exceptions during withdrawal operations. ```python from binance import Client, ThreadedWebsocketManager, ThreadedDepthCacheManager from binance.exceptions import BinanceAPIException # Initialize the client # Replace 'api_key' and 'api_secret' with your actual keys client = Client("api_key", "api_secret") # Get market depth for a symbol depth = client.get_order_book(symbol='BNBBTC') print("Market Depth:", depth) # Place a test market buy order # For actual orders, use create_order function try: order = client.create_test_order( symbol='BNBBTC', side=Client.SIDE_BUY, type=Client.ORDER_TYPE_MARKET, quantity=100 ) print("Test Order Result:", order) except BinanceAPIException as e: print(f"Error placing test order: {e}") # Get all symbol prices prices = client.get_all_tickers() print("All Tickers:", prices) # Withdraw 100 ETH (example - requires actual address and may have specific assumptions) # Ensure you have the necessary permissions and have reviewed withdrawal assumptions in the documentation. try: # Replace '' with a valid Ethereum address result = client.withdraw( asset='ETH', address='', amount=100 ) print("Withdrawal Result:", result) print("Success") except BinanceAPIException as e: print(f"Withdrawal failed: {e}") # Fetch list of all withdrawals withdraws = client.get_withdraw_history() print("Withdrawal History:", withdraws) # Fetch list of ETH withdrawals eth_withdraws = client.get_withdraw_history(coin='ETH') print("ETH Withdrawal History:", eth_withdraws) # Get a deposit address for BTC address = client.get_deposit_address(coin='BTC') print("BTC Deposit Address:", address) # Fetch historical kline data (example - requires parameters like symbol, interval, start_str, end_str) # klines = client.get_historical_klines("BNBBTC", Client.KLINE_INTERVAL_1DAY, "1 Dec, 2017", "1 Jan, 2018") # print("Historical Klines:", klines) ``` -------------------------------- ### Asynchronous Client Initialization and Usage Source: https://github.com/sammchardy/python-binance/blob/master/docs/overview.rst Demonstrates how to initialize and use the asynchronous Binance client, including closing the connection. Requires asyncio. ```python import asyncio from binance.async_client import AsyncClient async def main(): client = await AsyncClient.create('', '') print(client.response.headers) await client.close_connection() if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(main()) ``` -------------------------------- ### Initialize Synchronous Client Source: https://context7.com/sammchardy/python-binance/llms.txt Demonstrates how to instantiate the Client class for synchronous API requests. Includes configurations for testnet, specific regions, RSA authentication, and demo trading modes. ```python from binance import Client from binance.exceptions import BinanceAPIException # Basic initialization client = Client(api_key='your_api_key', api_secret='your_api_secret') # Testnet environment client = Client(api_key='your_api_key', api_secret='your_api_secret', testnet=True) # US region with custom settings client = Client( api_key='your_api_key', api_secret='your_api_secret', tld='us', requests_params={'timeout': 20} ) # With RSA/Ed25519 key authentication client = Client( api_key='your_api_key', private_key='/path/to/private_key.pem', private_key_pass='optional_password' ) # Demo trading mode client = Client(api_key='your_api_key', api_secret='your_api_secret', demo=True) # With verbose logging for debugging client = Client(api_key='your_api_key', api_secret='your_api_secret', verbose=True) ``` -------------------------------- ### GET /api/v3/ticker Source: https://github.com/sammchardy/python-binance/blob/master/docs/market_data.rst Get the last price for all symbols. ```APIDOC ## GET /api/v3/ticker ### Description Retrieves the last price for all trading symbols. ### Method GET ### Endpoint /api/v3/ticker ### Parameters #### Query Parameters - **symbol** (string) - Optional - The trading pair (e.g., 'BNBBTC') ### Request Example ```python prices = client.get_all_tickers() ``` ### Response #### Success Response (200) - **symbol** (string) - Trading pair - **price** (string) - Last price #### Response Example ```json [ { "symbol": "BNBBTC", "price": "0.00000100" } ] ``` ``` -------------------------------- ### GET /api/v3/avgPrice Source: https://github.com/sammchardy/python-binance/blob/master/docs/market_data.rst Get the average price for a symbol. ```APIDOC ## GET /api/v3/avgPrice ### Description Retrieves the average price for a specified symbol over the last 24 hours. ### Method GET ### Endpoint /api/v3/avgPrice ### Parameters #### Query Parameters - **symbol** (string) - Required - The trading pair (e.g., 'BNBBTC') ### Request Example ```python avg_price = client.get_avg_price(symbol='BNBBTC') ``` ### Response #### Success Response (200) - **price** (string) - The average price #### Response Example ```json { "price": "0.01576000" } ``` ``` -------------------------------- ### Client Initialization with Custom Requests Parameters Source: https://github.com/sammchardy/python-binance/blob/master/docs/overview.rst Instantiate the Binance client with custom requests parameters like SSL verification and timeouts. These settings apply globally. ```python client = Client("api-key", "api-secret", {"verify": False, "timeout": 20}) ``` -------------------------------- ### Start Sockets with BinanceSocketManager Source: https://github.com/sammchardy/python-binance/blob/master/docs/websockets.rst Create a BinanceSocketManager instance with an AsyncClient, start desired sockets (e.g., trade_socket), and then use an async context manager to receive messages. ```python import asyncio from binance import AsyncClient, BinanceSocketManager async def main(): client = await AsyncClient.create() bm = BinanceSocketManager(client) # start any sockets here, i.e a trade socket ts = bm.trade_socket('BNBBTC') # then start receiving messages async with ts as tscm: while True: res = await tscm.recv() print(res) await client.close_connection() ``` -------------------------------- ### GET /api/v3/aggTrades Source: https://github.com/sammchardy/python-binance/blob/master/docs/market_data.rst Get aggregate trades for a symbol. ```APIDOC ## GET /api/v3/aggTrades ### Description Retrieves aggregate trades for a specified symbol. ### Method GET ### Endpoint /api/v3/aggTrades ### Parameters #### Query Parameters - **symbol** (string) - Required - The trading pair (e.g., 'BNBBTC') - **limit** (integer) - Optional - Default 500, Max 1000 - **fromId** (integer) - Optional - Aggregate trade id to fetch from - **startTime** (integer) - Optional - UTC timestamp in ms - **endTime** (integer) - Optional - UTC timestamp in ms ### Request Example ```python trades = client.get_aggregate_trades(symbol='BNBBTC') ``` ### Response #### Success Response (200) - **a** (integer) - Aggregate tradeId - **p** (string) - Price - **q** (string) - Quantity - **f** (integer) - First tradeId - **l** (integer) - Last tradeId - **T** (integer) - Timestamp - **m** (boolean) - Is the buyer the maker? - **M** (boolean) - Was the trade the best price match? #### Response Example ```json [ { "a": 584207, "p": "0.00000100", "q": "100.00000000", "f": 584190, "l": 584207, "T": 1575513591500, "m": true, "M": true } ] ``` ``` -------------------------------- ### GET /api/v3/historicalTrades Source: https://github.com/sammchardy/python-binance/blob/master/docs/market_data.rst Get historical trades for a symbol. ```APIDOC ## GET /api/v3/historicalTrades ### Description Retrieves historical trades for a specified symbol. ### Method GET ### Endpoint /api/v3/historicalTrades ### Parameters #### Query Parameters - **symbol** (string) - Required - The trading pair (e.g., 'BNBBTC') - **limit** (integer) - Optional - Default 500, Max 1000 - **fromId** (integer) - Optional - Trade id to fetch from ### Request Example ```python trades = client.get_historical_trades(symbol='BNBBTC') ``` ### Response #### Success Response (200) - **id** (integer) - Trade id - **price** (string) - Price - **qty** (string) - Quantity - **time** (integer) - Timestamp - **isBuyerMaker** (boolean) - If buyer is maker - **isBestMatch** (boolean) - If best match #### Response Example ```json [ { "id": 28457, "price": "4.00000100", "qty": "12.00000000", "time": 1575513591500, "isBuyerMaker": true, "isBestMatch": true } ] ``` ``` -------------------------------- ### Initialize Asynchronous Client Source: https://context7.com/sammchardy/python-binance/llms.txt Shows how to use the AsyncClient for non-blocking I/O operations. Requires an event loop and proper connection closure. ```python import asyncio from binance import AsyncClient async def main(): # Create async client client = await AsyncClient.create(api_key='your_api_key', api_secret='your_api_secret') # Make async API calls exchange_info = await client.get_exchange_info() ticker = await client.get_symbol_ticker(symbol='BTCUSDT') print(f"BTC/USDT Price: {ticker['price']}") # Always close connection when done await client.close_connection() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### GET /api/v3/depth Source: https://github.com/sammchardy/python-binance/blob/master/docs/market_data.rst Get market depth for a symbol. ```APIDOC ## GET /api/v3/depth ### Description Retrieves the order book for a specified symbol. ### Method GET ### Endpoint /api/v3/depth ### Parameters #### Query Parameters - **symbol** (string) - Required - The trading pair (e.g., 'BNBBTC') ### Request Example ```python depth = client.get_order_book(symbol='BNBBTC') ``` ### Response #### Success Response (200) - **lastUpdateId** (integer) - The last update ID - **bids** (list) - List of bid orders [price, quantity] - **asks** (list) - List of ask orders [price, quantity] #### Response Example ```json { "lastUpdateId": 1027024, "bids": [ ["4.00000000", "431.00000000"], ["3.99990000", "100.00000000"] ], "asks": [ ["4.00000100", "12.00000000"], ["4.00000200", "10.00000000"] ] } ``` ``` -------------------------------- ### Initialize AsyncClient and BinanceSocketManager with TLD Source: https://github.com/sammchardy/python-binance/blob/master/docs/websockets.rst Create an asynchronous client and socket manager using a specific TLD, ensuring the connection uses the correct domain. ```python from binance import AsyncClient, BinanceSocketManager async def x(): client = await AsyncClient.create(tld='us') bm = BinanceSocketManager(client) # start a socket... await client.close_connection() ``` -------------------------------- ### GET /eapi/v1/openInterest Source: https://github.com/sammchardy/python-binance/blob/master/Endpoints.md Gets open interest for EAPI. ```APIDOC ## GET /eapi/v1/openInterest ### Description Gets open interest for EAPI. ### Method GET ### Endpoint /eapi/v1/openInterest ### Parameters #### Query Parameters - **underlying** (str) - Required - The underlying asset. - **pair** (str) - Optional - The trading pair. ### Request Example ```python client.options_v1_get_open_interest(underlying='USDT') ``` ### Response #### Success Response (200) - **openInterestList** (list) - A list of open interest data. - **symbol** (str) - The trading symbol. - **openInterest** (str) - The open interest amount. - **totalSettleVolume** (str) - The total settlement volume. - **totalVolume** (str) - The total volume. - **timestamp** (int) - The timestamp. #### Response Example ```json { "openInterestList": [ { "symbol": "BTC-USDT", "openInterest": "10000.00", "totalSettleVolume": "50000.00", "totalVolume": "100000.00", "timestamp": 1678886400000 } ] } ``` ``` -------------------------------- ### Initialize Binance Client and Get Order Book Source: https://github.com/sammchardy/python-binance/blob/master/README.rst Initialize the Binance client with your API key and secret. Then, retrieve the order book for a specific symbol. Make sure to replace 'api_key' and 'api_secret' with your actual credentials. ```python from binance import Client, ThreadedWebsocketManager, ThreadedDepthCacheManager client = Client(api_key, api_secret) # get market depth depth = client.get_order_book(symbol='BNBBTC') ``` -------------------------------- ### Initialize Binance Client Source: https://github.com/sammchardy/python-binance/blob/master/llms.txt Set up synchronous and asynchronous clients for interacting with the Binance API. Supports testnet, demo trading, RSA key authentication, and different top-level domains (TLDs). ```python from binance import Client, AsyncClient # Basic setup client = Client(api_key, api_secret) # Async setup async_client = await AsyncClient.create(api_key, api_secret) # Testnet client = Client(api_key, api_secret, testnet=True) # Demo trading (paper trading) client = Client(api_key, api_secret, demo=True) # RSA key authentication client = Client(api_key, private_key=open("private_key.pem").read()) # Other TLD (e.g. Binance US) client = Client(api_key, api_secret, tld="us") ``` -------------------------------- ### GET /dapi/v1/trade/asyn Source: https://github.com/sammchardy/python-binance/blob/master/Endpoints.md Gets asynchronous trades for DAPI. ```APIDOC ## GET /dapi/v1/trade/asyn ### Description Gets asynchronous trades for DAPI. ### Method GET ### Endpoint /dapi/v1/trade/asyn ### Parameters #### Query Parameters - **symbol** (str) - Required - The trading symbol. - **limit** (int) - Optional - Default 500, max 1000. - **fromId** (int) - Optional - If provided, get trades newer than this id. - **startTime** (int) - Optional - Get trades with timestamp equal or greater than this value. - **endTime** (int) - Optional - Get trades with timestamp equal or less than this value. ### Request Example ```python client.futures_coin_v1_get_trade_asyn(symbol='BTCUSDT', limit=100) ``` ### Response #### Success Response (200) - **id** (int) - Trade ID. - **price** (str) - Trade price. - **qty** (str) - Trade quantity. - **quoteQty** (str) - Trade quote quantity. - **commission** (str) - Commission amount. - **commissionAsset** (str) - Commission asset. - **time** (int) - Trade time in milliseconds. - **isBuyer** (bool) - Whether the buyer is the maker. - **isMaker** (bool) - Whether the trade was made by the maker. - **orderId** (int) - Order ID. #### Response Example ```json [ { "id": 123456789, "price": "25000.00", "qty": "0.001", "quoteQty": "25.00", "commission": "0.00001", "commissionAsset": "USDT", "time": 1678886400000, "isBuyer": true, "isMaker": false, "orderId": 987654321 } ] ``` ``` -------------------------------- ### GET /papi/v1/um/adlQuantile Source: https://github.com/sammchardy/python-binance/blob/master/Endpoints.md Gets ADL quantile for U-Margin trading. ```APIDOC ## GET /papi/v1/um/adlQuantile ### Description Gets ADL (Auto-Deleveraging) quantile for U-Margin trading. ### Method GET ### Endpoint /papi/v1/um/adlQuantile ### Parameters #### Query Parameters - **symbol** (str) - Optional - Trading symbol. - **recvWindow ``` -------------------------------- ### Basic Logging Setup Source: https://github.com/sammchardy/python-binance/blob/master/docs/overview.rst Enables basic debug logging for the application by configuring the root logger level. ```python import logging logging.basicConfig(level=logging.DEBUG) ``` -------------------------------- ### Install Agent Skill (Project) Source: https://github.com/sammchardy/python-binance/blob/master/README.rst Command to install the python-binance agent skill into the current project using npm. This enables integration with various AI coding assistants. ```bash # Install into the current project npx -y skills add sammchardy/python-binance ``` -------------------------------- ### GET /sapi/v1/loan/vip/repay/history Source: https://github.com/sammchardy/python-binance/blob/master/Endpoints.md Gets VIP loan repayment history. ```APIDOC ## GET /sapi/v1/loan/vip/repay/history ### Description Gets VIP loan repayment history. ### Method GET ### Endpoint /sapi/v1/loan/vip/repay/history ### Parameters #### Query Parameters - **startTime** (int) - Optional - The start time to query. - **endTime** (int) - Optional - The end time to query. - **limit** (int) - Optional - Default 100, max 100. - **recvWindow** (int) - Optional - The receive window for the request. - **timestamp** (int) - Required - Server time. ### Request Example ```python client.margin_v1_get_loan_vip_repay_history(**params) ``` ### Response #### Success Response (200) - **list** (list) - A list of repayment history records. - **asset** (str) - The asset being repaid. - **amount** (str) - The amount repaid. - **principal** (str) - The principal amount. - **interest** (str) - The interest amount. - **repayTime** (int) - The repayment time. #### Response Example ```json { "list": [ { "asset": "USDT", "amount": "105.00", "principal": "100.00", "interest": "5.00", "repayTime": 1678886400000 } ] } ``` ``` -------------------------------- ### Using Binance Helper Functions Source: https://context7.com/sammchardy/python-binance/llms.txt Provides examples of utility functions for rounding order quantities to valid step sizes and converting date strings or intervals into millisecond timestamps. ```python from binance.helpers import round_step_size, date_to_milliseconds, interval_to_milliseconds # Round quantity to step size rounded = round_step_size(0.123456789, 0.001) print(f"Rounded quantity: {rounded}") # Convert date string to milliseconds timestamp = date_to_milliseconds("1 Jan, 2024") print(f"Timestamp: {timestamp}") # Convert interval to milliseconds ms = interval_to_milliseconds("1h") print(f"1 hour in ms: {ms}") ``` -------------------------------- ### GET /fapi/v1/accountConfig Source: https://github.com/sammchardy/python-binance/blob/master/Endpoints.md Gets account configuration for futures trading. ```APIDOC ## GET /fapi/v1/accountConfig ### Description Gets account configuration for futures trading. ### Method GET ### Endpoint /fapi/v1/accountConfig ### Parameters #### Query Parameters - **timestamp** (int) - Required - Server time. - **recvWindow** (int) - Optional - The receive window for the request. ### Request Example ```python client.futures_v1_get_account_config(**params) ``` ### Response #### Success Response (200) - ** acetonitrile** (str) - Account type. - **isLeverageTradingEnabled** (bool) - Whether leverage trading is enabled. #### Response Example ```json { " acetonitrile": "MARGIN_ACCOUNT", "isLeverageTradingEnabled": true } ``` ``` -------------------------------- ### Options V1 - Get Margin Account Source: https://github.com/sammchardy/python-binance/blob/master/llms-full.txt Get margin account. ```APIDOC ## GET /api/v1/options/v1/getMarginAccount ### Description Retrieves margin account information. ### Method GET ### Endpoint /api/v1/options/v1/getMarginAccount ### Parameters #### Path Parameters None #### Query Parameters - **params** (object) - Required - Additional parameters. ### Request Example ```json { "params": {} } ``` ### Response #### Success Response (200) - **data** (object) - Margin account details. #### Response Example ```json { "code": 200, "msg": "success", "data": { "marginLevel": "150.0", "availableBalance": "1000.0" } } ``` ``` -------------------------------- ### Initialize Synchronous Binance Client Source: https://github.com/sammchardy/python-binance/blob/master/docs/overview.rst Initialize the synchronous client with your API key and secret. ```python from binance.client import Client client = Client(api_key, api_secret) ``` -------------------------------- ### Options V1 - Get Income Asyn Source: https://github.com/sammchardy/python-binance/blob/master/llms-full.txt Get income asyn. ```APIDOC ## GET /api/v1/options/v1/getIncomeAsyn ### Description Retrieves asynchronous income data. ### Method GET ### Endpoint /api/v1/options/v1/getIncomeAsyn ### Parameters #### Path Parameters None #### Query Parameters - **params** (object) - Required - Additional parameters, potentially including symbol, startTime, endTime, etc. ### Request Example ```json { "params": { "symbol": "BTC-240628-10000-C", "startTime": 1678886400000 } } ``` ### Response #### Success Response (200) - **data** (object) - Asynchronous income data. #### Response Example ```json { "code": 200, "msg": "success", "data": [ { "symbol": "BTC-240628-10000-C", "income": "10.5" } ] } ``` ``` -------------------------------- ### Synchronous Client Initialization and Exchange Info Source: https://github.com/sammchardy/python-binance/blob/master/docs/overview.rst Shows how to create a synchronous Binance client and retrieve exchange information. Requires API keys. ```python from binance import Client api_key = '' api_secret = '' def main(): client = Client(api_key, api_secret) res = client.get_exchange_info() print(client.response.headers) if __name__ == "__main__": main() ``` -------------------------------- ### Async WebSocket Trade Stream Example Source: https://github.com/sammchardy/python-binance/blob/master/llms.txt Demonstrates asynchronous streaming of trade data using BinanceSocketManager. This example runs for 10 iterations and then closes the connection. ```python from binance import AsyncClient, BinanceSocketManager async def main(): client = await AsyncClient.create() bsm = BinanceSocketManager(client) async with bsm.trade_socket("BTCUSDT") as ts: for _ in range(10): msg = await ts.recv() print(msg) await client.close_connection() ``` -------------------------------- ### Options V1 - Get Exercise History Source: https://github.com/sammchardy/python-binance/blob/master/llms-full.txt Get exercise history. ```APIDOC ## GET /api/v1/options/v1/getExerciseHistory ### Description Retrieves exercise history. ### Method GET ### Endpoint /api/v1/options/v1/getExerciseHistory ### Parameters #### Path Parameters None #### Query Parameters - **params** (object) - Required - Additional parameters, potentially including symbol, startTime, endTime, etc. ### Request Example ```json { "params": { "symbol": "BTC-240628-10000-C", "startTime": 1678886400000 } } ``` ### Response #### Success Response (200) - **data** (object) - Exercise history details. #### Response Example ```json { "code": 200, "msg": "success", "data": [ { "symbol": "BTC-240628-10000-C", "exerciseTime": 1678886400000 } ] } ``` ``` -------------------------------- ### Options V1 - Get Countdown Cancel All Source: https://github.com/sammchardy/python-binance/blob/master/llms-full.txt Get countdown cancel all. ```APIDOC ## GET /api/v1/options/v1/getCountdownCancelAll ### Description Retrieves countdown cancellation information. ### Method GET ### Endpoint /api/v1/options/v1/getCountdownCancelAll ### Parameters #### Path Parameters None #### Query Parameters - **params** (object) - Required - Additional parameters. ### Request Example ```json { "params": { "symbol": "BTC-240628-10000-C" } } ``` ### Response #### Success Response (200) - **data** (object) - Countdown cancellation details. #### Response Example ```json { "code": 200, "msg": "success", "data": {} } ``` ``` -------------------------------- ### Advanced Logging Setup with Formatting Source: https://github.com/sammchardy/python-binance/blob/master/docs/overview.rst Configures detailed logging with timestamps, logger names, and log levels using Python's logging module. ```python import logging # Configure logging logging.basicConfig( level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', ) ``` -------------------------------- ### Options V1 - Get Block Trades Source: https://github.com/sammchardy/python-binance/blob/master/llms-full.txt Get block trades. ```APIDOC ## GET /api/v1/options/v1/getBlockTrades ### Description Retrieves block trades. ### Method GET ### Endpoint /api/v1/options/v1/getBlockTrades ### Parameters #### Path Parameters None #### Query Parameters - **params** (object) - Required - Additional parameters, potentially including symbol, startTime, endTime, etc. ### Request Example ```json { "params": { "symbol": "BTC-240628-10000-C", "startTime": 1678886400000 } } ``` ### Response #### Success Response (200) - **data** (object) - Information about block trades. #### Response Example ```json { "code": 200, "msg": "success", "data": [ { "orderId": "1234567890" } ] } ``` ``` -------------------------------- ### Stream Market Data with BinanceSocketManager Source: https://context7.com/sammchardy/python-binance/llms.txt Demonstrates how to use AsyncClient and BinanceSocketManager to stream trade, kline, multiplex, and depth data. This approach is ideal for high-performance applications requiring real-time updates. ```python import asyncio from binance import AsyncClient, BinanceSocketManager async def main(): client = await AsyncClient.create() bm = BinanceSocketManager(client) # Trade stream async with bm.trade_socket('BTCUSDT') as ts: for _ in range(10): msg = await ts.recv() print(f"Trade: Price={msg['p']}, Qty={msg['q']}") # Kline stream async with bm.kline_socket('BTCUSDT', interval='1m') as ks: for _ in range(5): msg = await ks.recv() kline = msg['k'] print(f"Kline Close: {kline['c']}") # Multiplex stream streams = ['btcusdt@trade', 'ethusdt@trade'] async with bm.multiplex_socket(streams) as ms: for _ in range(10): msg = await ms.recv() print(f"Stream: {msg['stream']}, Data: {msg['data']}") # Depth stream async with bm.depth_socket('BTCUSDT', depth=5) as ds: msg = await ds.recv() print(f"Top bid: {msg['bids'][0]}") print(f"Top ask: {msg['asks'][0]}") await client.close_connection() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### GET /api/v3/ticker/bookTicker Source: https://github.com/sammchardy/python-binance/blob/master/docs/market_data.rst Get best bid and ask price for all symbols. ```APIDOC ## GET /api/v3/ticker/bookTicker ### Description Retrieves the best bid and ask price for all trading symbols. ### Method GET ### Endpoint /api/v3/ticker/bookTicker ### Parameters #### Query Parameters - **symbol** (string) - Optional - The trading pair (e.g., 'BNBBTC') ### Request Example ```python tickers = client.get_orderbook_tickers() ``` ### Response #### Success Response (200) - **symbol** (string) - Trading pair - **bidPrice** (string) - Best bid price - **bidQty** (string) - Best bid quantity - **askPrice** (string) - Best ask price - **askQty** (string) - Best ask quantity #### Response Example ```json [ { "symbol": "BNBBTC", "bidPrice": "0.00000100", "bidQty": "20.00000000", "askPrice": "0.00000200", "askQty": "100.00000000" } ] ``` ``` -------------------------------- ### GET /sapi/v1/algo/spot/historicalOrders Source: https://github.com/sammchardy/python-binance/blob/master/Endpoints.md Gets historical orders for spot algorithmic trading. ```APIDOC ## GET /sapi/v1/algo/spot/historicalOrders ### Description Gets historical orders for spot algorithmic trading. ### Method GET ### Endpoint /sapi/v1/algo/spot/historicalOrders ### Parameters #### Query Parameters - **symbol** (str) - Optional - Trading symbol. - **orderType** (str) - Optional - Order type (e.g., STOP_LOSS, TAKE_PROFIT, TWAP). - **startTime** (int) - Optional - The start time to query. - **endTime** (int) - Optional - The end time to query. - **limit** (int) - Optional - Default 100, max 100. - **recvWindow** (int) - Optional - The receive window for the request. - **timestamp** (int) - Required - Server time. ### Request Example ```python client.margin_v1_get_algo_spot_historical_orders(symbol='BTCUSDT', orderType='TWAP') ``` ### Response #### Success Response (200) - **orderId** (int) - Order ID. - **symbol** (str) - Trading symbol. - **orderType** (str) - Order type. - **createTime** (int) - Order creation time. - **updateTime** (int) - Order update time. - **orderStatus** (str) - Order status. - **clientOwnId** (str) - Client own ID. #### Response Example ```json [ { "orderId": 123456789, "symbol": "BTCUSDT", "orderType": "TWAP", "createTime": 1678886400000, "updateTime": 1678886400000, "orderStatus": "FILLED", "clientOwnId": "my_algo_order_id" } ] ``` ``` -------------------------------- ### Initialize Synchronous Client for Testnet Source: https://github.com/sammchardy/python-binance/blob/master/docs/overview.rst Enable testnet mode by setting the testnet parameter to True when initializing the synchronous client. ```python client = Client(api_key, api_secret, testnet=True) ``` -------------------------------- ### Importing and Using Binance Client Constants Source: https://github.com/sammchardy/python-binance/blob/master/docs/constants.rst Demonstrates how to import the `Client` class from `binance.client` and use its constants, such as `SIDE_BUY`, in your Python code. ```python from binance.client import Client from binance.websockets import BinanceSocketManager side = Client.SIDE_BUY ``` -------------------------------- ### GET /papi/v1/margin/openOrderList Source: https://github.com/sammchardy/python-binance/blob/master/Endpoints.md Gets open order list for margin trading. ```APIDOC ## GET /papi/v1/margin/openOrderList ### Description Gets open order list for margin trading. ### Method GET ### Endpoint /papi/v1/margin/openOrderList ### Parameters #### Query Parameters - **symbol** (str) - Optional - Trading symbol. - **isIsolated** (str) - Optional - Whether it is isolated margin or not. - **recvWindow** (int) - Optional - The receive window for the request. - **timestamp** (int) - Required - Server time. ### Request Example ```python client.papi_v1_get_margin_open_order_list(symbol='BTCUSDT', isIsolated='TRUE') ``` ### Response #### Success Response (200) - **orderId** (int) - Order ID. - **orderListId** (int) - Order list ID. - **clientOrderId** (str) - Client order ID. - **transactTime** (int) - Transaction time. - **price** (str) - Order price. - **origQty** (str) - Original quantity. - **executedQty** (str) - Executed quantity. - **cummulativeQuoteQty** (str) - Cumulative quote quantity. - **status** (str) - Order status. - **timeInForce** (str) - Time in force. - **type** (str) - Order type. - **side** (str) - Order side. - **stopPrice** (str) - Stop price. - **icebergQty** (str) - Iceberg quantity. - **time** (int) - Order time. - **updateTime** (int) - Update time. - **isWorking** (bool) - Whether the order is working. - **origQuoteOrderQty** (str) - Original quote order quantity. #### Response Example ```json [ { "orderId": 123456789, "orderListId": 0, "clientOrderId": "my_order_id", "transactTime": 1678886400000, "price": "25000.00", "origQty": "0.001", "executedQty": "0.000", "cummulativeQuoteQty": "0.00", "status": "NEW", "timeInForce": "GTC", "type": "LIMIT", "side": "BUY", "stopPrice": "0.00000000", "icebergQty": "0.00000000", "time": 1678886400000, "updateTime": 1678886400000, "isWorking": true, "origQuoteOrderQty": "25.00" } ] ``` ``` -------------------------------- ### GET /sapi/v1/broker/subAccount/spotSummary Source: https://github.com/sammchardy/python-binance/blob/master/Endpoints.md Gets the spot summary for a broker's sub-account. ```APIDOC ## GET /sapi/v1/broker/subAccount/spotSummary ### Description Gets the spot summary for a broker's sub-account. ### Method GET ### Endpoint /sapi/v1/broker/subAccount/spotSummary ### Parameters #### Query Parameters - **subAccountApiKey** (str) - Required - The API key of the sub-account. - **recvWindow** (int) - Optional - The receive window for the request. - **timestamp** (int) - Required - Server time. ### Request Example ```python client.margin_v1_get_broker_sub_account_spot_summary(**params) ``` ### Response #### Success Response (200) - **spotSummaryList** (list) - A list of spot summary information. - **asset** (str) - The asset. - **free** (str) - The free balance. - **locked** (str) - The locked balance. - **freeze** (str) - The freeze balance. - **withdrawing** (str) - The withdrawing balance. - **ipoable** (str) - The IPOable balance. - **balance** (str) - The total balance. - **crossUnPnl** (str) - Unrealized PNL for cross margin. - **availableBalance** (str) - Available balance. - **marginAvailable** (bool) - Whether margin is available. - **updateTime** (int) - Update time. #### Response Example ```json { "spotSummaryList": [ { "asset": "USDT", "free": "100.00", "locked": "0.00", "freeze": "0.00", "withdrawing": "0.00", "ipoable": "0.00", "balance": "100.00", "crossUnPnl": "0.00", "availableBalance": "100.00", "marginAvailable": true, "updateTime": 1678886400000 } ] } ``` ``` -------------------------------- ### Initialize Asynchronous Binance Client Source: https://github.com/sammchardy/python-binance/blob/master/docs/overview.rst Initialize the asynchronous client within an asyncio event loop. ```python import asyncio from binance.client import AsyncClient async def main(): # initialise the client client = await AsyncClient.create(api_key, api_secret) if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(main()) ``` -------------------------------- ### Place and Manage Trading Orders Source: https://context7.com/sammchardy/python-binance/llms.txt Demonstrates how to create market, limit, and stop-loss orders. Includes error handling and the use of test orders to validate requests without execution. ```python try: order = client.create_order(symbol='BTCUSDT', side=SIDE_BUY, type=ORDER_TYPE_MARKET, quantity=0.001) test_order = client.create_test_order(symbol='BTCUSDT', side=SIDE_BUY, type=ORDER_TYPE_MARKET, quantity=0.001) except BinanceAPIException as e: print(f"Error: {e.code} - {e.message}") ``` -------------------------------- ### GET /dapi/v1/continuousKlines Source: https://github.com/sammchardy/python-binance/blob/master/Endpoints.md Gets continuous contract klines for the specified symbol. ```APIDOC ## GET /dapi/v1/continuousKlines ### Description Gets continuous contract klines for the specified symbol. ### Method GET ### Endpoint /dapi/v1/continuousKlines ### Parameters #### Query Parameters - **pair** (str) - Required - The trading pair (e.g., BTCUSD). - **contractType** (str) - Required - The contract type (e.g., PERPETUAL, CURRENT_MONTH, NEXT_MONTH). - **interval** (str) - Required - The interval of the klines (e.g., 1m, 5m, 1h, 1d). - **fromId** (int) - Optional - The ID of the starting kline. - **startTime** (int) - Optional - The start time in milliseconds. - **endTime** (int) - Optional - The end time in milliseconds. - **limit** (int) - Optional - Default 500, max 1000. ### Request Example ```python client.futures_coin_v1_get_continuous_klines(pair='BTCUSD', contractType='PERPETUAL', interval='1h') ``` ### Response #### Success Response (200) - **openTime** (int) - Open time in milliseconds. - **open** (str) - Open price. - **high** (str) - High price. - **low** (str) - Low price. - **close** (str) - Close price. - **volume** (str) - Volume. - **turnover** (str) - Turnover. - **tradeNum** (int) - Number of trades. - **takerBuyBaseAssetVolume** (str) - Volume of taker buys for the base asset. - **takerBuyQuoteAssetVolume** (str) - Volume of taker buys for the quote asset. #### Response Example ```json [ [ 1678886400000, "25000.00", "25100.00", "24900.00", "25050.00", "100.00", "2505000.00", 500, "50.00", "1252500.00" ] ] ``` ```