### Install unicorn-binance-websocket-api with conda Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/README.md Install the package from the conda-forge channel. ```bash conda install -c conda-forge unicorn-binance-websocket-api ``` -------------------------------- ### Install unicorn-binance-websocket-api with pip Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/README.md Use this command to install the latest version of the package from PyPI. ```bash pip install unicorn-binance-websocket-api ``` -------------------------------- ### Start Binance WebSocket Socket Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/docs/_modules/unicorn_binance_websocket_api/sockets.html Initiates a WebSocket connection for a specific stream. It handles connection setup, user data subscription if applicable, and updates stream status to 'running'. ```python async def start_socket(self): logger.info(f"BinanceWebSocketApiSocket.start_socket({str(self.stream_id)}, {str(self.channels)}, " f"{str(self.markets)})") try: async with BinanceWebSocketApiConnection(self.manager, self.stream_id, self.channels, self.markets, symbols=self.symbols) as self.websocket: if self.websocket is None: raise StreamIsRestarting(stream_id=self.stream_id, reason="websocket is None") # New WS API userData subscription flow (Spot/Margin, Binance Feb 2026 change): # Authenticate by sending a signed subscription message right after connect. # This replaces the legacy listenKey approach and is re-sent on every reconnect. if self.manager.stream_list[self.stream_id].get('userData_type') == 'ws_api_signature': subscribe_payload = self.manager._build_userdata_subscribe_payload(self.stream_id) with self.manager.stream_list_lock: self.manager.stream_list[self.stream_id]['userdata_subscribe_id'] = subscribe_payload['id'] if self.manager.show_secrets_in_logs is True: logger.info(f"BinanceWebSocketApiSocket.start_socket({str(self.stream_id)}) - " f"Sending userDataStream.subscribe.signature: {subscribe_payload}") else: logger.info(f"BinanceWebSocketApiSocket.start_socket({str(self.stream_id)}) - " f"Sending userDataStream.subscribe.signature (id={subscribe_payload['id']})") await self.websocket.send(orjson.dumps(subscribe_payload).decode("utf-8")) if self.manager.stream_list[self.stream_id]['status'] == "restarting": self.manager.increase_reconnect_counter(self.stream_id) self.manager.stream_list[self.stream_id]['status'] = "running" self.manager.stream_list[self.stream_id]['has_stopped'] = None self.manager.set_socket_is_ready(stream_id=self.stream_id) self.manager.send_stream_signal(signal_type="CONNECT", stream_id=self.stream_id) self.manager.stream_list[self.stream_id]['last_stream_signal'] = "CONNECT" ``` -------------------------------- ### Get Listen Key Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/docs/_modules/unicorn_binance_websocket_api/api/spot.html Starts a user data stream to receive real-time updates for account information and order events. Requires an API key. ```APIDOC ## POST userDataStream.start ### Description Starts a user data stream (USER_STREAM) to receive real-time updates for account information and order events. This method requires an API key. ### Method POST ### Endpoint /api/v3/userDataStream ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **apiKey** (string) - Required - Your Binance API key. ### Request Example ```json { "id": "d3df8a61-98ea-4fe0-8f4e-0fcea5d418b0", "method": "userDataStream.start", "params": { "apiKey": "vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A" } } ``` ### Response #### Success Response (200) - **listenKey** (string) - The listen key required to subscribe to user data streams. #### Response Example ```json { "id": "d3df8a61-98ea-4fe0-8f4e-0fcea5d418b0", "status": 200, "result": { "listenKey": "xs0mRXdAKlIPDRFrlPcw0qI41Eh3ixNntmymGyhrhgqo7L6FuLaWArTD7RLP" }, "rateLimits": [ { "rateLimitType": "REQUEST_WEIGHT", "interval": "MINUTE", "intervalNum": 1, "limit": 6000, "count": 2 } ] } ``` ``` -------------------------------- ### Quick Start: Stream Real-time Trades Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/llms.txt A basic example demonstrating how to stream real-time trade data for BTCUSDT using the BinanceWebSocketApiManager. Requires the manager to be initialized with the exchange and uses a lambda function to process incoming stream data. ```python from unicorn_binance_websocket_api import BinanceWebSocketApiManager with BinanceWebSocketApiManager(exchange="binance.com") as ubwa: ubwa.create_stream(channels="trade", markets="btcusdt", process_stream_data=lambda data: print(data)) while not ubwa.is_manager_stopping(): pass ``` -------------------------------- ### Install Dependencies Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/examples/binance_futures_websocket_best_practice/README.md Install the required Python packages for the project. Ensure Python 3.7+ is installed. ```bash pip install -r requirements.txt ``` -------------------------------- ### Install ImageMagick Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/wiki/How-to-export-print_summary()-stdout-to-PNG? Install ImageMagick using apt. Ensure you have the necessary permissions. ```bash apt install imagemagick ``` -------------------------------- ### Example Script for Package Version Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/dev/sphinx/source/readme.md An example script demonstrating how to check for package updates using the `is_update_available` method. This script is part of the project's archive. ```python import time import logging from unicorn_binance_websocket_api.manager import BinanceWebSocketApiManager # https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/examples/_archive/example_version_of_this_package.py logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') # init api_manager = BinanceWebSocketApiManager(exchange='binance.com', output_default='dict') # check for update if api_manager.is_update_available(): logging.warning('There is a new version of the package is available!') else: logging.info('Your package is up-to-date.') # wait time.sleep(1000) ``` -------------------------------- ### Install from GitHub latest release (Linux/macOS) Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/docs/readme.html Install directly from the latest release archive on GitHub. This command dynamically fetches the latest release tag. Ensure curl is installed. ```bash pip install https://github.com/oliver-zehentnu/unicorn-binance-websocket-api/archive/$(curl -s https://api.github.com/repos/oliver-zehentleitner/unicorn-binance-websocket-api/releases/latest | grep -oP '"tag_name": "\K(.*)(?="')').tar.gz --upgrade ``` -------------------------------- ### Example Script for Version Check Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/README.md An example script demonstrating how to use the `is_update_available()` function to check for package updates. This script can be adapted for custom notification systems. ```python import os import sys import logging from unicorn_binance_websocket_api.manager import BinanceWebSocketApiManager if __name__ == '__main__': argv = sys.argv[1:] if len(argv) == 0: print('Usage: python example_version_of_this_package.py ') sys.exit(1) api_key = argv[0] api_secret = argv[1] logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) # https://docs.python.org/3/library/os.html#os.environ # export BINANCE_API_KEY=your_api_key # export BINANCE_API_SECRET=your_api_secret # os.environ['BINANCE_API_KEY'] = api_key # os.environ['BINANCE_API_SECRET'] = api_secret # Initialize and start the BinanceWebSocketApiManager binance_websocket_api_manager = BinanceWebSocketApiManager(exchange='binance.com', output_default='dict') # Check if an update is available if binance_websocket_api_manager.is_update_available(): print('There is a new version of the package available.') else: print('You are using the latest version of the package.') # Close the BinanceWebSocketApiManager binance_websocket_api_manager.stop_manager() print('Stopped the BinanceWebSocketApiManager.') ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/examples/binance_websocket_apache_kafka/README.md Install the required Python packages for the project using pip. It's recommended to install kafka-python from GitHub for the latest updates. ```bash pip install -r requirements.txt ``` ```bash pip install git+https://github.com/dpkp/kafka-python.git ``` -------------------------------- ### Install from latest release source with pip (Linux/macOS) Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/dev/sphinx/source/readme.md Install directly from the latest release archive on GitHub. This command automatically fetches the latest release tag. ```bash pip install https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/archive/$(curl -s https://api.github.com/repos/oliver-zehentleitner/unicorn-binance-websocket-api/releases/latest | grep -oP '"tag_name": "\K(.*)(?="')}).tar.gz --upgrade ``` -------------------------------- ### Start User Data Stream Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/docs/unicorn_binance_websocket_api.html Starts a user data stream to receive real-time updates for a specific user account. Requires a listenKey obtained from this endpoint. The stream can be configured with a callback function for processing responses. ```python from unicorn_binance_websocket_api.unicorn_binance_websocket_api import BinanceWebSocketApiManager bmang = BinanceWebSocketApiManager(exchange_symbol_separator='@') # Example: Start user data stream bmang.get_listen_key() # Example: Start user data stream with a callback def handle_user_data(msg): print(f"User data: {msg}") bmang.get_listen_key(process_response=handle_user_data) # Example: Start user data stream and return response directly response = bmang.get_listen_key(return_response=True) print(f"Listen key response: {response}") ``` -------------------------------- ### Get Start Time Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/docs/_modules/unicorn_binance_websocket_api/manager.html Retrieves the timestamp when the BinanceWebSocketApiManager instance was started. This can be used for performance monitoring or time-based analysis. ```python def get_start_time(self): """ Get the start_time of the BinanceWebSocketApiManager instance :return: timestamp """ return self.start_time ``` -------------------------------- ### Run the Example Script Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/examples/binance_websocket_stream_signals/README.md Execute the main demonstration script. This script activates and processes stream signals without processing actual data. ```bash python ubwa-demo.py ``` -------------------------------- ### Initialize BinanceWebSocketApiManager and Setup Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/ipynb/First_steps.ipynb Imports necessary libraries and initializes the BinanceWebSocketApiManager. It also sets up logging and checks for the presence of the unicorn-binance-rest-api library. ```python from unicorn_binance_websocket_api.unicorn_binance_websocket_api_manager import BinanceWebSocketApiManager import os import requests import sys import time import threading import logging logger = logging.getLogger() logger.setLevel(logging.CRITICAL) try: import unicorn_binance_rest_api except ImportError: print("Please install `unicorn-binance-rest-api`! https://pypi.org/project/unicorn-binance-rest-api/#description") sys.exit(1) def print_stream_data_from_stream_buffer(binance_websocket_api_manager): while True: if binance_websocket_api_manager.is_manager_stopping(): exit(0) oldest_stream_data_from_stream_buffer = binance_websocket_api_manager.pop_stream_data_from_stream_buffer() if oldest_stream_data_from_stream_buffer is not None: pass else: time.sleep(0.01) binance_api_key = "" binance_api_secret = "" #channels = {'aggTrade', 'trade', 'kline_1m', 'kline_5m', 'kline_15m', 'kline_30m', 'kline_1h', 'kline_2h', 'kline_4h', # 'kline_6h', 'kline_8h', 'kline_12h', 'kline_1d', 'kline_3d', 'kline_1w', 'kline_1M', 'miniTicker', # 'ticker', 'bookTicker', 'depth5', 'depth10', 'depth20', 'depth'} #channels.add('depth@100ms') channels = {'aggTrade', 'trade', 'kline_1m'} arr_channels = {'!miniTicker', '!ticker', '!bookTicker'} markets = [] try: binance_rest_client = unicorn_binance_rest_api.BinanceRestApiManager(binance_api_key, binance_api_secret) except requests.exceptions.ConnectionError: print("No internet connection?") sys.exit(1) ubwa = BinanceWebSocketApiManager() ``` -------------------------------- ### get_start_time Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/docs/genindex.html Gets the start time of the WebSocket API manager. ```APIDOC ## get_start_time() ### Description Retrieves the start time of the BinanceWebSocketApiManager instance. ### Method (Not specified in source, likely a Python method call) ### Endpoint (Not applicable, this is an SDK method) ### Parameters (Parameters not specified in source) ### Request Example (Not applicable) ### Response (Response details not specified in source) ``` -------------------------------- ### Run the Script Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/examples/binance_websocket_spot_userdata_async/README.md Execute the Python script to start the Binance Spot userData WebSocket connection. ```bash python binance_websocket_spot_userdata_async.py ``` -------------------------------- ### get_total_received_bytes Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/docs/modules.html Gets the total number of bytes received since the connection started. ```APIDOC ## get_total_received_bytes ### Description Returns the cumulative number of bytes received over the WebSocket connection. ### Method Not specified (likely a Python method call) ### Endpoint N/A ### Parameters None ### Request Example ```python api_manager.get_total_received_bytes() ``` ### Response * **total_bytes** (int) - The total bytes received. ``` -------------------------------- ### Get UnicornFy Version Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/docs/_modules/unicorn_binance_websocket_api/manager.html Retrieves the version of the UnicornFy package. This method requires the UnicornFy package to be installed. ```python from unicorn_fy.unicorn_fy import UnicornFy unicorn_fy = UnicornFy() return unicorn_fy.get_version() ``` -------------------------------- ### Configure API Credentials Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/examples/binance_websocket_api_futures/README.md Create an .env file with your Binance API key and secret. Use the provided .env-example as a template. ```bash BINANCE_API_KEY=12A34BCD5678EFG90HIJKLM12NOP3456QR789STUV0WXYZ BINANCE_API_SECRET=a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z6 ``` -------------------------------- ### Get Open Orders - Response Message Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/docs/_modules/unicorn_binance_websocket_api/api.html This is an example of a JSON response received from the Binance API detailing the status of open orders. ```json { "id": "55f07876-4f6f-4c47-87dc-43e5fff3f2e7", "status": 200, "result": [ { "symbol": "BTCUSDT", "orderId": 12569099453, "orderListId": -1, "clientOrderId": "4d96324ff9d44481926157", "price": "23416.10000000", "origQty": "0.00847000", "executedQty": "0.00720000", "cummulativeQuoteQty": "172.43931000", "status": "PARTIALLY_FILLED", "timeInForce": "GTC", "type": "LIMIT", "side": "SELL", "stopPrice": "0.00000000", "icebergQty": "0.00000000", "time": 1660801715639, "updateTime": 1660801717945, "isWorking": true, "workingTime": 1660801715639, "origQuoteOrderQty": "0.00000000", "selfTradePreventionMode": "NONE" } ] } ``` -------------------------------- ### Initialize BinanceWebSocketApiManager with Context Manager Source: https://context7.com/oliver-zehentleitner/unicorn-binance-websocket-api/llms.txt Demonstrates basic context-manager usage for the BinanceWebSocketApiManager with spot streams and asyncio queue output. Ensure logging is configured if needed. ```python from unicorn_binance_websocket_api import BinanceWebSocketApiManager import asyncio import logging import os logging.basicConfig( level=logging.INFO, filename="ubwa.log", format="{asctime} [{levelname:8}] {process} {thread} {module}: {message}", style="{" ) # --- Basic context-manager usage (spot, asyncio queue output) --- with BinanceWebSocketApiManager( exchange="binance.com", # see Exchanges enum for full list output_default="UnicornFy", # "raw_data" | "dict" | "UnicornFy" enable_stream_signal_buffer=True, auto_data_cleanup_stopped_streams=True, warn_on_update=True, socks5_proxy_server=None, # e.g. "127.0.0.1:9050" ) as ubwa: stream_id = ubwa.create_stream( channels="trade", markets="btcusdt", stream_label="BTC_trade" ) # ... consume data ... ubwa.stop_manager() # --- Futures exchange --- ubwa_futures = BinanceWebSocketApiManager(exchange="binance.com-futures", output_default="dict") ``` -------------------------------- ### Get Open Orders - Request Message Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/docs/_modules/unicorn_binance_websocket_api/api.html This is an example of the JSON message sent to the Binance API to request the status of open orders. ```json { "id": "55f07876-4f6f-4c47-87dc-43e5fff3f2e7", "method": "openOrders.status", "params": { "symbol": "BTCUSDT", "apiKey": "vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A", "signature": "d632b3fdb8a81dd44f82c7c901833309dd714fe508772a89b0a35b0ee0c48b89", "timestamp": 1660813156812 } } ``` -------------------------------- ### Create Documentation Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/wiki/Info-for-maintainers Execute this script to generate project documentation. Ensure you have followed the linked guide for creating docs. ```bash dev/sphinx/create_docs.sh ``` -------------------------------- ### Get Historical Trades Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/docs/_modules/unicorn_binance_websocket_api/api/spot.html Retrieves historical trades for a given symbol. You can specify a symbol, and optionally a limit for the number of trades and a starting ID. ```APIDOC ## GET /trades.historical ### Description Retrieves historical trades for a given symbol. You can specify a symbol, and optionally a limit for the number of trades and a starting ID. ### Method POST ### Endpoint /api ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **symbol** (str) - Required - The trading symbol (e.g., BNBBTC). - **fromId** (int) - Optional - The trade ID to start from. - **limit** (int) - Optional - The maximum number of trades to retrieve. ### Request Example ```json { "id": "cffc9c7d-4efc-4ce0-b587-6b87448f052a", "method": "trades.historical", "params": { "symbol": "BNBBTC", "fromId": 0, "limit": 1 } } ``` ### Response #### Success Response (200) - **id** (str) - The request ID. - **status** (int) - The status code of the response. - **result** (list) - A list of historical trades. - **id** (int) - The trade ID. - **price** (str) - The price of the trade. - **qty** (str) - The quantity of the trade. - **quoteQty** (str) - The quote quantity of the trade. - **time** (int) - The timestamp of the trade. - **isBuyerMaker** (bool) - Whether the buyer was the maker. - **isBestMatch** (bool) - Whether this was the best match. - **rateLimits** (list) - Information about rate limits. - **rateLimitType** (str) - The type of rate limit. - **interval** (str) - The interval of the rate limit. - **intervalNum** (int) - The number of intervals. - **limit** (int) - The limit for the rate. - **count** (int) - The current count for the rate limit. #### Response Example ```json { "id": "cffc9c7d-4efc-4ce0-b587-6b87448f052a", "status": 200, "result": [ { "id": 0, "price": "0.00005000", "qty": "40.00000000", "quoteQty": "0.00200000", "time": 1500004800376, "isBuyerMaker": true, "isBestMatch": true } ], "rateLimits": [ { "rateLimitType": "REQUEST_WEIGHT", "interval": "MINUTE", "intervalNum": 1, "limit": 6000, "count": 10 } ] } ``` ``` -------------------------------- ### BinanceWebSocketApiManager.run() Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/docs/modules.html Starts the Binance WebSocket API manager and begins processing data. ```APIDOC ## BinanceWebSocketApiManager.run() ### Description Starts the Binance WebSocket API manager and begins processing data. ### Method run() ### Parameters None ``` -------------------------------- ### Request Aggregate Trades Binance API Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/docs/unicorn_binance_websocket_api.html This snippet demonstrates how to construct a request to get aggregate trades from the Binance API. It specifies the symbol, a starting trade ID, and a limit. ```json { "id": "189da436-d4bd-48ca-9f95-9f613d621717", "method": "trades.aggregate", "params": { "symbol": "BNBBTC", "fromId": 50000000, "limit": 1 } } ``` -------------------------------- ### Directory Structure Overview Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/AGENTS.md Illustrates the main package and supporting directories within the project. ```text unicorn_binance_websocket_api/ # Main package manager.py # Core class BinanceWebSocketApiManager (~4800 lines) connection.py # Individual WebSocket connections (asyncio) sockets.py # Socket implementation with stream processing restclient.py # REST client for stream management restserver.py # Flask REST server for external control connection_settings.py # Exchanges enum + connection parameters exceptions.py # Custom exceptions api/ # WebSocket API (trading) for Spot & Futures unittest_binance_websocket_api.py # Unit tests (main test file, run in CI) dev/ # Local dev/integration tests — NOT run in CI examples/ # Usage examples (14 directories) docs/ # Pre-built HTML documentation (Sphinx) ``` -------------------------------- ### Get UI Kline Data Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/docs/_modules/unicorn_binance_websocket_api/api/spot.html Retrieves Kline (candlestick) data for a specified symbol and interval. Supports filtering by start time, end time, and limit. Time parameters are interpreted in UTC. ```APIDOC ## GET /api/v3/klines ### Description Retrieves Kline (candlestick) data for a specified symbol and interval. Supports filtering by start time, end time, and limit. Time parameters are interpreted in UTC. ### Method GET ### Endpoint /api/v3/klines ### Parameters #### Query Parameters - **symbol** (string) - Required - The trading pair symbol (e.g., "BNBBTC") - **interval** (string) - Optional - The interval of the klines (e.g., "1h", "1d") - **startTime** (integer) - Optional - The start time in milliseconds - **endTime** (integer) - Optional - The end time in milliseconds - **limit** (integer) - Optional - The maximum number of klines to return - **timeZone** (integer) - Optional - The time zone offset in minutes (default: 0) ### Request Example ```json { "id": "b137468a-fb20-4c06-bd6b-625148eec958", "method": "uiKlines", "params": { "symbol": "BNBBTC", "interval": "1h", "startTime": 1655969280000, "limit": 1 } } ``` ### Response #### Success Response (200) - **id** (string) - The request ID. - **status** (integer) - The status code of the response. - **result** (array) - An array of kline data. - Each kline is an array containing: - 0: Kline open time (integer) - 1: Open price (string) - 2: High price (string) - 3: Low price (string) - 4: Close price (string) - 5: Volume (string) - 6: Kline close time (integer) - 7: Quote asset volume (string) - 8: Number of trades (integer) - 9: Taker buy base asset volume (string) - 10: Taker buy quote asset volume (string) - 11: Unused field (string) - **rateLimits** (array) - Information about rate limits. #### Response Example ```json { "id": "b137468a-fb20-4c06-bd6b-625148eec958", "status": 200, "result": [ [ 1655971200000, "0.01086000", "0.01086600", "0.01083600", "0.01083800", "2290.53800000", 1655974799999, "24.85074442", 2283, "1171.64000000", "12.71225884", "0" ] ], "rateLimits": [ { "rateLimitType": "REQUEST_WEIGHT", "interval": "MINUTE", "intervalNum": 1, "limit": 6000, "count": 2 } ] } ``` ``` -------------------------------- ### BinanceWebSocketApiManager.help Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/docs/unicorn_binance_websocket_api.html Displays help information. ```APIDOC ## help ### Description Displays help information. ### Method GET ### Endpoint /help ### Parameters None ``` -------------------------------- ### BinanceWebSocketApiManager.help() Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/docs/modules.html Displays help information for the BinanceWebSocketApiManager. ```APIDOC ## BinanceWebSocketApiManager.help() ### Description Displays help information for the BinanceWebSocketApiManager. ### Method help() ### Parameters None ``` -------------------------------- ### Get Listen Key from RestClient (Python) Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/docs/_modules/unicorn_binance_websocket_api/manager.html Retrieves a listen key, either a new one or a cached one if it's less than 30 minutes old. This method checks the validity of the existing listen key based on its start time and cache duration. ```python if (self.stream_list[stream_id]['start_time'] + self.stream_list[stream_id]['listen_key_cache_time']) > \ time.time() or (self.stream_list[stream_id]['last_static_ping_listen_key'] + self.stream_list[stream_id]['listen_key_cache_time']) > time.time(): ``` -------------------------------- ### Create Order Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/README.md Demonstrates how to create a new order on Binance Spot market. ```APIDOC ## POST /api/v3/order ### Description Creates a new order on the Binance Spot market. ### Method POST ### Endpoint /api/v3/order ### Parameters #### Request Body - **symbol** (string) - Required - The trading pair, e.g. 'BUSDUSDT' - **side** (string) - Required - 'BUY' or 'SELL' - **type** (string) - Required - Order type, e.g. 'LIMIT' - **timeInForce** (string) - Optional - Order duration, e.g. 'GTC' - **quantity** (number) - Required - Amount of asset to trade - **price** (number) - Required - Price at which to place the order - **newClientOrderId** (string) - Optional - Unique ID for the order ### Request Example ```json { "symbol": "BUSDUSDT", "side": "SELL", "type": "LIMIT", "quantity": 15.0, "price": 1.1 } ``` ### Response #### Success Response (200) - **origClientOrderId** (string) - The client order ID. - **orderId** (integer) - The order ID. - **symbol** (string) - The trading pair. - **status** (string) - The order status. #### Response Example ```json { "origClientOrderId": "some_client_order_id", "orderId": 123456789, "symbol": "BUSDUSDT", "status": "NEW" } ``` ``` -------------------------------- ### Install latest release from GitHub with pip (Linux/macOS) Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/README.md Installs the latest release directly from GitHub using a dynamic tag name fetched via curl. Ensure you have curl installed. ```bash pip install https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/archive/$(curl -s https://api.github.com/repos/oliver-zehentleitner/unicorn-binance-websocket-api/releases/latest | grep -oP '"tag_name": "\K(.*)(?="') ).tar.gz --upgrade ``` -------------------------------- ### Run the Python Script Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/examples/binance_websocket_api_futures/README.md Execute the main Python script to start interacting with the Binance WebSocket API for Futures. ```bash python binance_websocket_api_futures.py ``` -------------------------------- ### Install Jupyter Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/ipynb/README.md Install Jupyter using pip. This command is typically run in a terminal or command prompt. ```bash pip3 install jupyter ``` -------------------------------- ### Initialize BinanceWebSocketApiManager Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/docs/_modules/unicorn_binance_websocket_api/manager.html Initializes the BinanceWebSocketApiManager. It sets up the API client, REST client, and starts the manager. It also checks for available updates and prints a warning if a new version is found. ```python self.replacement_text = "***SECRET_REMOVED***" self.api: WsApi = WsApi(manager=self) self.warn_on_update = warn_on_update if warn_on_update and self.is_update_available(): update_msg = f"Release {self.name}_" + self.get_latest_version() + " is available, " \ f"please consider updating! Changelog: " \ f"https://oliver-zehentleitner.github.io/unicorn-binance-websocket-api/changelog.html" print(update_msg) logger.warning(update_msg) self.restclient = BinanceWebSocketApiRestclient(debug=self.debug, disable_colorama=self.disable_colorama, exchange=self.exchange, socks5_proxy_server=self.socks5_proxy_server, socks5_proxy_user=self.socks5_proxy_user, socks5_proxy_pass=self.socks5_proxy_pass, stream_list=self.stream_list, warn_on_update=self.warn_on_update) self.start() ``` -------------------------------- ### Get Account Balance Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/docs/_modules/unicorn_binance_websocket_api/api/futures.html Retrieves the balance of a specific account. It can be used to get the balance of all of your futures wallets. ```APIDOC ## GET /api/v1/account.balance ### Description Retrieves the balance of a specific account. It can be used to get the balance of all of your futures wallets. ### Method GET ### Endpoint /api/v1/account.balance ### Parameters #### Query Parameters - **apiKey** (string) - Required - Your API key. - **timestamp** (integer) - Required - UTC timestamp in milliseconds. - **recvWindow** (integer) - Optional - The value cannot be greater than 60000. - **signature** (string) - Required - Signature generated using the API secret. ### Request Example ```json { "id": "605a6d20-6588-4cb9-afa0-b0ab087507ba", "method": "account.balance", "params": { "apiKey": "YOUR_API_KEY", "timestamp": 1678886400000, "signature": "208bb94a26f99aa122b1319490ca9cb2798fccc81d9b6449521a26268d53217a" } } ``` ### Response #### Success Response (200) - **id** (string) - Unique request ID. - **status** (integer) - HTTP status code. - **result** (object) - Contains account balance information. - **accountAlias** (string) - Unique account code. - **asset** (string) - Asset name. - **balance** (string) - Wallet balance. - **crossWalletBalance** (string) - Crossed wallet balance. - **crossUnPnl** (string) - Unrealized profit of crossed positions. - **availableBalance** (string) - Available balance. - **maxWithdrawAmount** (string) - Maximum amount for transfer out. - **marginAvailable** (boolean) - Whether the asset can be used as margin in Multi-Assets mode. - **updateTime** (integer) - Update time. - **rateLimits** (array) - Rate limit information. - **rateLimitType** (string) - Type of rate limit. - **interval** (string) - Interval of the rate limit. - **intervalNum** (integer) - Number of intervals. - **limit** (integer) - Limit number. - **count** (integer) - Current count. #### Response Example ```json { "id": "605a6d20-6588-4cb9-afa0-b0ab087507ba", "status": 200, "result": [ { "accountAlias": "SgsR", "asset": "USDT", "balance": "122607.35137903", "crossWalletBalance": "23.72469206", "crossUnPnl": "0.00000000", "availableBalance": "23.72469206", "maxWithdrawAmount": "23.72469206", "marginAvailable": true, "updateTime": 1617939110373 } ], "rateLimits": [ { "rateLimitType": "REQUEST_WEIGHT", "interval": "MINUTE", "intervalNum": 1, "limit": 2400, "count": 20 } ] } ``` ``` -------------------------------- ### Get Server Time Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/docs/_modules/unicorn_binance_websocket_api/api/futures.html Check server time by testing connectivity to the WebSocket API and getting the current server time. ```APIDOC ## GET /api/v1/time ### Description Check connectivity to the WebSocket API and get the current server time. ### Method GET ### Endpoint /api/v1/time ### Parameters #### Query Parameters - **symbol** (string) - Required - The symbol to get the server time for. ### Request Example ```json { "id": "187d3cb2-942d-484c-8271-4e2141bbadb1", "method": "time" } ``` ### Response #### Success Response (200) - **id** (string) - The request ID. - **status** (integer) - The status code of the response. - **result** (object) - The result of the request. - **serverTime** (integer) - The current server time in milliseconds. - **rateLimits** (array) - Information about rate limits. - **rateLimitType** (string) - The type of rate limit. - **interval** (string) - The interval of the rate limit. - **intervalNum** (integer) - The number of intervals. - **limit** (integer) - The limit for the rate. - **count** (integer) - The current count for the rate limit. #### Response Example ```json { "id": "187d3cb2-942d-484c-8271-4e2141bbadb1", "status": 200, "result": { "serverTime": 1656400526260 }, "rateLimits": [ { "rateLimitType": "REQUEST_WEIGHT", "interval": "MINUTE", "intervalNum": 1, "limit": 1200, "count": 1 } ] } ``` ``` -------------------------------- ### Run Data Download Script Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/examples/binance_websocket_kline_1m_ohlcv_to_sqlite/README.md Execute the Python script to start downloading and storing Binance OHLCV data. ```bash python binance_websocket_kline_1m_ohlcv_to_sqlite.py ``` -------------------------------- ### Get Symbol Price Ticker Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/docs/unicorn_binance_websocket_api.html Retrieves the latest price for a specified symbol. This method is useful for getting the current trading price. ```APIDOC ## Get Symbol Price Ticker ### Description Retrieves the latest price for a specified symbol. This method is useful for getting the current trading price. ### Method Signature `get_ticker_price(_process_response=None_, _request_id: str = None_, _return_response: bool = False_, _stream_id: str = None_, _stream_label: str = None_, _symbol: str = None_) -> str | dict | bool` ### Parameters * **process_response** (_function_) – Callback function to process received webstream data. * **request_id** (_str_) – Custom ID for the request. * **return_response** (_bool_) – If True, waits for and returns the API response directly. * **stream_id** (_str_) – ID of the stream to send the request. * **stream_label** (_str_) – Label of the stream to send the request (used if stream_id is not provided). * **symbol** (_str_) – The selected symbol (e.g., "BTCUSDT"). ### Message Sent ```json { "id": "", "method": "ticker.price", "params": { "symbol": "" } } ``` ### Response Example (Success) ```json { "id": "", "status": 200, "result": { "symbol": "BTCUSDT", "price": "6000.01", "time": 1589437530011 }, "rateLimits": [ { "rateLimitType": "REQUEST_WEIGHT", "interval": "MINUTE", "intervalNum": 1, "limit": 2400, "count": 2 } ] } ``` ### Response Example (Multiple Symbols) ```json { "id": "", "status": 200, "result": [ { "symbol": "BTCUSDT", "price": "6000.01", "time": 1589437530011 } ], "rateLimits": [ { "rateLimitType": "REQUEST_WEIGHT", "interval": "MINUTE", "intervalNum": 1, "limit": 2400, "count": 2 } ] } ``` ``` -------------------------------- ### Install specific release from GitHub with pip (Windows) Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/README.md Installs a specific version of the package from GitHub. Replace '2.13.0' with the desired version number. ```bash pip install https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/archive/2.13.0.tar.gz --upgrade ``` -------------------------------- ### Handle OSError on Server Start Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/docs/changelog.html Fixed an OSError that occurred when `self.monitoring_api_server.start()` was called if the server was already started. This ensures the server can be managed reliably. ```python OSError exception for self.monitoring_api_server.start() if its already started ``` -------------------------------- ### BinanceWebSocketApiRestclient.__init__ Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/docs/_modules/unicorn_binance_websocket_api/restclient.html Initializes a new instance of the BinanceWebSocketApiRestclient class. Allows configuration of various parameters for connecting to Binance and handling streams. ```APIDOC ## BinanceWebSocketApiRestclient.__init__ ### Description Initializes a new instance of the BinanceWebSocketApiRestclient class. Allows configuration of various parameters for connecting to Binance and handling streams. ### Parameters - **debug** (Optional[bool]) - If True, enables debug logging. - **disable_colorama** (Optional[bool]) - If True, disables colorama for logging. - **exchange** (Optional[str]) - The Binance exchange to connect to (default: "binance.com"). - **restful_base_uri** (Optional[str]) - Base URI for RESTful API calls. - **show_secrets_in_logs** (Optional[bool]) - If True, shows secrets in logs. - **socks5_proxy_server** (Optional[str]) - SOCKS5 proxy server address. - **socks5_proxy_user** (Optional[str]) - SOCKS5 proxy username. - **socks5_proxy_pass** (Optional[str]) - SOCKS5 proxy password. - **socks5_proxy_ssl_verification** (Optional[bool]) - SSL verification for SOCKS5 proxy (default: True). - **stream_list** (dict) - A dictionary to manage stream information. - **ubra** (BinanceRestApiManager) - An instance of BinanceRestApiManager. - **warn_on_update** (Optional[bool]) - If True, warns on updates (default: True). ``` -------------------------------- ### Create User Data Streams with Per-Stream Credentials Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/docs/_sources/readme.md.txt Demonstrates how to create multiple user data streams using different API keys and secrets for distinct accounts, and how to configure streams for isolated margin trading. ```APIDOC ## Create User Data Streams with Per-Stream Credentials Useful when running multiple `!userData` streams with different API keys on the same manager: ```python ubwa = BinanceWebSocketApiManager(exchange="binance.com") ubwa.create_stream(channels='arr', markets='!userData', api_key="API_KEY_ACCOUNT_A", api_secret="API_SECRET_ACCOUNT_A", stream_label="ACCOUNT_A", process_stream_data_async=process_userdata) ubwa.create_stream(channels='arr', markets='!userData', api_key="API_KEY_ACCOUNT_B", api_secret="API_SECRET_ACCOUNT_B", stream_label="ACCOUNT_B", process_stream_data_async=process_userdata) ``` Per-stream credentials override the manager defaults. Isolated Margin additionally requires the `symbols` parameter: ```python ubwa_im = BinanceWebSocketApiManager(exchange="binance.com-isolated_margin") ubwa_im.create_stream(channels='arr', markets='!userData', symbols='btcusdt', api_key="YOUR_BINANCE_API_KEY", api_secret="YOUR_BINANCE_API_SECRET", process_stream_data_async=process_userdata) ``` ``` -------------------------------- ### Install latest development version from GitHub with pip Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/README.md Installs the latest development version from the master branch of GitHub. This version is not stable and should be used with caution. ```bash pip install https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/tarball/master --upgrade ``` -------------------------------- ### Wait for Binance Stream to Start Source: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api/blob/master/docs/_modules/unicorn_binance_websocket_api/manager.html Waits until a specific stream has started and received its first data. Includes an optional timeout to prevent indefinite waiting. ```python def wait_till_stream_has_started(self, stream_id, timeout: float = 0.0) -> bool: """ Returns `True` as soon a specific stream has started and received its first stream data :param stream_id: id of a stream :type stream_id: str :param timeout: The timeout for how long to wait for the stream to stop. The function aborts if the waiting time is exceeded and returns False. :type timeout: float :return: bool """ timestamp = self.get_timestamp_unix() timeout = timestamp + timeout if timeout != 0.0 else timeout logger.debug(f"BinanceWebSocketApiManager.wait_till_stream_has_started({stream_id}) with timeout {timeout} " f ``` ```python started!") try: while self.stream_list[stream_id]['last_heartbeat'] is None: if self.get_timestamp_unix() > timeout != 0.0: logger.debug( f"BinanceWebSocketApiManager.wait_till_stream_has_started({stream_id}) finished with `False`!") return False time.sleep(0.1) ```