### Install aster-connector-python Source: https://github.com/asterdex/aster-connector-python/blob/master/README.md Install the library using pip. ```bash pip install aster-connector-python ``` -------------------------------- ### Initialize REST API Client and Get Timestamp Source: https://github.com/asterdex/aster-connector-python/blob/master/README.md Initialize the REST API client without an API key to get the current server timestamp. ```python from aster.rest_api import Client # Get timestamp client = Client() print(client.time()) ``` -------------------------------- ### GET /mark_price Source: https://context7.com/asterdex/aster-connector-python/llms.txt Retrieves mark price and funding rate information. ```APIDOC ## GET /mark_price ### Description Retrieves mark price and funding rate information for a symbol or all symbols. ### Parameters #### Query Parameters - **symbol** (string) - Optional ``` -------------------------------- ### GET /balance Source: https://context7.com/asterdex/aster-connector-python/llms.txt Retrieves the futures account balance information. ```APIDOC ## GET /balance ### Description Retrieves futures account balance information. ### Response #### Success Response (200) - **accountAlias** (string) - Account identifier - **asset** (string) - Asset name - **balance** (string) - Total balance ``` -------------------------------- ### Initialize REST API Client with API Key and Get Account Info Source: https://github.com/asterdex/aster-connector-python/blob/master/README.md Initialize the REST API client with API key and secret to retrieve account information. ```python client = Client(key='', secret='') # Get account information print(client.account()) ``` -------------------------------- ### Fetch Exchange Information Source: https://context7.com/asterdex/aster-connector-python/llms.txt Get trading rules, symbol details, and filter configurations for the exchange. ```python from aster.rest_api import Client client = Client() response = client.exchange_info() print(response) # Expected output: # { # 'exchangeFilters': [], # 'rateLimits': [...], # 'serverTime': 1699123456789, # 'symbols': [ # { # 'symbol': 'BTCUSDT', # 'pair': 'BTCUSDT', # 'contractType': 'PERPETUAL', # 'baseAsset': 'BTC', # 'quoteAsset': 'USDT', # 'filters': [...] # }, # ... # ] # } ``` -------------------------------- ### GET /book_ticker Source: https://context7.com/asterdex/aster-connector-python/llms.txt Retrieves the best bid and ask prices and quantities. ```APIDOC ## GET /book_ticker ### Description Retrieves the best bid and ask prices and quantities for a symbol or all symbols. ### Parameters #### Query Parameters - **symbol** (string) - Optional ``` -------------------------------- ### GET /ticker_price Source: https://context7.com/asterdex/aster-connector-python/llms.txt Retrieves the latest price for a symbol or all symbols. ```APIDOC ## GET /ticker_price ### Description Retrieves the latest price for a symbol or all symbols. ### Parameters #### Query Parameters - **symbol** (string) - Optional ``` -------------------------------- ### GET /ticker_24hr Source: https://context7.com/asterdex/aster-connector-python/llms.txt Retrieves 24-hour rolling window price change statistics. ```APIDOC ## GET /ticker_24hr ### Description Retrieves 24-hour rolling window price change statistics for a symbol or all symbols. ### Parameters #### Query Parameters - **symbol** (string) - Optional ``` -------------------------------- ### Retrieve Commission Rate Source: https://context7.com/asterdex/aster-connector-python/llms.txt Gets the current maker and taker commission rates for a specific symbol. ```python from aster.rest_api import Client client = Client(key='your_api_key', secret='your_api_secret') response = client.commission_rate(symbol='BTCUSDT') print(response) ``` -------------------------------- ### GET /klines Source: https://context7.com/asterdex/aster-connector-python/llms.txt Retrieves kline/candlestick bars for a symbol. ```APIDOC ## GET /klines ### Description Retrieves kline/candlestick bars for a symbol. Intervals: 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M. ### Parameters #### Query Parameters - **symbol** (string) - Required - **interval** (string) - Required - **limit** (integer) - Optional - **startTime** (long) - Optional - **endTime** (long) - Optional ``` -------------------------------- ### Get Account Information Source: https://context7.com/asterdex/aster-connector-python/llms.txt Retrieves comprehensive account information, including trading status, margin details, and asset/position summaries. ```python response = client.account() print(response) ``` -------------------------------- ### Get Mark Price and Funding Rate Source: https://context7.com/asterdex/aster-connector-python/llms.txt Retrieves mark price and funding rate information for a specific symbol or all symbols. ```python from aster.rest_api import Client client = Client() # Get mark price for specific symbol response = client.mark_price(symbol='BTCUSDT') print(response) # Get mark price for all symbols all_mark_prices = client.mark_price() ``` -------------------------------- ### Subscribe to WebSocket Partial Book Depth Stream Source: https://context7.com/asterdex/aster-connector-python/llms.txt Connects to the WebSocket API to receive partial order book updates (bids and asks) at specified depth levels and intervals. Ensure the `aster.websocket.client.stream.WebsocketClient` is initialized and started before subscribing. ```python import time from aster.websocket.client.stream import WebsocketClient def message_handler(message): print(message) # Expected message: # { # 'e': 'depthUpdate', # 'E': 1699123456789, # 'T': 1699123456785, # 's': 'BTCUSDT', # 'U': 123456780, # 'u': 123456789, # 'pu': 123456779, # 'b': [['58999.00', '1.500'], ['58998.00', '2.300'], ...], # 'a': [['59001.00', '0.750'], ['59002.00', '1.200'], ...] # } ws_client = WebsocketClient() ws_client.start() ws_client.partial_book_depth( symbol='btcusdt', id=1, level=10, # 5, 10, or 20 speed=500, # 100, 250, or 500 ms callback=message_handler ) time.sleep(30) ws_client.stop() ``` -------------------------------- ### Get Order Book Depth Source: https://context7.com/asterdex/aster-connector-python/llms.txt Retrieve the order book for a symbol with an optional limit parameter. ```python from aster.rest_api import Client client = Client() # Get order book with default limit response = client.depth(symbol='BTCUSDT') print(response) # Get order book with specific limit response = client.depth(symbol='BTCUSDT', limit=10) print(response) # Expected output: # { # 'lastUpdateId': 123456789, # 'bids': [['59000.00', '1.500'], ['58999.00', '2.300'], ...], # 'asks': [['59001.00', '0.750'], ['59002.00', '1.200'], ...] # } ``` -------------------------------- ### Get Account Balance Source: https://context7.com/asterdex/aster-connector-python/llms.txt Retrieves futures account balance information. This includes details like asset, balance, unrealized PnL, and available balance. ```python response = client.balance() print(response) ``` -------------------------------- ### Get Symbol Price Ticker Source: https://context7.com/asterdex/aster-connector-python/llms.txt Retrieves the latest price for a specific symbol or all symbols. ```python from aster.rest_api import Client client = Client() # Single symbol response = client.ticker_price(symbol='BTCUSDT') print(response) # All symbols all_prices = client.ticker_price() ``` -------------------------------- ### GET /all_orders Source: https://context7.com/asterdex/aster-connector-python/llms.txt Retrieves the complete history of account orders including active, canceled, or filled orders. ```APIDOC ## GET /all_orders ### Description Retrieves all account orders: active, canceled, or filled. ### Parameters #### Query Parameters - **symbol** (string) - Optional - The trading symbol - **limit** (integer) - Optional - Result limit - **startTime** (long) - Optional - Start time in milliseconds - **endTime** (long) - Optional - End time in milliseconds ``` -------------------------------- ### GET /position_risk Source: https://context7.com/asterdex/aster-connector-python/llms.txt Retrieves current position information including unrealized PnL for a symbol. ```APIDOC ## GET /position_risk ### Description Retrieves current position information including unrealized PnL. ### Parameters #### Query Parameters - **symbol** (string) - Required - The trading symbol ``` -------------------------------- ### Get Mark Price Klines Source: https://context7.com/asterdex/aster-connector-python/llms.txt Retrieves kline/candlestick data for the mark price of a symbol. ```python from aster.rest_api import Client client = Client() response = client.mark_price_klines(symbol='BTCUSDT', interval='1h', limit=50) print(response) ``` -------------------------------- ### GET /open_orders Source: https://context7.com/asterdex/aster-connector-python/llms.txt Retrieves current open orders, with options to filter by symbol or specific order ID. ```APIDOC ## GET /open_orders ### Description Retrieves current open orders. Can filter by symbol or get all open orders. ### Parameters #### Query Parameters - **symbol** (string) - Optional - The trading symbol - **orderId** (integer) - Optional - The specific order ID ``` -------------------------------- ### Get and Change Multi-Assets Mode Source: https://context7.com/asterdex/aster-connector-python/llms.txt Retrieves or modifies the multi-assets mode, which impacts how margin is calculated across different assets. Setting it to true enables this mode. ```python # Get current mode response = client.get_multi_asset_mode() print(response) ``` ```python # Change mode response = client.change_multi_asset_mode(multiAssetsMargin='true') print(response) ``` -------------------------------- ### Get Index Price Klines Source: https://context7.com/asterdex/aster-connector-python/llms.txt Retrieves kline/candlestick data for the index price of a trading pair. ```python from aster.rest_api import Client client = Client() response = client.index_price_klines(pair='BTCUSDT', interval='1h', limit=50) print(response) ``` -------------------------------- ### GET /agg_trades Source: https://context7.com/asterdex/aster-connector-python/llms.txt Retrieves aggregated trades for a specific symbol with optional time filters. ```APIDOC ## GET /agg_trades ### Description Retrieves aggregated trades for a symbol. ### Parameters #### Query Parameters - **symbol** (string) - Required - The trading pair symbol - **limit** (integer) - Optional - Number of results - **startTime** (long) - Optional - Start time in ms - **endTime** (long) - Optional - End time in ms ### Response #### Success Response (200) - **a** (long) - Aggregate trade ID - **p** (string) - Price - **q** (string) - Quantity - **f** (long) - First trade ID - **l** (long) - Last trade ID - **T** (long) - Timestamp - **m** (boolean) - Was the buyer the maker? ``` -------------------------------- ### Get 24hr Ticker Price Change Statistics Source: https://context7.com/asterdex/aster-connector-python/llms.txt Retrieves 24-hour rolling window price change statistics for a single symbol or all symbols. ```python from aster.rest_api import Client client = Client() # Single symbol response = client.ticker_24hr_price_change(symbol='BTCUSDT') print(response) # All symbols (returns array) all_tickers = client.ticker_24hr_price_change() ``` -------------------------------- ### Get All Orders History Source: https://context7.com/asterdex/aster-connector-python/llms.txt Retrieves a history of all account orders, including active, canceled, and filled orders. You can specify a symbol, limit, and time range for the query. ```python response = client.get_all_orders( symbol='BTCUSDT', limit=100, startTime=1699000000000, endTime=1699123456789 ) print(response) ``` -------------------------------- ### Get Position Risk Source: https://context7.com/asterdex/aster-connector-python/llms.txt Retrieves current position risk details for a given symbol, including position amount, entry price, mark price, unrealized PnL, and liquidation price. ```python response = client.get_position_risk(symbol='BTCUSDT') print(response) ``` -------------------------------- ### Get Symbol Order Book Ticker Source: https://context7.com/asterdex/aster-connector-python/llms.txt Retrieves the best bid and ask prices and quantities for a symbol or all symbols. ```python from aster.rest_api import Client client = Client() # Single symbol response = client.book_ticker(symbol='BTCUSDT') print(response) ``` -------------------------------- ### Get Funding Rate History Source: https://context7.com/asterdex/aster-connector-python/llms.txt Retrieves historical funding rate records for a symbol within a specified time range. ```python from aster.rest_api import Client client = Client() response = client.funding_rate( symbol='BTCUSDT', limit=100, startTime=1699000000000, endTime=1699123456789 ) print(response) ``` -------------------------------- ### Get and Change Position Mode Source: https://context7.com/asterdex/aster-connector-python/llms.txt Manages the position mode (Hedge Mode or One-way Mode) for all symbols. Hedge Mode allows holding positions in both long and short directions simultaneously for a symbol. ```python # Get current position mode response = client.get_position_mode() print(response) ``` ```python # Change position mode response = client.change_position_mode(dualSidePosition='true') # Enable Hedge Mode print(response) ``` -------------------------------- ### Get Open Orders Source: https://context7.com/asterdex/aster-connector-python/llms.txt Retrieves current open orders. You can filter by order ID for a specific order or retrieve all open orders for a symbol or across all symbols. ```python response = client.get_open_orders(symbol='BTCUSDT', orderId=123456789) print(response) ``` ```python response = client.get_orders(symbol='BTCUSDT') print(response) ``` ```python response = client.get_orders() print(response) ``` -------------------------------- ### Get Aggregated Trades Source: https://context7.com/asterdex/aster-connector-python/llms.txt Retrieves aggregated trade data for a specific symbol with optional time filters. ```python response = client.agg_trades( symbol='BTCUSDT', limit=100, startTime=1699000000000, endTime=1699123456789 ) print(response) ``` -------------------------------- ### Get Kline/Candlestick Data Source: https://context7.com/asterdex/aster-connector-python/llms.txt Retrieves kline bars for a symbol. Supported intervals include 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, and 1M. ```python from aster.rest_api import Client client = Client() response = client.klines( symbol='BTCUSDT', interval='1h', limit=100, startTime=1699000000000, endTime=1699123456789 ) print(response) ``` -------------------------------- ### Initialize Client to Show Full Response Header Source: https://github.com/asterdex/aster-connector-python/blob/master/README.md Initialize the client with `show_header=True` to display the full response metadata for debugging purposes. ```python client = Client(show_header=True) print(client.time()) ``` -------------------------------- ### Configure Client with Proxy Source: https://github.com/asterdex/aster-connector-python/blob/master/README.md Initialize the client with proxy settings to route requests through a specified proxy server. ```python from aster.rest_api import Client proxies = { 'https': 'http://1.2.3.4:8080' } client= Client(proxies=proxies) ``` -------------------------------- ### Initialize WebSocket Client Source: https://context7.com/asterdex/aster-connector-python/llms.txt Sets up the WebSocket client for real-time data streaming with automatic heartbeat management. ```python from aster.websocket.client.stream import WebsocketClient def message_handler(message): print(f"Received: {message}") # Initialize WebSocket client ws_client = WebsocketClient() # Custom stream URL (optional) # ws_client = WebsocketClient(stream_url="wss://fstream.asterdex.com") # Start the client ws_client.start() # Subscribe to streams here... # Stop the client when done ws_client.stop() ``` -------------------------------- ### Initialize Client to Show Response Limit Usage Source: https://github.com/asterdex/aster-connector-python/blob/master/README.md Initialize the client with `show_limit_usage=True` to display API rate limit usage information from response headers. ```python from aster.rest_api import Client client = Client(show_limit_usage=True) print(client.time()) ``` -------------------------------- ### Initialize REST API Client Source: https://context7.com/asterdex/aster-connector-python/llms.txt Configure the client with API credentials, timeouts, and proxy settings. Use the key and secret parameters for authenticated requests. ```python from aster.rest_api import Client # Basic client for public endpoints (no authentication required) client = Client() # Authenticated client with API credentials client = Client(key='your_api_key', secret='your_api_secret') # Client with all configuration options client = Client( key='your_api_key', secret='your_api_secret', timeout=10, # Request timeout in seconds proxies={'https': 'http://1.2.3.4:8080'}, # Proxy configuration show_limit_usage=True, # Show API rate limit usage in response show_header=True # Show full response headers ) # Response with limit usage enabled # Returns: {'data': {...}, 'limit_usage': {'x-mbx-used-weight': '1'}} print(client.time()) ``` -------------------------------- ### Initialize WebSocket Client and Subscribe to Mini Ticker Source: https://github.com/asterdex/aster-connector-python/blob/master/README.md Connect to the WebSocket stream, define a message handler, and subscribe to the mini ticker stream for a specific symbol. ```python from aster.websocket.client.stream import WebsocketClient as Client def message_handler(message): print(message) ws_client = Client() ws_client.start() ws_client.mini_ticker( symbol='bnbusdt', id=1, callback=message_handler, ) ``` -------------------------------- ### WebSocket Client Initialization Source: https://context7.com/asterdex/aster-connector-python/llms.txt Initializes and manages the WebSocket client for real-time data streams. ```APIDOC ## WebSocket Client Initialization ### Description The WebSocket client enables real-time streaming of market data and user data. It automatically handles ping/pong heartbeats. ### Initialization ```python from aster.websocket.client.stream import WebsocketClient def message_handler(message): print(f"Received: {message}") # Initialize WebSocket client ws_client = WebsocketClient() # Custom stream URL (optional) # ws_client = WebsocketClient(stream_url="wss://fstream.asterdex.com") ``` ### Usage 1. **Start the client**: Call the `start()` method to begin the WebSocket connection and message handling. ```python ws_client.start() ``` 2. **Subscribe to streams**: Add your stream subscription logic after starting the client. This typically involves sending subscription messages to the WebSocket server. ```python # Subscribe to streams here... # Example: ws_client.subscribe(streams=['btcusdt@trade']) ``` 3. **Stop the client**: Call the `stop()` method to gracefully close the WebSocket connection. ```python ws_client.stop() ``` ### Message Handling Provide a callback function to the `WebsocketClient` to process incoming messages. ```python ws_client = WebsocketClient(on_message=message_handler) ``` ``` -------------------------------- ### Retrieve Leverage Brackets Source: https://context7.com/asterdex/aster-connector-python/llms.txt Fetches the notional and leverage bracket configurations for a specific symbol. ```python from aster.rest_api import Client client = Client(key='your_api_key', secret='your_api_secret') response = client.leverage_brackets(symbol='BTCUSDT') print(response) ``` -------------------------------- ### Query Order with RecvWindow Parameter Source: https://github.com/asterdex/aster-connector-python/blob/master/README.md Set a custom receive window for signed endpoints to control the time allowed for server response. The value must be between 0 and 60000 milliseconds. ```python from aster.rest_api import Client client = Client(key, secret) response = client.query_order('BTCUSDT', orderId=11, recvWindow=10000) ``` -------------------------------- ### REST API Client Initialization Source: https://context7.com/asterdex/aster-connector-python/llms.txt Initialize the REST API Client for making authenticated and unauthenticated requests. Supports configuration for API keys, timeouts, proxies, and response details. ```APIDOC ## REST API Client Initialization ### Description The REST API Client is the main entry point for making authenticated and unauthenticated requests to the Aster Finance API. It supports various configuration options including API credentials, timeouts, proxies, and response metadata display. ### Request Example ```python from aster.rest_api import Client # Basic client for public endpoints (no authentication required) client = Client() # Authenticated client with API credentials client = Client(key='your_api_key', secret='your_api_secret') # Client with all configuration options client = Client( key='your_api_key', secret='your_api_secret', timeout=10, # Request timeout in seconds proxies={'https': 'http://1.2.3.4:8080'}, # Proxy configuration show_limit_usage=True, # Show API rate limit usage in response show_header=True # Show full response headers ) # Response with limit usage enabled # Returns: {'data': {...}, 'limit_usage': {'x-mbx-used-weight': '1'}} print(client.time()) ``` ``` -------------------------------- ### Place Multiple Orders (Batch) Source: https://context7.com/asterdex/aster-connector-python/llms.txt Submits up to 5 orders in a single request. ```python from aster.rest_api import Client from aster.error import ClientError client = Client(key='your_api_key', secret='your_api_secret') try: batch_orders = [ { 'symbol': 'BTCUSDT', 'side': 'BUY', 'type': 'LIMIT', 'quantity': '0.001', 'price': '58000', 'timeInForce': 'GTC' }, { 'symbol': 'BTCUSDT', 'side': 'SELL', 'type': 'LIMIT', 'quantity': '0.001', 'price': '62000', 'timeInForce': 'GTC' } ] response = client.new_batch_order(batchOrders=batch_orders) print(response) except ClientError as error: print(f"Error: {error.error_message}") ``` -------------------------------- ### Manage User Data Stream Listen Key Source: https://context7.com/asterdex/aster-connector-python/llms.txt Handles the lifecycle of a listen key, including creation, renewal, and closure for WebSocket streams. ```python from aster.rest_api import Client client = Client(key='your_api_key') # Create a new listen key response = client.new_listen_key() listen_key = response['listenKey'] print(f"Listen Key: {listen_key}") # Renew/keepalive the listen key (call every 30 minutes) client.renew_listen_key(listenKey=listen_key) # Close the listen key when done client.close_listen_key(listenKey=listen_key) ``` -------------------------------- ### Query Order with Unrecognized Parameter Naming Source: https://github.com/asterdex/aster-connector-python/blob/master/README.md Demonstrates that using PEP8 style naming (e.g., order_list_id) for parameters will result in an unrecognized parameter error. ```python # Unrecognised parameter name response = client.query_order('BTCUSDT', order_list_id=1) ``` -------------------------------- ### Query Order with Correct Parameter Naming Source: https://github.com/asterdex/aster-connector-python/blob/master/README.md Use the exact parameter naming as specified in the API documentation for querying orders. ```python # Recognised parameter name response = client.query_order('BTCUSDT', orderListId=1) ``` -------------------------------- ### Subscribe to Multiple WebSocket Streams Simultaneously Source: https://context7.com/asterdex/aster-connector-python/llms.txt Utilizes the `instant_subscribe` method to connect to and receive data from multiple WebSocket streams concurrently. This is efficient for monitoring various market events or symbols at once. The `callback` function processes messages from all subscribed streams. ```python import time from aster.websocket.client.stream import WebsocketClient def message_handler(message): print(message) ws_client = WebsocketClient() ws_client.start() # Subscribe to multiple streams at once ws_client.instant_subscribe( stream=['btcusdt@bookTicker', 'ethusdt@bookTicker', 'btcusdt@aggTrade'], callback=message_handler ) time.sleep(60) ws_client.stop() ``` -------------------------------- ### Retrieve Force Orders Source: https://context7.com/asterdex/aster-connector-python/llms.txt Fetches liquidation or force orders associated with the user account. ```python from aster.rest_api import Client client = Client(key='your_api_key', secret='your_api_secret') response = client.force_orders( symbol='BTCUSDT', autoCloseType='LIQUIDATION', limit=50 ) print(response) ``` -------------------------------- ### Subscribe to Liquidation Order Stream Source: https://context7.com/asterdex/aster-connector-python/llms.txt Subscribes to force liquidation order information for a single symbol or the entire market. ```python import time from aster.websocket.client.stream import WebsocketClient def message_handler(message): print(message) ws_client = WebsocketClient() ws_client.start() # Single symbol ws_client.liquidation_order(symbol='btcusdt', id=1, callback=message_handler) # All market ws_client.liquidation_order(id=2, callback=message_handler) time.sleep(60) ws_client.stop() ``` -------------------------------- ### User Data Stream - Listen Key Management Source: https://context7.com/asterdex/aster-connector-python/llms.txt Manages listen keys for establishing and maintaining WebSocket user data streams. ```APIDOC ## User Data Stream - Listen Key Management ### Description Creates, renews, or closes a listen key for WebSocket user data streams. ### Methods - **new_listen_key()**: Creates a new listen key. - **renew_listen_key(listenKey)**: Renews an existing listen key. - **close_listen_key(listenKey)**: Closes an existing listen key. ### Parameters #### new_listen_key() No parameters required. #### renew_listen_key(listenKey) - **listenKey** (string) - Required - The listen key to renew. #### close_listen_key(listenKey) - **listenKey** (string) - Required - The listen key to close. ### Response #### new_listen_key() - **listenKey** (string) - The newly created listen key. #### renew_listen_key() and close_listen_key() These methods typically return an empty object or a success confirmation upon successful execution. ### Usage Example ```python from aster.rest_api import Client client = Client(key='your_api_key') # Create a new listen key response = client.new_listen_key() listen_key = response['listenKey'] print(f"Listen Key: {listen_key}") # Renew/keepalive the listen key (call every 30 minutes) client.renew_listen_key(listenKey=listen_key) # Close the listen key when done client.close_listen_key(listenKey=listen_key) ``` ``` -------------------------------- ### Subscribe to Mark Price Stream Source: https://context7.com/asterdex/aster-connector-python/llms.txt Subscribes to mark price and funding rate updates with configurable update speeds. ```python import time from aster.websocket.client.stream import WebsocketClient def message_handler(message): print(message) # Expected message: # { # 'e': 'markPriceUpdate', # 'E': 1699123456789, # 's': 'BTCUSDT', # 'p': '59000.00000000', # 'i': '58990.00000000', # 'P': '59005.00000000', # 'r': '0.00010000', # 'T': 1699171200000 # } ws_client = WebsocketClient() ws_client.start() # Default 3-second updates ws_client.mark_price(symbol='btcusdt', id=1, callback=message_handler) # Or 1-second updates ws_client.mark_price(symbol='btcusdt', id=2, callback=message_handler, speed=1) time.sleep(30) ws_client.stop() ``` -------------------------------- ### Combine Selected WebSocket Streams Source: https://github.com/asterdex/aster-connector-python/blob/master/README.md Subscribe to multiple WebSocket streams simultaneously by providing a list of stream names to the `instant_subscribe` method. ```python # Combine selected streams ws_client.instant_subscribe( stream=['bnbusdt@bookTicker', 'ethusdt@bookTicker'], callback=message_handler, ) ``` -------------------------------- ### Fetch All Book Tickers Source: https://context7.com/asterdex/aster-connector-python/llms.txt Retrieves the current book ticker information for all symbols. ```python all_book_tickers = client.book_ticker() ``` -------------------------------- ### Retrieve Server Time Source: https://context7.com/asterdex/aster-connector-python/llms.txt Fetch the current server time to synchronize local timestamps for signed requests. ```python from aster.rest_api import Client client = Client() response = client.time() print(response) # Expected output: {'serverTime': 1699123456789} ``` -------------------------------- ### Post a New Limit Order Source: https://github.com/asterdex/aster-connector-python/blob/master/README.md Submit a new limit order with specified parameters. Ensure all required fields like symbol, side, type, quantity, and price are provided. ```python params = { 'symbol': 'BTCUSDT', 'side': 'SELL', 'type': 'LIMIT', 'timeInForce': 'GTC', 'quantity': 0.002, 'price': 59808 } response = client.new_order(**params) print(response) ``` -------------------------------- ### Subscribe to Mini Ticker Stream Source: https://context7.com/asterdex/aster-connector-python/llms.txt Subscribes to 24hr rolling window mini-ticker statistics for a single symbol or the entire market. ```python import time from aster.websocket.client.stream import WebsocketClient def message_handler(message): print(message) ws_client = WebsocketClient() ws_client.start() # Single symbol ws_client.mini_ticker( symbol='btcusdt', id=1, callback=message_handler ) # All market ws_client.mini_ticker( id=2, callback=message_handler ) time.sleep(30) ws_client.stop() ``` -------------------------------- ### Place New Futures Orders Source: https://context7.com/asterdex/aster-connector-python/llms.txt Creates new futures orders using various order types. Requires authentication via API key and secret. ```python import logging from aster.rest_api import Client from aster.error import ClientError client = Client(key='your_api_key', secret='your_api_secret') try: # Place a LIMIT order response = client.new_order( symbol='BTCUSDT', side='BUY', type='LIMIT', quantity=0.001, price=58000.00, timeInForce='GTC' # Good Till Cancelled ) print(response) # Expected output: # { # 'orderId': 123456789, # 'symbol': 'BTCUSDT', # 'status': 'NEW', # 'clientOrderId': 'abc123', # 'price': '58000.00', # 'avgPrice': '0.00', # 'origQty': '0.001', # 'executedQty': '0.000', # 'type': 'LIMIT', # 'side': 'BUY', # 'timeInForce': 'GTC', # 'updateTime': 1699123456789 # } # Place a MARKET order market_response = client.new_order( symbol='BTCUSDT', side='SELL', type='MARKET', quantity=0.001 ) print(market_response) except ClientError as error: logging.error(f"Error: status={error.status_code}, code={error.error_code}, message={error.error_message}") ``` -------------------------------- ### Auto-Cancel All Open Orders (Countdown) Source: https://context7.com/asterdex/aster-connector-python/llms.txt Sets a countdown timer to automatically cancel all open orders for a symbol. Set countdownTime to 0 to disable. ```python from aster.rest_api import Client client = Client(key='your_api_key', secret='your_api_secret') # Set countdown to cancel orders in 30 seconds (30000 ms) response = client.countdown_cancel_order(symbol='BTCUSDT', countdownTime=30000) print(response) # Expected output: # { # 'symbol': 'BTCUSDT', # 'countdownTime': 30000 # } ``` -------------------------------- ### POST /change_leverage Source: https://context7.com/asterdex/aster-connector-python/llms.txt Updates the initial leverage for a specific trading symbol. ```APIDOC ## POST /change_leverage ### Description Changes the initial leverage for a specific symbol. ### Parameters #### Request Body - **symbol** (string) - Required - The trading symbol - **leverage** (integer) - Required - Leverage value ``` -------------------------------- ### Test API Connectivity Source: https://context7.com/asterdex/aster-connector-python/llms.txt Verify connection to the REST API using the ping endpoint. ```python from aster.rest_api import Client client = Client() response = client.ping() print(response) # Expected output: {} ``` -------------------------------- ### Force Orders (Liquidation Orders) Source: https://context7.com/asterdex/aster-connector-python/llms.txt Retrieves a user's force or liquidation orders for a given symbol. ```APIDOC ## GET /api/v1/force_orders ### Description Retrieves user's force/liquidation orders. ### Method GET ### Endpoint /api/v1/force_orders ### Parameters #### Query Parameters - **symbol** (string) - Required - The trading symbol (e.g., BTCUSDT). - **autoCloseType** (string) - Required - The type of force order ('LIQUIDATION'). - **limit** (integer) - Optional - The number of orders to retrieve (default 50). ### Response #### Success Response (200) (Response structure depends on the specific order details, typically an array of order objects.) ### Request Example ```python response = client.force_orders( symbol='BTCUSDT', autoCloseType='LIQUIDATION', limit=50 ) ``` ``` -------------------------------- ### Subscribe to Kline/Candlestick Stream Source: https://context7.com/asterdex/aster-connector-python/llms.txt Subscribes to kline updates pushed every 250 milliseconds for a specific interval. ```python import time from aster.websocket.client.stream import WebsocketClient def message_handler(message): print(message) # Expected message: # { # 'e': 'kline', # 'E': 1699123456789, # 's': 'BTCUSDT', # 'k': { # 't': 1699120800000, # 'T': 1699124399999, # 's': 'BTCUSDT', # 'i': '1h', # 'o': '59000.00', # 'c': '59200.00', # 'h': '59500.00', # 'l': '58900.00', # 'v': '1500.500', # 'n': 5000, # 'x': False, # 'q': '88950000.00' # } # } ws_client = WebsocketClient() ws_client.start() ws_client.kline( symbol='btcusdt', id=1, interval='1h', callback=message_handler ) time.sleep(60) ws_client.stop() ``` -------------------------------- ### Handle Aster REST API Errors Source: https://context7.com/asterdex/aster-connector-python/llms.txt Demonstrates how to catch and handle specific exceptions raised by the Aster REST API client. This includes `ClientError` for 4xx responses, `ServerError` for 5xx responses, and `ParameterRequiredError` for missing mandatory parameters. Each exception provides details about the error. ```python from aster.rest_api import Client from aster.error import ClientError, ServerError, ParameterRequiredError client = Client(key='your_api_key', secret='your_api_secret') try: # Attempt an operation response = client.new_order( symbol='BTCUSDT', side='BUY', type='LIMIT', quantity=0.001, price=58000.00, timeInForce='GTC' ) except ClientError as e: # 4XX errors - client-side issues print(f"Client Error (HTTP {e.status_code})") print(f"Error Code: {e.error_code}") print(f"Error Message: {e.error_message}") print(f"Response Headers: {e.header}") except ServerError as e: # 5XX errors - server-side issues print(f"Server Error (HTTP {e.status_code})") print(f"Message: {e.message}") except ParameterRequiredError as e: # Missing required parameters print(f"Missing parameters: {e.params}") ``` -------------------------------- ### Subscribe to Book Ticker Stream Source: https://context7.com/asterdex/aster-connector-python/llms.txt Subscribes to real-time best bid/ask price and quantity updates. ```python import time from aster.websocket.client.stream import WebsocketClient def message_handler(message): print(message) # Expected message: # { # 'e': 'bookTicker', # 'u': 123456789, # 's': 'BTCUSDT', # 'b': '58999.00', # 'B': '1.500', # 'a': '59001.00', # 'A': '2.000', # 'T': 1699123456789, # 'E': 1699123456790 # } ws_client = WebsocketClient() ws_client.start() # Single symbol ws_client.book_ticker(symbol='btcusdt', id=1, callback=message_handler) # All symbols ws_client.book_ticker(id=2, callback=message_handler) time.sleep(30) ws_client.stop() ``` -------------------------------- ### Set Request Timeout Source: https://github.com/asterdex/aster-connector-python/blob/master/README.md Configure a custom timeout in seconds for waiting for a server response. If no response is received within this time, a timeout error will occur. ```python from aster.rest_api import Client client= Client(timeout=1) ``` -------------------------------- ### Leverage Brackets Source: https://context7.com/asterdex/aster-connector-python/llms.txt Retrieves notional and leverage brackets for a given symbol. ```APIDOC ## GET /api/v1/leverage_brackets ### Description Retrieves notional and leverage brackets for symbols. ### Method GET ### Endpoint /api/v1/leverage_brackets ### Parameters #### Query Parameters - **symbol** (string) - Required - The trading symbol (e.g., BTCUSDT). ### Response #### Success Response (200) - **symbol** (string) - The trading symbol. - **brackets** (array) - A list of leverage brackets. - **bracket** (integer) - The bracket level. - **initialLeverage** (integer) - The initial leverage for this bracket. - **notionalCap** (number) - The maximum notional value for this bracket. - **notionalFloor** (number) - The minimum notional value for this bracket. - **maintMarginRatio** (number) - The maintenance margin ratio for this bracket. #### Response Example ```json [ { "symbol": "BTCUSDT", "brackets": [ { "bracket": 1, "initialLeverage": 125, "notionalCap": 50000, "notionalFloor": 0, "maintMarginRatio": 0.004 } ] } ] ``` ``` -------------------------------- ### Subscribe to Aggregate Trade Stream Source: https://context7.com/asterdex/aster-connector-python/llms.txt Subscribes to aggregated trade data updates pushed every 100 milliseconds. ```python import time from aster.websocket.client.stream import WebsocketClient def message_handler(message): print(message) # Expected message: # { # 'e': 'aggTrade', # 'E': 1699123456789, # 's': 'BTCUSDT', # 'a': 123456, # 'p': '59000.00', # 'q': '0.100', # 'f': 100000, # 'l': 100002, # 'T': 1699123456780, # 'm': False # } ws_client = WebsocketClient() ws_client.start() ws_client.agg_trade( symbol='btcusdt', id=1, callback=message_handler ) time.sleep(60) ws_client.stop() ``` -------------------------------- ### Subscribe to Ticker Stream Source: https://context7.com/asterdex/aster-connector-python/llms.txt Subscribes to 24hr rolling window ticker statistics for a single symbol or all symbols. ```python import time from aster.websocket.client.stream import WebsocketClient def message_handler(message): print(message) ws_client = WebsocketClient() ws_client.start() # Single symbol ws_client.ticker(symbol='btcusdt', id=1, callback=message_handler) # All symbols ws_client.ticker(id=2, callback=message_handler) time.sleep(30) ws_client.stop() ``` -------------------------------- ### Exchange Information Source: https://context7.com/asterdex/aster-connector-python/llms.txt Fetches current exchange trading rules and detailed symbol information, including price filters and lot sizes. ```APIDOC ## Exchange Information ### Description Returns current exchange trading rules and symbol information including price filters, lot sizes, and available trading pairs. ### Method GET ### Endpoint /api/v1/exchangeInfo ### Parameters None ### Request Example ```python from aster.rest_api import Client client = Client() response = client.exchange_info() print(response) # Expected output: # { # 'exchangeFilters': [], # 'rateLimits': [...], # 'serverTime': 1699123456789, # 'symbols': [ # { # 'symbol': 'BTCUSDT', # 'pair': 'BTCUSDT', # 'contractType': 'PERPETUAL', # 'baseAsset': 'BTC', # 'quoteAsset': 'USDT', # 'filters': [...] # }, # ... # ] # } ``` ### Response #### Success Response (200) - **exchangeFilters** (array) - List of exchange-wide filters. - **rateLimits** (array) - List of rate limit rules. - **serverTime** (integer) - Server time in milliseconds. - **symbols** (array) - List of trading symbols with their details and filters. ``` -------------------------------- ### Retrieve Aggregated Trades Source: https://context7.com/asterdex/aster-connector-python/llms.txt Fetch compressed trade data where trades with identical properties are aggregated. ```python from aster.rest_api import Client client = Client() ``` -------------------------------- ### Retrieve Account Trade List Source: https://context7.com/asterdex/aster-connector-python/llms.txt Fetches a list of trades for a specific account and symbol within a defined time range. ```python from aster.rest_api import Client client = Client(key='your_api_key', secret='your_api_secret') response = client.get_account_trades( symbol='BTCUSDT', limit=50, startTime=1699000000000, endTime=1699123456789 ) print(response) ``` -------------------------------- ### Retrieve Income History Source: https://context7.com/asterdex/aster-connector-python/llms.txt Retrieves historical income records such as realized PnL, funding fees, and commissions. ```python from aster.rest_api import Client client = Client(key='your_api_key', secret='your_api_secret') response = client.get_income_history( symbol='BTCUSDT', incomeType='REALIZED_PNL', limit=100 ) print(response) ``` -------------------------------- ### Test Connectivity Source: https://context7.com/asterdex/aster-connector-python/llms.txt Tests connectivity to the Aster REST API without requiring authentication. Returns an empty response upon successful connection. ```APIDOC ## Test Connectivity ### Description The ping endpoint tests connectivity to the Aster REST API without authentication. Returns an empty response on success. ### Method GET ### Endpoint /api/v1/ping ### Parameters None ### Request Example ```python from aster.rest_api import Client client = Client() response = client.ping() print(response) # Expected output: {} ``` ### Response #### Success Response (200) - **Empty Object** - Indicates successful connection. ``` -------------------------------- ### Change Leverage Source: https://context7.com/asterdex/aster-connector-python/llms.txt Changes the initial leverage for a specified trading symbol. Ensure the leverage value is within the allowed limits for the symbol. ```python response = client.change_leverage(symbol='BTCUSDT', leverage=10) print(response) ``` -------------------------------- ### Income History Source: https://context7.com/asterdex/aster-connector-python/llms.txt Retrieves the income history for an account, including realized PnL, funding fees, and commissions. ```APIDOC ## GET /api/v1/income/history ### Description Retrieves income history including realized PnL, funding fees, and commissions. ### Method GET ### Endpoint /api/v1/income/history ### Parameters #### Query Parameters - **symbol** (string) - Required - The trading symbol (e.g., BTCUSDT). - **incomeType** (string) - Optional - The type of income to retrieve (e.g., 'REALIZED_PNL', 'FUNDING_FEE', 'COMMISSION'). - **limit** (integer) - Optional - The number of records to retrieve (default 100). - **startTime** (integer) - Optional - The start time in milliseconds. - **endTime** (integer) - Optional - The end time in milliseconds. ### Response #### Success Response (200) - **symbol** (string) - The trading symbol. - **incomeType** (string) - The type of income. - **income** (string) - The amount of income. - **asset** (string) - The asset associated with the income. - **time** (integer) - The timestamp of the income event in milliseconds. - **info** (string) - Additional information about the income event (e.g., 'TRADE', 'FUNDING_FEE'). - **tranId** (integer) - The transaction ID. - **tradeId** (string) - The trade ID, if applicable. #### Response Example ```json [ { "symbol": "BTCUSDT", "incomeType": "REALIZED_PNL", "income": "10.50000000", "asset": "USDT", "time": 1699123456789, "info": "TRADE", "tranId": 123456789, "tradeId": "789012" } ] ``` ``` -------------------------------- ### Subscribe to WebSocket User Data Stream Source: https://context7.com/asterdex/aster-connector-python/llms.txt Connects to a private WebSocket stream to receive real-time updates on account activity, orders, and positions. Requires obtaining a `listenKey` from the REST API and periodically renewing it to maintain the connection. The `message_handler` processes events like `ACCOUNT_UPDATE` and `ORDER_TRADE_UPDATE`. ```python import time import logging from aster.rest_api import Client from aster.websocket.client.stream import WebsocketClient logging.basicConfig(level=logging.DEBUG) def message_handler(message): print(f"User Data: {message}") # Expected messages include: # - ACCOUNT_UPDATE: Balance and position changes # - ORDER_TRADE_UPDATE: Order execution reports # - MARGIN_CALL: Margin call warnings # Get listen key from REST API api_key = 'your_api_key' api_secret = 'your_api_secret' rest_client = Client(key=api_key, secret=api_secret) response = rest_client.new_listen_key() listen_key = response['listenKey'] logging.info(f"Listen key: {listen_key}") # Connect WebSocket ws_client = WebsocketClient() ws_client.start() ws_client.user_data( listen_key=listen_key, id=1, callback=message_handler ) # Keep connection alive - renew listen key every 30 minutes try: while True: time.sleep(1800) # 30 minutes rest_client.renew_listen_key(listenKey=listen_key) logging.info("Listen key renewed") except KeyboardInterrupt: pass finally: ws_client.stop() rest_client.close_listen_key(listenKey=listen_key) ``` -------------------------------- ### Cancel Multiple Orders (Batch) Source: https://context7.com/asterdex/aster-connector-python/llms.txt Cancels multiple orders using a list of order IDs or client order IDs. ```python from aster.rest_api import Client client = Client(key='your_api_key', secret='your_api_secret') response = client.cancel_batch_order( symbol='BTCUSDT', orderIdList=[123456789, 123456790], origClientOrderIdList=[] ) print(response) ``` -------------------------------- ### Check Server Time Source: https://context7.com/asterdex/aster-connector-python/llms.txt Retrieves the current server time from the Aster API, useful for timestamp synchronization for signed requests. ```APIDOC ## Check Server Time ### Description Retrieves the current server time from the Aster API. Useful for synchronizing local timestamps with server time for signed requests. ### Method GET ### Endpoint /api/v1/time ### Parameters None ### Request Example ```python from aster.rest_api import Client client = Client() response = client.time() print(response) # Expected output: {'serverTime': 1699123456789} ``` ### Response #### Success Response (200) - **serverTime** (integer) - The current server time in milliseconds since the Unix epoch. ```