### Installing Binance Futures WebSocket Library - Bash Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/docs/guides/getting_started.md This snippet demonstrates how to install the `binance-futures-websocket` library using pip, the Python package installer. It's the first step to set up the environment for using the library and ensures all necessary dependencies are met. ```bash pip install binance-futures-websocket ``` -------------------------------- ### Placing Market Order via WebSocket API - Python Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/docs/guides/getting_started.md This example shows how to initialize `BinanceClient`, connect to the WebSocket API using an API key and private key, and then place a market buy order for BTCUSDT. It demonstrates basic order placement, asynchronous execution, and proper connection closure using `asyncio.run`. ```python import asyncio from binance_futures_async import BinanceClient from binance_futures_async.exceptions import ConnectionError, AuthenticationError async def main(): # Initialize the client client = BinanceClient() # Connect to WebSocket API ws_service = await client.websocket_service( api_key='your_api_key', private_key_path='path/to/your/key' # .pem file or HMAC secret ) # Place a market order try: response = await ws_service.place_market_order( symbol="BTCUSDT", side="BUY", quantity="0.001" ) print(f"Order placed: {response}") finally: await ws_service.close() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Subscribing to User Data Stream - Python Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/docs/guides/getting_started.md This example demonstrates how to initialize and subscribe to a user data stream to receive account updates. It requires an API key and a message handler to process incoming user-specific data, maintaining the connection indefinitely until explicitly stopped. ```python from binance_futures_async import BinanceClient def handle_user_data(message): print(f"Received user data: {message}") async def main(): client = BinanceClient() # Initialize user data stream user_stream = await client.user_stream( api_key='your_api_key', message_handler=handle_user_data ) # Keep the connection alive try: while True: await asyncio.sleep(1) finally: await user_stream.stop() ``` -------------------------------- ### Implementing Comprehensive Error Handling - Python Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/docs/guides/getting_started.md This example demonstrates best practices for error handling within the `binance-futures-async` library. It shows how to catch specific exceptions like `ConnectionError`, `AuthenticationError`, `RequestError`, and `UserStreamError` to provide targeted feedback, along with a general `Exception` catch-all for unexpected issues. ```python from binance_futures_async.exceptions import ( ConnectionError, AuthenticationError, RequestError, UserStreamError ) async def main(): try: # Your code here pass except ConnectionError as e: print(f"Connection error: {e}") except AuthenticationError as e: print(f"Authentication failed: {e}") except RequestError as e: print(f"Request failed: {e}") except UserStreamError as e: print(f"User stream error: {e}") except Exception as e: print(f"Unexpected error: {e}") ``` -------------------------------- ### Installing Binance Futures Async Library - Bash Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/README.md This snippet provides the command to install the `binance-futures-async` Python library using pip, the standard package installer for Python. This is the first step to set up the environment before using the library's functionalities. ```bash pip install binance-futures-async ``` -------------------------------- ### Subscribing to Market Data Streams - Python Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/docs/guides/getting_started.md This snippet illustrates how to set up a market data stream using `BinanceClient`. It defines a handler function for incoming messages and subscribes to 1-minute kline data for BTCUSDT, ensuring the connection remains active by sleeping indefinitely until closed. ```python from binance_futures_async import BinanceClient def handle_market_data(message): print(f"Received market data: {message}") async def main(): client = BinanceClient() # Initialize market streams market_service = await client.market_service( message_handler=handle_market_data ) # Subscribe to various data streams await market_service.subscribe_kline( symbols=["BTCUSDT"], intervals=["1m"] ) # Keep the connection alive try: while True: await asyncio.sleep(1) finally: await market_service.close() ``` -------------------------------- ### Installing Binance Futures Async Library - Bash Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/docs/index.md This snippet demonstrates how to install the `binance-futures-async` Python library using pip, the standard package installer for Python. This command should be run in a terminal or command prompt to make the library available for use in Python projects. ```bash pip install binance-futures-async ``` -------------------------------- ### Complete Binance Futures Async Client Usage Example Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/docs/api/market_service.md A comprehensive example demonstrating how to initialize the BinanceClient, connect to the market service, subscribe to multiple data streams (kline, mark price, aggregate trade), and handle incoming market data messages. It also includes error handling for connection and request issues. ```python import asyncio from binance_futures_async import BinanceClient from binance_futures_async.exceptions import ConnectionError, RequestError async def handle_market_data(message: Dict[str, Any]): """Process incoming market data messages.""" if message.get('e') == 'kline': # Handle kline/candlestick update kline = message['k'] print(f"Kline update for {message['s']}:") print(f"Interval: {kline['i']}") print(f"Close: {kline['c']}") elif message.get('e') == 'aggTrade': # Handle aggregate trade print(f"Trade: {message['s']} Price: {message['p']}") elif message.get('e') == 'markPrice': # Handle mark price update print(f"Mark price: {message['s']} Price: {message['p']}") async def main(): client = BinanceClient() market_service = None try: # Initialize market service market_service = await client.market_service( message_handler=handle_market_data ) # Subscribe to multiple data streams await market_service.subscribe_kline( symbols=["BTCUSDT"], intervals=["1m", "5m"] ) await market_service.subscribe_mark_price( symbols=["BTCUSDT"], update_speed="1000ms" ) await market_service.subscribe_aggregate_trade( symbols=["BTCUSDT"] ) # Keep the connection alive while True: await asyncio.sleep(1) except ConnectionError as e: print(f"Connection error: {e}") except RequestError as e: print(f"Request error: {e}") except Exception as e: print(f"Unexpected error: {e}") finally: if market_service: await market_service.close() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Example Usage of WebSocket Service in Python Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/docs/api/client.md This example demonstrates how to initialize and use the `websocket_service` method of the `BinanceClient`. It shows how to pass the API key, private key path, enable validation, and override default configuration settings. ```python client = BinanceClient() ws_service = await client.websocket_service( api_key="your_api_key", private_key_path="path/to/your/key", enable_validation=True, config={ 'connection_timeout': 60, 'request_timeout': 15 } ) ``` -------------------------------- ### Example Usage of Market Service in Python Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/docs/api/client.md This example demonstrates how to initialize and use the `market_service` method of the `BinanceClient`. It shows how to define a message handler function and pass it along with custom configuration for the ping interval. ```python def handle_market_data(message): print(f"Received market data: {message}") client = BinanceClient() market_service = await client.market_service( message_handler=handle_market_data, config={ 'ping_interval': 300 } ) ``` -------------------------------- ### Implementing Market Data Message Handlers - Python Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/docs/guides/getting_started.md This snippet provides a detailed example of how to implement message handlers for market data streams. It shows how to dispatch messages based on `event_type` (e.g., 'kline', 'aggTrade', 'markPrice') and specifically how to parse and print kline data, extracting symbol, interval, and OHLC values. ```python def handle_market_data(message): # Handle different message types event_type = message.get('e') if event_type == 'kline': handle_kline(message) elif event_type == 'aggTrade': handle_aggtrade(message) elif event_type == 'markPrice': handle_markprice(message) def handle_kline(message): k = message['k'] print(f"Symbol: {message['s']}") print(f"Interval: {k['i']}") print(f"Open: {k['o']}") print(f"High: {k['h']}") print(f"Low: {k['l']}") print(f"Close: {k['c']}") ``` -------------------------------- ### Example: Subscribing to Mark Price Stream (Python) Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/docs/api/market_service.md This example shows how to subscribe to mark price updates for 'BTCUSDT' and 'ETHUSDT' with a faster update speed of '1000ms'. The `symbols` parameter takes a list of trading pairs, and `update_speed` specifies the desired frequency. ```Python await market_service.subscribe_mark_price( symbols=["BTCUSDT", "ETHUSDT"], update_speed="1000ms" ) ``` -------------------------------- ### Example: Subscribing to Kline Stream (Python) Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/docs/api/market_service.md This example demonstrates how to subscribe to kline updates for 'BTCUSDT' across '1m', '5m', and '1h' intervals. The `symbols` parameter specifies the trading pair, and `intervals` is a list of desired candlestick timeframes. ```Python await market_service.subscribe_kline( symbols=["BTCUSDT"], intervals=["1m", "5m", "1h"] ) ``` -------------------------------- ### Placing Market and Limit Orders with Binance Futures Async (Python) Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/docs/guides/examples.md This snippet demonstrates how to establish a WebSocket connection using `BinanceClient` and place basic market and limit orders on Binance Futures. It shows how to specify the trading symbol, side (BUY/SELL), quantity, and for limit orders, the price and `timeInForce`. Dependencies: `asyncio`, `binance_futures_async`. ```Python import asyncio from binance_futures_async import BinanceClient from binance_futures_async.exceptions import ConnectionError, RequestError async def basic_orders(): client = BinanceClient() ws_service = None try: ws_service = await client.websocket_service( api_key='your_api_key', private_key_path='path/to/your/key' ) # Place a market order market_order = await ws_service.place_market_order( symbol="BTCUSDT", side="BUY", quantity="0.001" ) print(f"Market order placed: {market_order}") # Place a limit order limit_order = await ws_service.place_limit_order( symbol="BTCUSDT", side="BUY", quantity="0.001", price="50000", timeInForce="GTC" ) print(f"Limit order placed: {limit_order}") finally: if ws_service: await ws_service.close() if __name__ == "__main__": asyncio.run(basic_orders()) ``` -------------------------------- ### Complete Binance Futures Async Client Usage Example in Python Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/docs/api/websocket_service.md This comprehensive example showcases the full workflow of interacting with the Binance Futures API using the `binance_futures_async` library. It covers initializing the client, establishing a WebSocket connection, logging in, retrieving account and position information, placing various order types (limit, stop market, take profit market), and implementing robust error handling for common exceptions like connection, authentication, request, and order validation errors. ```python import asyncio from binance_futures_async import BinanceClient from binance_futures_async.exceptions import ( ConnectionError, AuthenticationError, RequestError, OrderValidationError ) async def main(): client = BinanceClient() ws_service = None try: # Initialize service ws_service = await client.websocket_service( api_key="your_api_key", private_key_path="path/to/your/key", enable_validation=True ) # Connect and login (Ed25519 only) await ws_service.login() # Get account information balance = await ws_service.get_account_balance() positions = await ws_service.get_position_info() # Place orders limit_order = await ws_service.place_limit_order( symbol="BTCUSDT", side="BUY", quantity="0.001", price="50000", timeInForce="GTC" ) stop_loss = await ws_service.place_stop_market_order( symbol="BTCUSDT", side="SELL", quantity="0.001", stopPrice="48000" ) take_profit = await ws_service.place_take_profit_market_order( symbol="BTCUSDT", side="SELL", quantity="0.001", stopPrice="52000" ) except ConnectionError as e: print(f"Connection error: {e}") except AuthenticationError as e: print(f"Authentication error: {e}") except RequestError as e: print(f"Request error: {e}") except OrderValidationError as e: print(f"Order validation error: {e}") finally: if ws_service: await ws_service.close() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Example: Subscribing to Aggregate Trade Stream (Python) Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/docs/api/market_service.md This example demonstrates how to subscribe to aggregate trade updates for 'BTCUSDT' and 'ETHUSDT' using the `MarketService` instance. The `symbols` parameter takes a list of strings representing the desired trading pairs. ```Python await market_service.subscribe_aggregate_trade(["BTCUSDT", "ETHUSDT"]) ``` -------------------------------- ### Placing Advanced Order Types (Stop Loss, Take Profit, Trailing Stop) with Binance Futures Async (Python) Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/docs/guides/examples.md This example illustrates how to place more complex order types, including stop-loss, take-profit, and trailing stop market orders, using the Binance Futures WebSocket service. It demonstrates the use of `stopPrice` for stop-loss/take-profit and `callbackRate` for trailing stops. Dependencies: `asyncio`, `binance_futures_async`. ```Python async def advanced_orders(): client = BinanceClient() ws_service = None try: ws_service = await client.websocket_service( api_key='your_api_key', private_key_path='path/to/your/key' ) # Place a stop-loss order stop_loss = await ws_service.place_stop_market_order( symbol="BTCUSDT", side="SELL", quantity="0.001", stopPrice="45000" ) print(f"Stop-loss order placed: {stop_loss}") # Place a take-profit order take_profit = await ws_service.place_take_profit_market_order( symbol="BTCUSDT", side="SELL", quantity="0.001", stopPrice="55000" ) print(f"Take-profit order placed: {take_profit}") # Place a trailing stop order trailing_stop = await ws_service.place_trailing_stop_market_order( symbol="BTCUSDT", side="SELL", quantity="0.001", callbackRate="1.0" # 1% callback rate ) print(f"Trailing stop order placed: {trailing_stop}") finally: if ws_service: await ws_service.close() ``` -------------------------------- ### Connecting to Binance Futures WebSocket API and Getting Balance - Python Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/docs/index.md This Python example demonstrates how to establish an asynchronous connection to the Binance Futures WebSocket API using `BinanceClient`, authenticate with provided API credentials, and retrieve the account balance. It includes robust error handling for connection, authentication, and request issues, ensuring the WebSocket service is properly closed upon completion or error. ```python import asyncio from binance_futures_async import BinanceClient from binance_futures_async.exceptions import ConnectionError, AuthenticationError, RequestError async def main(): client = BinanceClient() ws_service = None try: # Connect to WebSocket API with your credentials ws_service = await client.websocket_service( api_key='your_api_key', private_key_path='path/to/your/key' ) # Get account balance balance = await ws_service.get_account_balance() print(f'Account balance: {balance}') except Exception as e: print(f'Error: {e}') finally: if ws_service: await ws_service.close() if __name__ == '__main__': asyncio.run(main()) ``` -------------------------------- ### Example: Retrieving Account Balance Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/docs/api/websocket_service.md This example demonstrates how to call the `get_account_balance` method to retrieve the current account balance information. The result is stored in the `balance` variable. ```python balance = await ws_service.get_account_balance() ``` -------------------------------- ### Example: Retrieving Account Status Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/docs/api/websocket_service.md This example demonstrates how to call the `get_account_status` method to retrieve the current account status information. The result is stored in the `status` variable. ```python status = await ws_service.get_account_status() ``` -------------------------------- ### Example: Retrieving Ticker Book for BTCUSDT Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/docs/api/websocket_service.md This example demonstrates how to call the `get_ticker_book` method to retrieve the best bid and ask prices for the 'BTCUSDT' trading pair. The result is stored in the `book_ticker` variable. ```python book_ticker = await ws_service.get_ticker_book("BTCUSDT") ``` -------------------------------- ### Example Usage of User Data Stream in Python Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/docs/api/client.md This example demonstrates how to initialize and use the `user_stream` method of the `BinanceClient`. It shows how to define a message handler function and pass it along with the API key and custom configuration for the health check interval. ```python def handle_user_data(message): print(f"Received user data: {message}") client = BinanceClient() user_stream = await client.user_stream( api_key="your_api_key", message_handler=handle_user_data, config={ 'health_check_interval': 30 } ) ``` -------------------------------- ### Example: Subscribing to Continuous Contract Kline Stream (Python) Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/docs/api/market_service.md This example shows how to subscribe to continuous contract kline updates for 'BTCUSDT' perpetual contracts at '1m' and '5m' intervals. It specifies the trading pair, contract type, and desired kline intervals. ```Python await market_service.subscribe_continuous_kline( pairs=["BTCUSDT"], contract_types=["perpetual"], intervals=["1m", "5m"] ) ``` -------------------------------- ### Placing a Limit Order using Binance Futures WebSocket API - Python Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/README.md This example demonstrates how to connect to the Binance Futures WebSocket API using `BinanceClient` and place a limit order for a specified symbol, quantity, and price. It includes error handling for connection, authentication, and request errors, ensuring robust order placement. ```python import asyncio from binance_futures_async import BinanceClient from binance_futures_async.exceptions import ConnectionError, AuthenticationError, RequestError async def main(): client = BinanceClient() ws_service = None try: # Connect to WebSocket API with your credentials ws_service = await client.websocket_service( api_key="your_api_key", private_key_path="path/to/your/key" # Can be: # - ED25519: path to .pem file # - RSA: path to .pem file # - HMAC: your secret key as string ) # Place a limit order for BTC response = await ws_service.place_limit_order( symbol="BTCUSDT", side="BUY", quantity="0.001", price="50000", timeInForce="GTC" ) print(f"Order placed: {response}") except ConnectionError as e: print(f"Connection error: {e}") except AuthenticationError as e: print(f"Authentication error: {e}") except RequestError as e: print(f"Request error: {e}") except Exception as e: print(f"Unexpected error: {e}") finally: if ws_service: await ws_service.close() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Overriding Default Configurations for Binance Futures Async Services (Python) Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/README.md This example illustrates how to customize service configurations by passing a `config` dictionary during initialization. It demonstrates overriding `return_rate_limits`, `connection_timeout`, and `request_timeout` for the WebSocket API, and `ping_interval` and `max_reconnect_attempts` for the Market Streams. ```Python from binance_futures_async import BinanceClient async def main(): client = BinanceClient() # WebSocket API with custom config ws_service = await client.websocket_service( api_key="your_api_key", private_key_path="path/to/your/key", config={ 'return_rate_limits': False, # Disable rate limit info 'connection_timeout': 60, # Longer timeout 'request_timeout': 15 # Shorter request timeout } ) # Market Streams with custom config market_service = await client.market_service( message_handler=handle_market_data, config={ 'ping_interval': 300, # Longer ping interval 'max_reconnect_attempts': 10 # More reconnection attempts } ) ``` -------------------------------- ### Example: Retrieving Position Info for Single and All Symbols Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/docs/api/websocket_service.md These examples illustrate how to use `get_position_info` to fetch position details for a specific symbol ('BTCUSDT') and how to retrieve information for all open positions by omitting the `symbol` parameter. The results are stored in `btc_position` and `all_positions` respectively. ```python # Single symbol position btc_position = await ws_service.get_position_info("BTCUSDT") # All positions all_positions = await ws_service.get_position_info() ``` -------------------------------- ### Example: Subscribing to Partial Book Depth for BTCUSDT Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/docs/api/market_service.md Demonstrates how to call the `subscribe_partial_book_depth` method to receive partial order book updates for the BTCUSDT symbol, specifying 10 levels of depth and an update speed of 100ms. ```python await market_service.subscribe_partial_book_depth( symbols=["BTCUSDT"], levels=10, update_speed=100 ) ``` -------------------------------- ### Complete Binance Futures User Data Stream Example - Python Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/docs/api/user_data_stream.md This comprehensive example demonstrates how to set up a real-time user data stream with Binance Futures using the `binance-futures-async` library. It defines a `UserDataHandler` class to process various stream events like account updates, order updates, and position updates, maintaining local state for balances, positions, and orders. The `main` asynchronous function initializes the `BinanceClient`, connects to the user stream with a custom message handler, configures health checks, and includes robust error handling for connection, authentication, and stream-specific issues, while continuously printing current positions. ```Python import asyncio from typing import Dict, Any from binance_futures_async import BinanceClient from binance_futures_async.exceptions import ( ConnectionError, AuthenticationError, UserStreamError ) class UserDataHandler: def __init__(self): self.positions = {} self.balances = {} self.orders = {} async def handle_message(self, message: Dict[str, Any]): """Handle incoming user data stream messages.""" try: event_type = message.get('e') if event_type == 'ACCOUNT_UPDATE': await self.handle_account_update(message) elif event_type == 'ORDER_TRADE_UPDATE': await self.handle_order_update(message) elif event_type == 'MARGIN_CALL': await self.handle_margin_call(message) elif event_type == 'ACCOUNT_CONFIG_UPDATE': await self.handle_position_update(message) except Exception as e: print(f"Error processing message: {e}") async def handle_account_update(self, message: Dict[str, Any]): """Process account updates.""" update = message['a'] # Update balances for balance in update['B']: asset = balance['a'] self.balances[asset] = { 'wallet_balance': balance['wb'], 'cross_wallet_balance': balance['cw'] } # Update positions for position in update['P']: symbol = position['s'] self.positions[symbol] = { 'amount': position['pa'], 'entry_price': position['ep'], 'unrealized_pnl': position['up'] } async def handle_order_update(self, message: Dict[str, Any]): """Process order updates.""" order = message['o'] order_id = order['c'] self.orders[order_id] = { 'symbol': order['s'], 'side': order['S'], 'type': order['o'], 'status': order['X'], 'price': order['p'], 'quantity': order['q'] } async def main(): client = BinanceClient() user_stream = None handler = UserDataHandler() try: # Initialize user data stream user_stream = await client.user_stream( api_key="your_api_key", message_handler=handler.handle_message, config={ 'health_check_interval': 30, # More frequent health checks 'ping_interval': 1800 # 30-minute keepalive } ) print("User data stream started") # Keep the connection alive while True: await asyncio.sleep(1) # Example: Print current positions if handler.positions: print("\nCurrent Positions:") for symbol, pos in handler.positions.items(): print(f"{symbol}: {pos['amount']} @ {pos['entry_price']}") except ConnectionError as e: print(f"Connection error: {e}") except AuthenticationError as e: print(f"Authentication error: {e}") except UserStreamError as e: print(f"User stream error: {e}") except Exception as e: print(f"Unexpected error: {e}") finally: if user_stream: await user_stream.stop() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Implementing a Binance Futures Trading Bot - Python Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/docs/guides/examples.md This `TradingBot` class provides a basic framework for an asynchronous trading bot interacting with Binance Futures. It initializes WebSocket, market, and user data services, subscribes to mark price updates, and manages positions based on account updates. It includes placeholder methods for trading logic (`should_open_position`, `should_close_position`) and demonstrates placing market orders. ```python class TradingBot: def __init__(self): self.client = BinanceClient() self.ws_service = None self.market_service = None self.user_stream = None self.positions = {} self.last_price = None async def start(self): # Initialize all services self.ws_service = await self.client.websocket_service( api_key='your_api_key', private_key_path='path/to/your/key' ) self.market_service = await self.client.market_service( message_handler=self.handle_market_data ) self.user_stream = await self.client.user_stream( api_key='your_api_key', message_handler=self.handle_user_data ) # Subscribe to market data await self.market_service.subscribe_mark_price( symbols=["BTCUSDT"] ) def handle_market_data(self, message): if message.get('e') == 'markPrice': self.last_price = float(message['p']) asyncio.create_task(self.check_trading_conditions()) def handle_user_data(self, message): if message.get('e') == 'ACCOUNT_UPDATE': for position in message['a'].get('P', []): self.positions[position['s']] = float(position['pa']) async def check_trading_conditions(self): if not self.last_price: return position = self.positions.get('BTCUSDT', 0) try: if position == 0 and self.should_open_position(): await self.open_position() elif position != 0 and self.should_close_position(): await self.close_position() except Exception as e: print(f"Error in trading logic: {e}") def should_open_position(self): # Implement your trading logic here return False def should_close_position(self): # Implement your trading logic here return False async def open_position(self): await self.ws_service.place_market_order( symbol="BTCUSDT", side="BUY", quantity="0.001" ) async def close_position(self): await self.ws_service.place_market_order( symbol="BTCUSDT", side="SELL", quantity="0.001" ) async def stop(self): if self.ws_service: await self.ws_service.close() if self.market_service: await self.market_service.close() if self.user_stream: await self.user_stream.stop() async def run_trading_bot(): bot = TradingBot() try: await bot.start() while True: await asyncio.sleep(1) finally: await bot.stop() if __name__ == "__main__": asyncio.run(run_trading_bot()) ``` -------------------------------- ### Defining Default Market Stream Configurations (Python) Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/docs/guides/configuration.md This snippet defines the default configuration for the Market Stream service. It includes standard parameters for connection and request timeouts, ping intervals, and reconnection logic, providing a robust foundation for receiving market data. ```Python MARKET_STREAM_DEFAULTS = { 'connection_timeout': 30, 'request_timeout': 30, 'ping_interval': 180, 'reconnect_delay': 5, 'max_reconnect_delay': 300, 'max_reconnect_attempts': 5 } ``` -------------------------------- ### Handling Binance Futures User Data Streams - Python Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/docs/guides/examples.md This set of functions demonstrates how to process various user data events received from the Binance Futures user stream. It includes handlers for account updates (balances, positions), order trade updates, and margin calls, printing relevant information for each event type. It also shows how to initialize and maintain the user data stream connection. ```python def handle_user_data(message): event_type = message.get('e') if event_type == 'ACCOUNT_UPDATE': handle_account_update(message) elif event_type == 'ORDER_TRADE_UPDATE': handle_order_update(message) elif event_type == 'MARGIN_CALL': handle_margin_call(message) def handle_account_update(message): data = message['a'] print("\nAccount Update:") print(f"Reason: {data['m']}") # Balance updates for balance in data.get('B', []): print(f"Asset: {balance['a']}, Wallet Balance: {balance['wb']}") # Position updates for position in data.get('P', []): print(f"Symbol: {position['s']}, Position: {position['pa']}, Entry Price: {position['ep']}") def handle_order_update(message): data = message['o'] print("\nOrder Update:") print(f"Symbol: {data['s']}") print(f"Side: {data['S']}") print(f"Type: {data['o']}") print(f"Status: {data['X']}") def handle_margin_call(message): print("\nMargin Call!") positions = message.get('p', []) for position in positions: print(f"Symbol: {position['s']}, Position Amount: {position['ps']}") async def user_data_monitoring(): client = BinanceClient() user_stream = None try: user_stream = await client.user_stream( api_key='your_api_key', message_handler=handle_user_data ) # Keep connection alive while True: await asyncio.sleep(1) finally: if user_stream: await user_stream.stop() ``` -------------------------------- ### Example: Retrieving Order Book Depth for BTCUSDT Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/docs/api/websocket_service.md This example demonstrates how to call the `get_depth` method to retrieve the top 10 price levels of the order book for the 'BTCUSDT' trading pair. The result is stored in the `depth` variable. ```python depth = await ws_service.get_depth("BTCUSDT", limit=10) ``` -------------------------------- ### Subscribing to Multiple Market Data Streams with Binance Futures Async (Python) Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/docs/guides/examples.md This snippet demonstrates how to subscribe to and handle multiple types of market data streams (kline, aggregate trade, mark price) simultaneously using the `BinanceClient`'s market service. It defines a central `message_handler` function to dispatch messages based on their event type and shows how to subscribe to different symbols and intervals. Dependencies: `asyncio`, `binance_futures_async`. ```Python def handle_market_data(message): event_type = message.get('e') if event_type == 'kline': handle_kline(message) elif event_type == 'aggTrade': handle_aggtrade(message) elif event_type == 'markPrice': handle_markprice(message) def handle_kline(message): k = message['k'] print(f"Kline {message['s']} {k['i']}: O:{k['o']} H:{k['h']} L:{k['l']} C:{k['c']}") def handle_aggtrade(message): print(f"Trade {message['s']}: Price: {message['p']}, Quantity: {message['q']}") def handle_markprice(message): print(f"Mark Price {message['s']}: {message['p']}") async def market_streams(): client = BinanceClient() market_service = None try: market_service = await client.market_service( message_handler=handle_market_data ) # Subscribe to multiple data types await market_service.subscribe_kline( symbols=["BTCUSDT", "ETHUSDT"], intervals=["1m", "5m"] ) await market_service.subscribe_mark_price( symbols=["BTCUSDT", "ETHUSDT"] ) await market_service.subscribe_aggregate_trade( symbols=["BTCUSDT"] ) # Keep connection alive while True: await asyncio.sleep(1) finally: if market_service: await market_service.close() ``` -------------------------------- ### Example: Retrieving Ticker Prices for Single and All Symbols Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/docs/api/websocket_service.md These examples illustrate how to use `get_ticker_price` to fetch the latest price for a specific symbol ('BTCUSDT') and how to retrieve prices for all available symbols by omitting the `symbol` parameter. The results are stored in `btc_price` and `all_prices` respectively. ```python # Single symbol btc_price = await ws_service.get_ticker_price("BTCUSDT") # All symbols all_prices = await ws_service.get_ticker_price() ``` -------------------------------- ### Customizing WebSocket API Configuration (Python) Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/docs/guides/configuration.md This snippet demonstrates how to initialize the BinanceClient and customize the WebSocket API service configuration. It shows overriding default settings like return_rate_limits, connection_timeout, request_timeout, and ping_interval by passing a custom config dictionary during service instantiation, along with API key and validation settings. ```Python from binance_futures_async import BinanceClient async def main(): client = BinanceClient() # Custom configuration config = { 'return_rate_limits': False, # Disable rate limit info 'connection_timeout': 60, # Longer timeout 'request_timeout': 15, # Shorter request timeout 'ping_interval': 120 # More frequent pings } ws_service = await client.websocket_service( api_key='your_api_key', private_key_path='path/to/your/key', enable_validation=True, # Enable order validation config=config ) ``` -------------------------------- ### Configuring for Reliable Long-Running Systems in Python Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/docs/guides/configuration.md This configuration snippet demonstrates settings optimized for stable, long-running applications. It increases `max_reconnect_attempts` and `connection_timeout` while setting a `health_check_interval` to ensure continuous operation and resilience against transient network issues. ```python config = { 'max_reconnect_attempts': 15, # More reconnection attempts 'health_check_interval': 30, # Frequent health checks 'connection_timeout': 60, # Longer connection timeout 'request_timeout': 45 # Longer request timeout } ``` -------------------------------- ### Configuring for Poor Network Conditions in Python Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/docs/guides/configuration.md This configuration snippet provides settings tailored for unreliable network environments. It extends `connection_timeout`, `request_timeout`, and `reconnect_delay`, along with increasing `max_reconnect_attempts` to enhance robustness and recovery in challenging network scenarios. ```python config = { 'connection_timeout': 90, # Longer connection timeout 'request_timeout': 60, # Longer request timeout 'reconnect_delay': 10, # Longer initial reconnect delay 'max_reconnect_attempts': 20 # More reconnection attempts } ``` -------------------------------- ### Monitoring User Data Stream for Account Updates - Python Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/README.md This example shows how to initialize and maintain a user data stream to receive real-time account updates. It sets up a `message_handler` function to process incoming data and keeps the connection alive, enabling continuous monitoring of user-specific events. ```python import asyncio from binance_futures_async import BinanceClient from binance_futures_async.exceptions import ConnectionError, AuthenticationError, UserStreamError def handle_user_data(message): print(f"Received user data: {message}") async def main(): client = BinanceClient() user_stream = None try: # Initialize user data stream user_stream = await client.user_stream( api_key="your_api_key", message_handler=handle_user_data ) # Keep connection alive while True: await asyncio.sleep(1) except ConnectionError as e: print(f"Connection error: {e}") except AuthenticationError as e: print(f"Authentication error: {e}") except UserStreamError as e: print(f"User stream error: {e}") except Exception as e: print(f"Unexpected error: {e}") finally: if user_stream: await user_stream.stop() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Optimizing Configuration for High-Performance Trading (Python) Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/docs/guides/configuration.md This snippet provides a recommended configuration for high-performance trading applications. It suggests reducing response payload by disabling rate limit returns, setting aggressive timeouts for requests and connections, and increasing ping frequency to maintain a highly responsive and low-latency trading environment. ```Python config = { 'return_rate_limits': False, # Reduce response payload 'request_timeout': 10, # Fast timeout for HFT 'connection_timeout': 15, # Quick connection detection 'ping_interval': 60 # Frequent connection checks } ``` -------------------------------- ### Default Configuration Settings for Binance Futures Async Services (Python) Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/README.md This snippet outlines the default configuration parameters for the WebSocket API, User Data Stream, and Market Stream services. These defaults include settings for connection and request timeouts, ping intervals, and reconnection strategies, providing sensible starting points for client operations. ```Python # WebSocket API defaults WEBSOCKET_DEFAULTS = { 'return_rate_limits': True, # Return rate limit info in responses 'connection_timeout': 30, # Connection timeout in seconds 'request_timeout': 30, # Individual request timeout 'ping_interval': 180, # WebSocket ping interval 'reconnect_delay': 5, # Initial reconnection delay 'max_reconnect_delay': 300, # Maximum reconnection delay 'max_reconnect_attempts': 5 # Maximum reconnection attempts } # User Data Stream defaults USER_STREAM_DEFAULTS = { 'connection_timeout': 30, 'request_timeout': 30, 'ping_interval': 3300, # 55 minutes (listen key keepalive) 'reconnect_delay': 5, 'max_reconnect_delay': 300, 'max_reconnect_attempts': 5, 'health_check_interval': 60 # Stream health check interval } # Market Stream defaults MARKET_STREAM_DEFAULTS = { 'connection_timeout': 30, 'request_timeout': 30, 'ping_interval': 180, 'reconnect_delay': 5, 'max_reconnect_delay': 300, 'max_reconnect_attempts': 5 } ``` -------------------------------- ### Defining Default User Data Stream Configurations (Python) Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/docs/guides/configuration.md This snippet outlines the default configuration for the User Data Stream service. It specifies timeouts, ping intervals (tuned for listen key keepalive), and reconnection parameters, along with a health check interval, ensuring the stream remains active and responsive. ```Python USER_STREAM_DEFAULTS = { 'connection_timeout': 30, 'request_timeout': 30, 'ping_interval': 3300, # 55 minutes (listen key keepalive) 'reconnect_delay': 5, 'max_reconnect_delay': 300, 'max_reconnect_attempts': 5, 'health_check_interval': 60 # Stream health check interval } ``` -------------------------------- ### Defining Default WebSocket API Configurations (Python) Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/docs/guides/configuration.md This snippet defines the default configuration parameters for the WebSocket API service within the Binance Futures library. It includes settings for rate limit reporting, various timeouts (connection, request), WebSocket ping intervals, and reconnection strategies, providing a baseline for service behavior. ```Python WEBSOCKET_DEFAULTS = { 'return_rate_limits': True, # Return rate limit info in responses 'connection_timeout': 30, # Connection timeout in seconds 'request_timeout': 30, # Individual request timeout 'ping_interval': 180, # WebSocket ping interval 'reconnect_delay': 5, # Initial reconnection delay 'max_reconnect_delay': 300, # Maximum reconnection delay 'max_reconnect_attempts': 5 # Maximum reconnection attempts } ``` -------------------------------- ### Customizing Market Streams Configuration (Python) Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/docs/guides/configuration.md This snippet illustrates how to apply custom configurations to the Market Stream service. It shows overriding default ping_interval, max_reconnect_attempts, and connection_timeout by providing a market_config dictionary when initializing the market_service, allowing fine-grained control over market data stream behavior. ```Python # Custom market streams configuration market_config = { 'ping_interval': 300, # Longer ping interval 'max_reconnect_attempts': 10, # More reconnection attempts 'connection_timeout': 45 # Longer connection timeout } market_service = await client.market_service( message_handler=handle_market_data, config=market_config ) ``` -------------------------------- ### Catching Base BinanceWebSocketError in Python Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/README.md This example shows how to catch the base `BinanceWebSocketError` exception, which is the parent class for all library-specific errors. It allows for a general error handling mechanism for any issues originating from the Binance WebSocket library. ```python try: await ws_service.place_limit_order(...) except BinanceWebSocketError as e: print(f"Library error occurred: {e}") ``` -------------------------------- ### Starting User Data Stream Connection in Python Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/docs/api/user_data_stream.md Initiates the connection to the Binance Futures user data stream. This asynchronous method establishes the WebSocket connection and begins receiving real-time updates. It may raise various errors if the connection cannot be established or authentication fails. ```Python async def start(self) -> None ``` -------------------------------- ### Customizing User Data Stream Configuration (Python) Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/docs/guides/configuration.md This snippet demonstrates how to customize the User Data Stream configuration. It shows setting specific values for health_check_interval, ping_interval (for listen key refresh), and max_reconnect_attempts via a user_config dictionary passed during user_stream initialization, along with the API key and message handler. ```Python # Custom user stream configuration user_config = { 'health_check_interval': 30, # More frequent health checks 'ping_interval': 3000, # More frequent listen key refresh 'max_reconnect_attempts': 15 # More reconnection attempts } user_stream = await client.user_stream( api_key='your_api_key', message_handler=handle_user_data, config=user_config ) ``` -------------------------------- ### Implementing a Robust Binance Futures Async Application with Multiple Services (Python) Source: https://github.com/mumtazkahn/binance-futures-async/blob/main/docs/api/client.md This example illustrates a well-structured asynchronous application using the Binance Futures Async client, integrating multiple services (websocket, user stream, market data). It defines dedicated message handlers for different data types and implements comprehensive error handling for various client-specific exceptions, ensuring graceful shutdown of all initialized services in a finally block. ```Python import asyncio from binance_futures_async import BinanceClient from binance_futures_async.exceptions import ( ConnectionError, AuthenticationError, RequestError, UserStreamError ) async def handle_market_data(message): try: # Process market data print(f"Market update: {message}") except Exception as e: print(f"Error in market handler: {e}") async def handle_user_data(message): try: # Process user data print(f"Account update: {message}") except Exception as e: print(f"Error in user handler: {e}") async def main(): client = BinanceClient() ws_service = None user_stream = None market_service = None try: # Initialize services ws_service = await client.websocket_service( api_key="your_api_key", private_key_path="path/to/your/key", enable_validation=True ) user_stream = await client.user_stream( api_key="your_api_key", message_handler=handle_user_data ) market_service = await client.market_service( message_handler=handle_market_data ) # Keep application running while True: await asyncio.sleep(1) except (ConnectionError, AuthenticationError, RequestError, UserStreamError) as e: print(f"Error: {e}") finally: # Cleanup if ws_service: await ws_service.close() if user_stream: await user_stream.stop() if market_service: await market_service.close() if __name__ == "__main__": asyncio.run(main()) ```