### Install python-binance Source: https://github.com/binance-exchange/python-binance/blob/master/docs/overview.rst Installs the python-binance library using pip. Ensure you have Python and pip installed. ```bash pip install python-binance ``` -------------------------------- ### Initialize Binance Client Source: https://github.com/binance-exchange/python-binance/blob/master/docs/overview.rst Initializes the Binance API client with your API key and secret. ```python from binance.client import Client client = Client(api_key, api_secret) ``` -------------------------------- ### Proxy Settings for Client Instantiation Source: https://github.com/binance-exchange/python-binance/blob/master/docs/overview.rst Configures proxy settings when initializing the Binance API client. ```python proxies = { 'http': 'http://10.10.1.10:3128', 'https': 'http://10.10.1.10:1080' } # in the Client instantiation client = Client("api-key", "api-secret", {'proxies': proxies}) ``` -------------------------------- ### Client Initialization with Custom Requests Parameters Source: https://github.com/binance-exchange/python-binance/blob/master/docs/overview.rst Initializes the Binance API client with custom request parameters like verification and timeout. ```python client = Client("api-key", "api-secret", {"verify": False, "timeout": 20}) ``` -------------------------------- ### Install python-binance Source: https://github.com/binance-exchange/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 ``` -------------------------------- ### Set Proxy Environment Variables (Windows) Source: https://github.com/binance-exchange/python-binance/blob/master/docs/overview.rst Sets HTTP and HTTPS proxy environment variables for Windows systems, affecting all requests made by the application. ```bash C:\>set HTTP_PROXY=http://10.10.1.10:3128 C:\>set HTTPS_PROXY=http://10.10.1.10:1080 ``` -------------------------------- ### Set Proxy Environment Variables (Linux) Source: https://github.com/binance-exchange/python-binance/blob/master/docs/overview.rst Sets HTTP and HTTPS proxy environment variables for Linux systems, affecting all requests made by the application. ```bash $ export HTTP_PROXY="http://10.10.1.10:3128" $ export HTTPS_PROXY="http://10.10.1.10:1080" ``` -------------------------------- ### Proxy Settings for Individual API Calls Source: https://github.com/binance-exchange/python-binance/blob/master/docs/overview.rst Applies proxy settings to a specific API call, overriding client-level configurations. ```python # or on an individual call client.get_all_orders(symbol='BNBBTC', requests_params={'proxies': proxies}) ``` -------------------------------- ### Initialize and Start Websocket Manager Source: https://github.com/binance-exchange/python-binance/blob/master/docs/websockets.rst Demonstrates how to create an instance of BinanceSocketManager, start a trade socket for a specific symbol, and then start the manager to begin receiving messages. A callback function is required to process incoming messages. ```python from binance.websockets import BinanceSocketManager # Assuming 'client' is an authenticated Binance API client instance # client = Client(api_key, api_secret) bm = BinanceSocketManager(client) def process_message(msg): print("message type: {}".format(msg['e'])) print(msg) # Process the message data here # Start a trade socket for the 'BNBBTC' symbol conn_key = bm.start_trade_socket('BNBBTC', process_message) # Start the socket manager bm.start() ``` -------------------------------- ### Twisted Installation on Windows Source: https://github.com/binance-exchange/python-binance/blob/master/docs/faqs.rst Addresses issues with installing the Twisted library using pip on Windows, specifically when build errors indicate the need for Microsoft Visual C++ Build Tools. It directs users to the Python Wiki for guidance on Windows compilers. ```python # To install Twisted on Windows if build errors occur: # Ensure Microsoft Visual C++ Build Tools are installed. # Refer to: https://wiki.python.org/moin/WindowsCompilers ``` -------------------------------- ### Override Request Parameters for a Specific API Call Source: https://github.com/binance-exchange/python-binance/blob/master/docs/overview.rst Demonstrates how to override default or client-level request parameters for a specific API call, such as setting a custom timeout for get_all_orders. ```python # this would result in verify: False and timeout: 5 for the get_all_orders call client = Client("api-key", "api-secret", {"verify": False, "timeout": 20}) client.get_all_orders(symbol='BNBBTC', requests_params={'timeout': 5}) ``` -------------------------------- ### Start Multiplexed Streams Source: https://github.com/binance-exchange/python-binance/blob/master/docs/changelog.rst Adds the `start_multiplex_socket` function to `BinanceSocketManager` for creating and managing multiplexed websocket streams. ```python from binance import BinanceSocketManager bsm = BinanceSocketManager(client) conn_key = bsmsm.start_multiplex_socket(callback=handle_socket_message, streams=['!ticker@arr', 'btcusdt@depth']) bsm.join(conn_key) ``` -------------------------------- ### Get All Ticker Prices Source: https://github.com/binance-exchange/python-binance/blob/master/PYPIREADME.rst Retrieves a list of all symbol prices available on the Binance exchange. ```python # get all symbol prices prices = client.get_all_tickers() ``` -------------------------------- ### Start User Socket Source: https://github.com/binance-exchange/python-binance/blob/master/docs/websockets.rst Starts a websocket connection to monitor user-specific events, including account updates, order updates, and trade updates. The manager handles maintaining the connection. ```python bm.start_user_socket(process_message) ``` -------------------------------- ### Place a Test Market Order Source: https://github.com/binance-exchange/python-binance/blob/master/PYPIREADME.rst Shows how to place a test market buy order. For actual orders, use the `create_order` function. This example uses constants for side and order type. ```python order = client.create_test_order( symbol='BNBBTC', side=Client.SIDE_BUY, type=Client.ORDER_TYPE_MARKET, quantity=100 ) ``` -------------------------------- ### Wait for Depth Cache Socket to Start Source: https://github.com/binance-exchange/python-binance/blob/master/docs/changelog.rst Ensures the depth cache socket is properly started before fetching order book data, improving reliability. ```python from binance.depthcache import DepthCacheManager dcm = DepthCacheManager(client) dcm.start() dcm.join() order_book = dcm.get_order_book('BTCUSDT') ``` -------------------------------- ### Initialize Binance Client and Get Order Book Source: https://github.com/binance-exchange/python-binance/blob/master/PYPIREADME.rst Demonstrates how to initialize the Binance client with API keys and retrieve the order book for a specific symbol (BNBBTC). ```python from binance.client import Client client = Client(api_key, api_secret) # get market depth depth = client.get_order_book(symbol='BNBBTC') ``` -------------------------------- ### Start Mini Ticker Socket Source: https://github.com/binance-exchange/python-binance/blob/master/docs/websockets.rst Starts a websocket connection to receive mini-ticker updates. Updates can be received every second by default or at a specified interval (in milliseconds). ```python bm.start_miniticker_socket(process_message) bm.start_miniticker_socket(process_message, 5000) ``` -------------------------------- ### Get Account Information Source: https://github.com/binance-exchange/python-binance/blob/master/docs/account.rst Fetches comprehensive account information, including balances, trading status, and permissions. ```python info = client.get_account() ``` -------------------------------- ### Get Deposit Address Source: https://github.com/binance-exchange/python-binance/blob/master/PYPIREADME.rst Fetches the deposit address for a specified asset (e.g., BTC). ```python # get a deposit address for BTC address = client.get_deposit_address(asset='BTC') ``` -------------------------------- ### Start Trade Socket Source: https://github.com/binance-exchange/python-binance/blob/master/docs/websockets.rst Subscribes to real-time trade data for a specified symbol. Each trade executed on the exchange will be sent through this stream. ```python conn_key = bm.start_trade_socket('BNBBTC', process_message) ``` -------------------------------- ### Start Ticker Socket Source: https://github.com/binance-exchange/python-binance/blob/master/docs/websockets.rst Subscribes to ticker information for all trading pairs. This stream provides rolling window statistics for each symbol. ```python conn_key = bm.start_ticker_socket(process_message) ``` -------------------------------- ### Get Products (Deprecated) Source: https://github.com/binance-exchange/python-binance/blob/master/docs/general.rst Retrieves a list of available trading products. This endpoint is deprecated and users should use the `get_exchange_info` endpoint instead. ```python products = client.get_products() ``` -------------------------------- ### Start Aggregated Trade Websocket Source: https://github.com/binance-exchange/python-binance/blob/master/PYPIREADME.rst Initiates a websocket connection to receive real-time aggregated trade data for a given symbol (BNBBTC). Includes a callback function to process incoming messages. ```python # start aggregated trade websocket for BNBBTC def process_message(msg): print("message type: {}".format(msg['e'])) print(msg) # do something from binance.websockets import BinanceSocketManager bm = BinanceSocketManager(client) bm.start_aggtrade_socket('BNBBTC', process_message) bm.start() ``` -------------------------------- ### Binance API Documentation Source: https://github.com/binance-exchange/python-binance/blob/master/docs/index.rst This section consolidates various API endpoints and methods provided by the python-binance library. It includes details on authentication, market data retrieval, order management, account information, and websocket connections. Each entry details the method signature, parameters, return values, and usage examples. ```APIDOC Binance API Endpoints: Market Data: get_symbol_ticker(symbol=None) - Get the latest ticker for a symbol or all symbols. - Parameters: - symbol (str, optional): The trading pair (e.g., 'BTCUSDT'). - Returns: Ticker information. get_klines(symbol, interval, startTime=None, endTime=None, limit=None) - Get candlestick data for a symbol. - Parameters: - symbol (str): The trading pair. - interval (str): The interval for the candlesticks (e.g., '1m', '1h', '1d'). - startTime (int, optional): Start time in milliseconds. - endTime (int, optional): End time in milliseconds. - limit (int, optional): Maximum number of klines to return. - Returns: List of candlestick data. Account Management: get_account() - Get account information. - Returns: Account details including balances. create_order(symbol, side, type, timeInForce, quantity, price=None, **params) - Create a new order. - Parameters: - symbol (str): The trading pair. - side (str): 'BUY' or 'SELL'. - type (str): Order type (e.g., 'LIMIT', 'MARKET'). - timeInForce (str): Order time in force (e.g., 'GTC', 'IOC'). - quantity (float): The quantity to trade. - price (float, optional): The price for limit orders. - **params: Additional parameters for the order. - Returns: Order information. Websockets: start_symbol_miniticker_socket(callback, symbol) - Start a websocket for mini ticker updates for a symbol. - Parameters: - callback (function): Function to call with received data. - symbol (str): The trading pair. - Returns: WebSocket connection object. start_kline_socket(callback, symbol, interval) - Start a websocket for kline updates. - Parameters: - callback (function): Function to call with received data. - symbol (str): The trading pair. - interval (str): The candlestick interval. - Returns: WebSocket connection object. Error Handling: BinanceAPIException: Custom exception for API errors. BinanceOrderException: Custom exception for order errors. General Usage: Client(api_key, api_secret) - Initialize the Binance client. - Parameters: - api_key (str): Your Binance API key. - api_secret (str): Your Binance API secret. - Returns: Binance API client instance. ``` -------------------------------- ### Start Depth Socket (Diff and Partial Book) Source: https://github.com/binance-exchange/python-binance/blob/master/docs/websockets.rst Demonstrates how to subscribe to depth stream updates. It supports receiving either the default difference (diff) response or a partial order book snapshot by specifying a depth level. ```python from binance.enums import * # Start a depth socket for diff response diff_key = bm.start_depth_socket('BNBBTC', process_message) # Start a depth socket for a partial book response (e.g., top 5 levels) partial_key = bm.start_depth_socket('BNBBTC', process_message, depth=BinanceSocketManager.WEBSOCKET_DEPTH_5) ``` -------------------------------- ### Updated Documentation and Small Bugfix Source: https://github.com/binance-exchange/python-binance/blob/master/docs/changelog.rst Contains updated documentation to provide clearer explanations and examples. Also includes a small bugfix to address a minor issue within the library. ```python # Updated documentation # Small bugfix ``` -------------------------------- ### Get Open Orders Source: https://github.com/binance-exchange/python-binance/blob/master/docs/account.rst Retrieves a list of all currently open orders for a given symbol. Requires the symbol. ```python orders = client.get_open_orders(symbol='BNBBTC') ``` -------------------------------- ### Get Asset Balance Helper Function Source: https://github.com/binance-exchange/python-binance/blob/master/docs/changelog.rst Introduces `get_asset_balance` as a helper function to efficiently retrieve the balance for a specific asset. ```python balance = client.get_asset_balance(asset='BTC') print(balance) ``` -------------------------------- ### Get Symbol Info Function Source: https://github.com/binance-exchange/python-binance/blob/master/docs/changelog.rst Introduces the `get_symbol_info` function to easily retrieve detailed information about a specific trading symbol. ```python symbol_info = client.get_symbol_info('BTCUSDT') print(symbol_info) ``` -------------------------------- ### Get System Status Source: https://github.com/binance-exchange/python-binance/blob/master/docs/general.rst Fetches the current system status of the Binance exchange. It indicates whether the system is operational or undergoing maintenance. ```python status = client.get_system_status() ``` -------------------------------- ### Get All Prices Source: https://github.com/binance-exchange/python-binance/blob/master/docs/market_data.rst Fetches the last price for all trading symbols on Binance. This provides a quick overview of current market prices. ```python prices = client.get_all_tickers() ``` -------------------------------- ### Get Account Status Source: https://github.com/binance-exchange/python-binance/blob/master/docs/account.rst Fetches the status of the user's account, indicating if it's active or has any restrictions. ```python status = client.get_account_status() ``` -------------------------------- ### Get Orderbook Tickers Source: https://github.com/binance-exchange/python-binance/blob/master/docs/market_data.rst Retrieves the first bid and ask entry from the order book for all symbols. This offers a snapshot of the best bid and ask prices. ```python tickers = client.get_orderbook_tickers() ``` -------------------------------- ### Get My Trades Source: https://github.com/binance-exchange/python-binance/blob/master/docs/account.rst Retrieves a list of trades executed by the authenticated account for a given symbol. Requires the symbol. ```python trades = client.get_my_trades(symbol='BNBBTC') ``` -------------------------------- ### Start Aggregated Trade Socket Source: https://github.com/binance-exchange/python-binance/blob/master/docs/websockets.rst Subscribes to aggregated trade data for a specified symbol. This stream combines trades that occurred within the same second. ```python conn_key = bm.start_aggtrade_socket('BNBBTC', process_message) ``` -------------------------------- ### Start Kline Socket Source: https://github.com/binance-exchange/python-binance/blob/master/docs/websockets.rst Allows subscribing to candlestick (kline) data for a given symbol. An optional interval parameter can be provided to specify the kline interval, defaulting to 1 minute. ```python from binance.enums import * # Start a kline socket for BNBBTC with 30-minute intervals conn_key = bm.start_kline_socket('BNBBTC', process_message, interval=KLINE_INTERVAL_30MINUTE) ``` -------------------------------- ### Get Exchange Information Source: https://github.com/binance-exchange/python-binance/blob/master/docs/general.rst Retrieves comprehensive information about the Binance exchange, including trading rules, symbols, and filters. This is a foundational call for many trading operations. ```python info = client.get_exchange_info() ``` -------------------------------- ### Start Symbol Ticker Socket Source: https://github.com/binance-exchange/python-binance/blob/master/docs/websockets.rst Subscribes to the latest symbol ticker information for a specific trading pair. This includes the last price, price change, etc. ```python conn_key = bm.start_symbol_ticker_socket('BNBBTC', process_message) ``` -------------------------------- ### Get Asset Balance Source: https://github.com/binance-exchange/python-binance/blob/master/docs/account.rst Retrieves the balance for a specific asset. Requires the asset symbol (e.g., 'BTC', 'ETH'). ```python balance = client.get_asset_balance(asset='BTC') ``` -------------------------------- ### Get Server Time Source: https://github.com/binance-exchange/python-binance/blob/master/docs/general.rst Retrieves the current server time from Binance. This is useful for synchronizing client-side clocks with the exchange. ```python time_res = client.get_server_time() ``` -------------------------------- ### Get Historical Klines for Any Date Range Source: https://github.com/binance-exchange/python-binance/blob/master/docs/changelog.rst Enhances `get_historical_klines` to fetch klines for any specified date range, addressing issues with response limits and interval logic. ```python klines = client.get_historical_klines('BNBBTC', '1h', '1 week ago UTC') ``` -------------------------------- ### Get Recent Trades Source: https://github.com/binance-exchange/python-binance/blob/master/docs/market_data.rst Fetches recent trades for a given symbol. This includes the price, quantity, and time of each trade. ```python trades = client.get_recent_trades(symbol='BNBBTC') ``` -------------------------------- ### Start Multiplex Socket Source: https://github.com/binance-exchange/python-binance/blob/master/docs/websockets.rst Enables the creation of a single socket connection to receive data from multiple streams simultaneously. This includes streams like aggregated trades, tickers, and depth, but excludes user streams. Stream names must be in lowercase. ```python def process_m_message(msg): print("stream: {} data: {}".format(msg['stream'], msg['data'])) # Start a multiplex socket with 'bnbbtc@aggTrade' and 'neobtc@ticker' streams conn_key = bm.start_multiplex_socket(['bnbbtc@aggTrade', 'neobtc@ticker'], process_m_message) ``` -------------------------------- ### Get Market Depth Source: https://github.com/binance-exchange/python-binance/blob/master/docs/market_data.rst Retrieves the order book for a specified symbol. This endpoint provides bid and ask prices and quantities. ```python depth = client.get_order_book(symbol='BNBBTC') ``` -------------------------------- ### Get Symbol Information Source: https://github.com/binance-exchange/python-binance/blob/master/docs/general.rst Fetches detailed information for a specific trading symbol on the Binance exchange. This includes details like price filters, lot size filters, and more. ```python info = client.get_symbol_info('BNBBTC') ``` -------------------------------- ### Process Depth Cache Updates Source: https://github.com/binance-exchange/python-binance/blob/master/docs/depth_cache.rst An example callback function that processes depth cache updates. It prints the symbol and the top 5 bids and asks from the provided DepthCache object. Handles cases where the depth_cache might be None due to errors. ```python def process_depth(depth_cache): if depth_cache is not None: print("symbol {}".format(depth_cache.symbol)) print("top 5 bids") print(depth_cache.get_bids()[:5]) print("top 5 asks") print(depth_cache.get_asks()[:5]) else: # depth cache had an error and needs to be restarted ``` -------------------------------- ### Fetch Historical Kline Data Source: https://github.com/binance-exchange/python-binance/blob/master/PYPIREADME.rst Provides functions to fetch historical kline (candlestick) data for various intervals and date ranges. Examples include fetching 1-minute klines for the last day, 30-minute klines for a specific month in 2017, and weekly klines since listing. ```python # get historical kline data from any date range # fetch 1 minute klines for the last day up until now klines = client.get_historical_klines("BNBBTC", Client.KLINE_INTERVAL_1MINUTE, "1 day ago UTC") # fetch 30 minute klines for the last month of 2017 klines = client.get_historical_klines("ETHBTC", Client.KLINE_INTERVAL_30MINUTE, "1 Dec, 2017", "1 Jan, 2018") # fetch weekly klines since it listed klines = client.get_historical_klines("NEOBTC", KLINE_INTERVAL_1WEEK, "1 Jan, 2017") ``` -------------------------------- ### Deposit Address and Withdraw Endpoint Upgrades Source: https://github.com/binance-exchange/python-binance/blob/master/docs/changelog.rst Adds an endpoint for getting deposit addresses and upgrades the withdraw endpoints to version 3. It also introduces a new exchange info endpoint with rate limit and full symbol details. ```python # Added Get deposit address endpoint # Upgraded withdraw endpoints to v3 # New exchange info endpoint with rate limits and full symbol info ``` -------------------------------- ### Get Aggregate Trades Source: https://github.com/binance-exchange/python-binance/blob/master/docs/market_data.rst Fetches aggregated trades for a symbol. Aggregated trades combine multiple trades into a single entry, showing the total quantity and average price. ```python trades = client.get_aggregate_trades(symbol='BNBBTC') ``` -------------------------------- ### Withdraw Funds with Exception Handling Source: https://github.com/binance-exchange/python-binance/blob/master/PYPIREADME.rst Demonstrates how to withdraw funds (e.g., ETH) and includes robust exception handling for Binance API errors and withdrawal-specific errors. ```python # withdraw 100 ETH # check docs for assumptions around withdrawals from binance.exceptions import BinanceAPIException, BinanceWithdrawException try: result = client.withdraw( asset='ETH', address='', amount=100) except BinanceAPIException as e: print(e) except BinanceWithdrawException as e: print(e) else: print("Success") ``` -------------------------------- ### Binance API General Endpoints Source: https://github.com/binance-exchange/python-binance/blob/master/docs/general.rst Provides an overview of general endpoints for the Binance API, including methods for pinging the server, retrieving server time, system status, exchange information, symbol-specific information, and product listings. ```APIDOC Client: ping(): description: Pings the server to check connectivity. returns: Empty response if successful. get_server_time(): description: Retrieves the current server time. returns: timestamp: Server timestamp in milliseconds. get_system_status(): description: Gets the current system status. returns: status: Integer representing system status (0: normal, 1: maintenance). msg: String message indicating system status ('normal' or 'System maintenance.'). get_exchange_info(): description: Retrieves comprehensive exchange information, including symbols, filters, and rates. returns: exchangeInfo: Object containing exchange details. get_symbol_info(symbol: str): description: Gets detailed information for a specific trading symbol. parameters: symbol: The trading symbol (e.g., 'BNBBTC'). returns: symbolInfo: Object containing symbol-specific details. get_products(): description: Deprecated. Retrieves a list of available trading products. Use get_exchange_info instead. returns: products: List of product information. ``` -------------------------------- ### Binance API Documentation Overview Source: https://github.com/binance-exchange/python-binance/blob/master/docs/binance.rst This section outlines the structure and modules available within the Binance API Python library. It details the purpose of each module, including client interactions, depth caching, exception handling, helper utilities, and WebSocket connectivity. ```APIDOC Binance API =========== client module ---------------------- .. automodule:: binance.client :members: :undoc-members: :show-inheritance: depthcache module -------------------------- .. automodule:: binance.depthcache :members: :undoc-members: :show-inheritance: exceptions module -------------------------- .. automodule:: binance.exceptions :members: :undoc-members: :show-inheritance: helpers module -------------------------- .. automodule:: binance.helpers :members: :undoc-members: :show-inheritance: websockets module -------------------------- .. automodule:: binance.websockets :members: :undoc-members: :show-inheritance: ``` -------------------------------- ### Get Withdraw Fee Source: https://github.com/binance-exchange/python-binance/blob/master/docs/changelog.rst Adds the `get_withdraw_fee` function to retrieve withdrawal fees for various assets. ```python fees = client.get_withdraw_fee() print(fees) ``` -------------------------------- ### Place Helper Limit Order Source: https://github.com/binance-exchange/python-binance/blob/master/docs/account.rst Uses helper functions to simplify placing limit buy or sell orders. Specify the symbol, quantity, and price. ```python order = client.order_limit_buy( symbol='BNBBTC', quantity=100, price='0.00001') order = client.order_limit_sell( symbol='BNBBTC', quantity=100, price='0.00001') ``` -------------------------------- ### Get Account Status Function Source: https://github.com/binance-exchange/python-binance/blob/master/docs/changelog.rst Adds the `get_account_status` function to retrieve the current status of the user's account. ```python account_status = client.get_account_status() print(account_status) ``` -------------------------------- ### Initialize DepthCacheManager Source: https://github.com/binance-exchange/python-binance/blob/master/docs/depth_cache.rst Demonstrates how to create an instance of DepthCacheManager to track depth updates for a symbol. It accepts the API client, symbol, and an optional callback function. ```python from binance.depthcache import DepthCacheManager dcm = DepthCacheManager(client, 'BNBBTC', callback=process_depth) ``` -------------------------------- ### General, Market Data, and Account Endpoints Source: https://github.com/binance-exchange/python-binance/blob/master/docs/changelog.rst Initial release includes foundational endpoints for general operations, market data retrieval, and account management, setting the stage for the library's core functionalities. ```python # General, Market Data and Account endpoints ``` -------------------------------- ### Place Market Order Source: https://github.com/binance-exchange/python-binance/blob/master/docs/account.rst Uses helper functions to simplify placing market buy or sell orders. Specify the symbol and quantity. ```python order = client.order_market_buy( symbol='BNBBTC', quantity=100) order = client.order_market_sell( symbol='BNBBTC', quantity=100) ``` -------------------------------- ### Ticker Calls and FAQs Source: https://github.com/binance-exchange/python-binance/blob/master/docs/changelog.rst Adds calls for `get_all_tickers` and `get_orderbook_tickers` to retrieve market data. Also includes some frequently asked questions (FAQs) to assist users. ```python # Added get_all_tickers call # Added get_orderbook_tickers call # Added some FAQs ``` -------------------------------- ### Get Historical Klines with Millisecond Timestamps Source: https://github.com/binance-exchange/python-binance/blob/master/docs/changelog.rst Adds millisecond precision to the timestamp parameter for the `get_historical_klines` function, allowing for more granular historical data retrieval. ```python client.get_historical_klines(symbol='BTCUSDT', interval='1h', start_str='2023-01-01 00:00:00', end_str='2023-01-01 01:00:00', limit=500) ``` -------------------------------- ### Stop Individual Socket Source: https://github.com/binance-exchange/python-binance/blob/master/docs/websockets.rst Stops a specific websocket connection using its connection key. The connection key is returned when the socket is initially started. ```python bm.stop_socket(conn_key) ``` -------------------------------- ### Binance Helper Functions API Documentation Source: https://github.com/binance-exchange/python-binance/blob/master/docs/helpers.rst API documentation for helper functions in the binance.helpers module. These functions assist in converting date formats and time intervals into milliseconds, which are commonly used in API requests. ```APIDOC binance.helpers: date_to_milliseconds(date: Union[datetime, str, int]) -> int Converts a date (datetime object, string, or integer timestamp) to milliseconds since the epoch. Parameters: date: The date to convert. Can be a datetime object, a string in a recognizable format, or an integer timestamp. Returns: The date represented as milliseconds since the epoch. interval_to_milliseconds(interval: str) -> int Converts a Binance interval string (e.g., '1m', '1h', '1d') to milliseconds. Parameters: interval: The Binance interval string. Returns: The interval in milliseconds. Raises: ValueError: If the interval string is not recognized. ``` -------------------------------- ### Place Limit Order Source: https://github.com/binance-exchange/python-binance/blob/master/docs/account.rst Places a limit order on the exchange. Users can specify the symbol, side (buy/sell), quantity, price, and time-in-force. ```python from binance.enums import * order = client.create_order( symbol='BNBBTC', side=SIDE_BUY, type=ORDER_TYPE_LIMIT, timeInForce=TIME_IN_FORCE_GTC, quantity=100, price='0.00001') ``` -------------------------------- ### Get Withdraw Fee Source: https://github.com/binance-exchange/python-binance/blob/master/docs/withdraw.rst Retrieves the current withdrawal fee for a specified asset. This helps in calculating the cost of withdrawing funds. ```python address = client.get_withdraw_fee(asset='BTC') ``` -------------------------------- ### Get Deposit Address Source: https://github.com/binance-exchange/python-binance/blob/master/docs/withdraw.rst Retrieves the deposit address for a specified asset. This address can be used to deposit funds into the Binance account. ```python address = client.get_deposit_address(asset='BTC') ``` -------------------------------- ### Fetch All Orders Source: https://github.com/binance-exchange/python-binance/blob/master/docs/account.rst Retrieves a list of all orders for a given symbol, with an option to limit the number of results. Requires a valid client instance. ```python orders = client.get_all_orders(symbol='BNBBTC', limit=10) ``` -------------------------------- ### Binance API Endpoints - Orders Source: https://github.com/binance-exchange/python-binance/blob/master/docs/account.rst Provides access to order-related endpoints for the Binance API. Includes functionalities for fetching, placing, and managing orders. ```APIDOC GET /api/v3/order Get an order Parameters: - symbol (string, required): The trading pair, e.g., 'BNBUSDT'. - orderId (long, optional): Order ID. - origClientOrderId (string, optional): Client order ID. - recvWindow (long, optional): The request was processed after this time. - timestamp (long, required): UTC timestamp in ms POST /api/v3/order/test Test new order Parameters: - symbol (string, required) - side (enum, required): BUY or SELL. - type (enum, required): Order type: LIMIT, MARKET, STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, TAKE_PROFIT_LIMIT, LIMIT_MAKER. - timeInForce (enum, optional): GTC, IOC, or FOK. - quantity (decimal, required) - price (decimal, optional) - newClientOrderId (string, optional): Used to uniquely identify this order. POST /api/v3/order Place a new order Parameters: - symbol (string, required) - side (enum, required): BUY or SELL. - type (enum, required): Order type: LIMIT, MARKET, STOP_LOSS, STOP_LOSS_LIMIT, TAKE_PROFIT, TAKE_PROFIT_LIMIT, LIMIT_MAKER. - timeInForce (enum, optional): GTC, IOC, or FOK. - quantity (decimal, required) - price (decimal, optional) - newClientOrderId (string, optional): Used to uniquely identify this order. DELETE /api/v3/order Cancel an order Parameters: - symbol (string, required) - orderId (long, optional) - origClientOrderId (string, optional) - newClientOrderId (string, optional): Used to uniquely identify this cancellation request. - timestamp (long, required) GET /api/v3/openOrders Get all open orders Parameters: - symbol (string, optional) - timestamp (long, required) GET /api/v3/allOrders Get all orders for a given symbol Parameters: - symbol (string, required) - orderId (long, optional) - startTime (long, optional) - endTime (long, optional) - limit (int, optional): Default 100, Max 1000 - timestamp (long, required) ``` -------------------------------- ### Get Historical Trades Source: https://github.com/binance-exchange/python-binance/blob/master/docs/market_data.rst Retrieves historical trades for a symbol. This endpoint is useful for analyzing past trading activity. ```python trades = client.get_historical_trades(symbol='BNBBTC') ``` -------------------------------- ### Handling BinanceAPIException Source: https://github.com/binance-exchange/python-binance/blob/master/docs/exceptions.rst Demonstrates how to catch and handle a BinanceAPIException, accessing its attributes like status_code and message. ```python try: client.get_all_orders() except BinanceAPIException as e: print(e.status_code) print(e.message) ``` -------------------------------- ### Travis CI, Coveralls, and Pair Validation Source: https://github.com/binance-exchange/python-binance/blob/master/docs/changelog.rst Adds support for Travis CI and Coveralls for continuous integration and testing. Also includes validation for trading pairs using the public endpoint. ```python # Travis.CI and Coveralls support # Validation for pairs using public endpoint ``` -------------------------------- ### Stop All Sockets and Close Manager Source: https://github.com/binance-exchange/python-binance/blob/master/docs/websockets.rst Closes all active websocket connections and terminates the BinanceSocketManager. A new 'start' call is required to establish any subsequent connections. ```python bm.close() ``` -------------------------------- ### Place Test Order Source: https://github.com/binance-exchange/python-binance/blob/master/docs/account.rst Creates and validates a new order without sending it to the exchange. Useful for testing order parameters. Requires specifying symbol, side, type, timeInForce, quantity, and price. ```python from binance.enums import * order = client.create_test_order( symbol='BNBBTC', side=SIDE_BUY, type=ORDER_TYPE_LIMIT, timeInForce=TIME_IN_FORCE_GTC, quantity=100, price='0.00001') ``` -------------------------------- ### Discontinuation Notice Source: https://github.com/binance-exchange/python-binance/blob/master/README.md This snippet informs users about the discontinuation of the python-binance library and provides a link to the recommended alternative. ```Markdown # Discontinue this Library The support to this library is scheduled to be discontinued, and it will be offline within the next six months. Please consider this offically supported Python library available at https://github.com/binance/binance-connector-python ``` -------------------------------- ### Get Kline/Candlesticks Source: https://github.com/binance-exchange/python-binance/blob/master/docs/market_data.rst Retrieves Kline (candlestick) data for a symbol and interval. Candlesticks represent price movements over a specific time period. ```python candles = client.get_klines(symbol='BNBBTC', interval=Client.KLINE_INTERVAL_30MINUTE) ``` -------------------------------- ### Get Historical Kline/Candlesticks Source: https://github.com/binance-exchange/python-binance/blob/master/docs/market_data.rst Fetches historical Kline (candlestick) data for any date range and interval. This is useful for backtesting and historical analysis. ```python # fetch 1 minute klines for the last day up until now klines = client.get_historical_klines("BNBBTC", Client.KLINE_INTERVAL_1MINUTE, "1 day ago UTC") # fetch 30 minute klines for the last month of 2017 klines = client.get_historical_klines("ETHBTC", Client.KLINE_INTERVAL_30MINUTE, "1 Dec, 2017", "1 Jan, 2018") # fetch weekly klines since it listed klines = client.get_historical_klines("NEOBTC", KLINE_INTERVAL_1WEEK, "1 Jan, 2017") ``` -------------------------------- ### Create Order with Asset Parameter Source: https://github.com/binance-exchange/python-binance/blob/master/docs/changelog.rst Updates the `create_order` function to accept an `asset` parameter, which is used if the `name` parameter is not provided. ```python client.create_order(symbol='BTCUSDT', side='BUY', type='LIMIT', timeInForce='GTC', quantity=0.01, price=10000, asset='BTC') ``` -------------------------------- ### Depth and Interval Parameters for Sockets Source: https://github.com/binance-exchange/python-binance/blob/master/docs/changelog.rst Introduces the 'depth' parameter for depth sockets and the 'interval' parameter for kline sockets. Also adds update time parameters, new enums for socket values, and improves websocket documentation. ```python # depth parameter to depth socket # interval parameter to kline socket # update time parameter for compatible sockets # new enums for socket depth and update time values # better websocket documentation ``` -------------------------------- ### Mini Ticker Socket Source: https://github.com/binance-exchange/python-binance/blob/master/docs/changelog.rst Adds the `start_miniticker_socket` function to subscribe to mini ticker updates for all symbols. ```python from binance import BinanceSocketManager bsm = BinanceSocketManager(client) conn_key = bsmsm.start_miniticker_socket(callback=handle_socket_message) bsm.join(conn_key) ``` -------------------------------- ### Binance API Endpoints - Account Source: https://github.com/binance-exchange/python-binance/blob/master/docs/account.rst Provides access to account-related endpoints for the Binance API. Includes functionalities for retrieving account information, balances, and trade history. ```APIDOC GET /api/v3/account Get account information Parameters: - timestamp (long, required) - recvWindow (long, optional) GET /api/v3/account/status Get account status Parameters: - timestamp (long, required) GET /api/v3/asset/balance Get asset balance for a specific asset Parameters: - asset (string, required) - timestamp (long, required) GET /api/v3/myTrades Get trades for a specific account and symbol Parameters: - symbol (string, required) - limit (int, optional): Default 100, Max 1000 - fromId (long, optional): Trade id to fetch from - startTime (long, optional) - endTime (long, optional) - timestamp (long, required) ``` -------------------------------- ### Get 24hr Ticker Source: https://github.com/binance-exchange/python-binance/blob/master/docs/market_data.rst Retrieves the 24-hour ticker price change statistics for all symbols. This includes high, low, price change, and volume information. ```python tickers = client.get_ticker() ``` -------------------------------- ### BNB Market Support and New Market Type Handling Source: https://github.com/binance-exchange/python-binance/blob/master/docs/changelog.rst Adds support for the BNB market and includes a fix for errors that occurred when encountering new market types not previously known to the library. ```python # support for BNB market # fixed error if new market type is created that we don't know about ``` -------------------------------- ### Exit Program with Twisted Reactor Source: https://github.com/binance-exchange/python-binance/blob/master/docs/websockets.rst Provides instructions on how to properly exit a program that uses the Twisted reactor for websockets. It ensures the reactor loop is stopped to allow the program to terminate. ```python from twisted.internet import reactor # program code here # when you need to exit reactor.stop() ``` -------------------------------- ### Aggregate Trade Iterator Source: https://github.com/binance-exchange/python-binance/blob/master/docs/market_data.rst Provides an iterator to fetch aggregate trades for a symbol, starting from a specific time or order ID. This is efficient for processing large amounts of trade data. ```python agg_trades = client.aggregate_trade_iter(symbol='ETHBTC', start_str='30 minutes ago UTC') # iterate over the trade iterator for trade in agg_trades: print(trade) # do something with the trade data # convert the iterator to a list # note: generators can only be iterated over once so we need to call it again agg_trades = client.aggregate_trade_iter(symbol='ETHBTC', '30 minutes ago UTC') agg_trade_list = list(agg_trades) # example using last_id value agg_trades = client.aggregate_trade_iter(symbol='ETHBTC', last_id=23380478) agg_trade_list = list(agg_trades) ``` -------------------------------- ### System Status Endpoint Source: https://github.com/binance-exchange/python-binance/blob/master/docs/changelog.rst Introduces the `get_system_status` function to fetch the current system status of the Binance exchange. ```python status = client.get_system_status() print(status) ``` -------------------------------- ### Fetch Withdrawal History Source: https://github.com/binance-exchange/python-binance/blob/master/PYPIREADME.rst Retrieves the withdrawal history, with an option to filter by asset (e.g., ETH). ```python # fetch list of withdrawals withdraws = client.get_withdraw_history() # fetch list of ETH withdrawals eth_withdraws = client.get_withdraw_history(asset='ETH') ``` -------------------------------- ### Fetch Deposit History Source: https://github.com/binance-exchange/python-binance/blob/master/docs/withdraw.rst Fetches the deposit history for all assets or a specific asset. Returns a list of deposit records. ```python deposits = client.get_deposit_history() btc_deposits = client.get_deposit_history(asset='BTC') ``` -------------------------------- ### Retrieve Current Depth Cache Source: https://github.com/binance-exchange/python-binance/blob/master/docs/depth_cache.rst Illustrates how to get the current DepthCache object from the DepthCacheManager at any time. This allows direct access to the latest order book data, including bids and asks. It also includes error handling for when the cache is unavailable. ```python depth_cache = dcm.get_depth_cache() if depth_cache is not None: print("symbol {}".format(depth_cache.symbol)) print("top 5 bids") print(depth_cache.get_bids()[:5]) print("top 5 asks") print(depth_cache.get_asks()[:5]) else: # depth cache had an error and needs to be restarted ``` -------------------------------- ### Upgrade to v3 Signed Endpoints and Function Documentation Source: https://github.com/binance-exchange/python-binance/blob/master/docs/changelog.rst Upgrades the library to use v3 signed endpoints for increased security and functionality. Also updates the function documentation to reflect these changes. ```python # Upgrade to v3 signed endpoints # Update function documentation ``` -------------------------------- ### Place Withdrawal Source: https://github.com/binance-exchange/python-binance/blob/master/docs/withdraw.rst Places a withdrawal request for a specified asset, address, and amount. Requires withdrawal permissions for the API key and prior email confirmation for the withdrawal. Handles BinanceAPIException and BinanceWithdrawException. ```python from binance.exceptions import BinanceAPIException, BinanceWithdrawException try: # name parameter will be set to the asset value by the client if not passed result = client.withdraw( asset='ETH', address='', amount=100) except BinanceAPIException as e: print(e) except BinanceWithdrawException as e: print(e) else: print("Success") # passing a name parameter result = client.withdraw( asset='ETH', address='', amount=100, name='Withdraw') # if the coin requires a extra tag or name such as XRP or XMR then pass an `addressTag` parameter. result = client.withdraw( asset='XRP', address='', addressTag='', amount=10000) ``` -------------------------------- ### Websocket Manager and Order Validation Source: https://github.com/binance-exchange/python-binance/blob/master/docs/changelog.rst Introduces the Websocket manager for real-time data streams. Also adds order parameter validation and defines Order and Symbol enums for better data handling. Includes API Endpoints for Data Streams. ```python # Websocket manager # Order parameter validation # Order and Symbol enums # API Endpoints for Data Streams ``` -------------------------------- ### Format Amount String Source: https://github.com/binance-exchange/python-binance/blob/master/docs/account.rst Formats a floating-point amount to a string with a specified precision. This is useful for ensuring correct formatting for exchange API requests. ```python amount = 0.000234234 precision = 5 amt_str = "{:0.0{}f}".format(amount, precision) ``` -------------------------------- ### Fetch Withdraw History Source: https://github.com/binance-exchange/python-binance/blob/master/docs/withdraw.rst Fetches the withdrawal history for all assets or a specific asset. Returns a list of withdrawal records. ```python withdraws = client.get_withdraw_history() btc_withdraws = client.get_withdraw_history(asset='BTC') ``` -------------------------------- ### Depth Cache Initialization Fix Source: https://github.com/binance-exchange/python-binance/blob/master/docs/changelog.rst Resolves an issue where multiple depth caches were sharing a single cache. This fix ensures that bid and ask objects are initialized independently for each depth cache. ```python # Fix multiple depth caches sharing a cache by initialising bid and ask objects each time ``` -------------------------------- ### Depth Cache Manager and Connection Key Source: https://github.com/binance-exchange/python-binance/blob/master/docs/changelog.rst The Depth Cache Manager now utilizes a 0ms socket update time. Additionally, a connection key is returned upon socket creation, which is then used to stop the socket. ```python # Depth Cache Manager uses 0ms socket update time # connection key returned when creating socket, this key is then used to stop it ``` -------------------------------- ### Withdraw Endpoints and Order Helper Functions Source: https://github.com/binance-exchange/python-binance/blob/master/docs/changelog.rst Adds new withdraw endpoints and helper functions for managing orders. This enhances the library's capabilities for executing and managing trades. ```python # Withdraw endpoints # Order helper functions ``` -------------------------------- ### Websocket Restart and Exception Handling Source: https://github.com/binance-exchange/python-binance/blob/master/docs/changelog.rst Addresses issues with stopping and restarting websockets, preventing them from reconnecting unexpectedly. It also includes a fix for exceptions that occurred when parsing non-JSON websocket messages. ```python # Fixed stopping sockets where they were reconnecting # Fixed websockets unable to be restarted after close # Exception in parsing non-JSON websocket message ```