### Example Usage of Spot Order Type Hint Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/6-types-and-errors.md Example demonstrating the usage of 'LIMIT' order type with type hinting. ```python # Limit order order = client.order( symbol="BTCUSDT", side="BUY", order_type="LIMIT", quantity=0.1, price=30000 ) # Market order order = client.order( symbol="BTCUSDT", side="BUY", order_type="MARKET", quote_order_qty=100 # Buy $100 worth ) ``` -------------------------------- ### Example Usage of Order Side Type Hint Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/6-types-and-errors.md Example demonstrating the usage of the 'BUY' order side with type hinting. ```python order = client.order( symbol="BTCUSDT", side="BUY", # Type: Literal["BUY", "SELL"] order_type="LIMIT", quantity=0.1, price=30000 ) ``` -------------------------------- ### Example Usage of Kline Interval Type Hint (Spot) Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/6-types-and-errors.md Example demonstrating the usage of '1h' kline interval with type hinting. ```python klines = client.klines( symbol="BTCUSDT", interval="1h", # Type: Literal["1m", "5m", ...] limit=100 ) ``` -------------------------------- ### Install pymexc Library Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/0-overview.md Install the pymexc library using pip. Ensure you have Python 3.9.0 or higher. ```bash pip install pymexc ``` -------------------------------- ### Example Usage of Futures Order Side Type Hint Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/6-types-and-errors.md Example demonstrating the usage of 'OPEN_LONG' (value 1) for a futures order with type hinting. ```python order = client.order( symbol="BTC_USDT", side=1, # OPEN_LONG type=5, # MARKET vol=0.1, leverage=4, open_type=1 # ISOLATED ) ``` -------------------------------- ### Configuration Reference Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/README.md Configuration and setup reference for the pymexc library, covering client configuration, proxy setup, environment variables, and rate limiting. ```APIDOC ## Configuration Reference ### Description Configuration and setup reference. ### Topics - **Client Configuration**: all constructor parameters for all client types - **HTTP Proxy Setup**: configure proxies with authentication - **Environment Variables**: managing credentials safely with .env files - **WebSocket Configuration**: ping/timeout settings, retry behavior - **Base URLs**: endpoint URLs for spot, futures, web, WebSocket - **Rate Limiting**: understanding and handling rate limits - **API Keys & U_ID**: how to obtain and use credentials - **Error Handling**: accessing and managing API errors - **Async client configuration** ### Use Cases Setting up clients, configuring proxies, managing credentials securely. ``` -------------------------------- ### Get Historical Funding Rates Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/2-futures-api-reference.md Fetches historical funding rates for a contract, with options for pagination. Example shows retrieving 50 results per page. ```python history = client.funding_rate_history(symbol="BTC_USDT", page_size=50) ``` -------------------------------- ### Get Rebate Records Detail Source: https://github.com/makarworld/pymexc/blob/master/README.md Retrieves detailed rebate records. Optional parameters include start time, end time, and pagination. ```python result = spot_client.get_rebate_records_detail() ``` -------------------------------- ### Sub-Account Permissions Examples Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/6-types-and-errors.md Illustrates how to assign permissions as a comma-separated string or a list of literals, and how to use them when creating a sub-account API key. ```python # As string permissions = "SPOT_DEAL_READ,SPOT_DEAL_WRITE" # As list permissions = ["SPOT_DEAL_READ", "SPOT_DEAL_WRITE"] # API call api_key = client.create_sub_account_api_key( sub_account="bot_1", note="Trading API", permissions=permissions ) ``` -------------------------------- ### Get Account Assets - Python Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/4-web-futures-api-reference.md Retrieves all account assets and balances. Requires user ID. ```python account = client.assets() ``` -------------------------------- ### Get All Account Assets Source: https://github.com/makarworld/pymexc/blob/master/README.md Retrieves information about all assets in the account. This endpoint does not require any parameters. ```python result = futures_client.assets() ``` -------------------------------- ### Initialize Spot and Futures Clients and Make Requests Source: https://github.com/makarworld/pymexc/blob/master/README.md Demonstrates initializing HTTP and WebSocket clients for both spot and futures markets. Use the HTTP client for simple requests and the WebSocket client for real-time data streams. Ensure your API key and secret are correctly set. ```python from pymexc import spot, futures api_key = "YOUR API KEY" api_secret = "YOUR API SECRET KEY" def handle_message(message): # handle websocket message print(message) # SPOT V3 # initialize HTTP client spot_client = spot.HTTP(api_key = api_key, api_secret = api_secret) # initialize WebSocket client ws_spot_client = spot.WebSocket(api_key = api_key, api_secret = api_secret) # make http request to api print(spot_client.exchange_info()) # create websocket connection to public channel (spot@public.deals.v3.api@BTCUSDT) # all messages will be handled by function `handle_message` ws_spot_client.deals_stream(handle_message, "BTCUSDT") # FUTURES V1 # initialize HTTP client futures_client = futures.HTTP(api_key = api_key, api_secret = api_secret) # initialize WebSocket client ws_futures_client = futures.WebSocket(api_key = api_key, api_secret = api_secret, # subscribe on personal information about about account # if not provided, will not be subscribed # you can subsctibe later by calling ws_futures_client.personal_stream(callback) for all info # or ws_futures_client.filter_stream(callback, params={"filters":[{"filter":"..."}]}) for specific info (https://mexcdevelop.github.io/apidocs/contract_v1_en/#filter-subscription) personal_callback = handle_message) # make http request to api print(futures_client.index_price("MX_USDT")) # create websocket connection to public channel (sub.tickers) # all messages will be handled by function `handle_message` ws_futures_client.tickers_stream(handle_message) # loop forever for save websocket connection while True: ... ``` -------------------------------- ### Get Kline Candlestick Data Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/4-web-futures-api-reference.md Retrieve candlestick data for a given symbol and interval. Supports custom start and end times. ```python def kline( self, symbol: str, interval: Optional[Literal["Min1", "Min5", "Min15", "Min30", "Min60", "Hour4", "Hour8", "Day1", "Week1", "Month1"]] = None, start: Optional[int] = None, end: Optional[int] = None, ) -> dict ``` -------------------------------- ### Async/Await Example (Python) Source: https://github.com/makarworld/pymexc/blob/master/README.md Demonstrates concurrent API requests using asyncio and the async client. Initializes an async client and makes multiple calls simultaneously, then processes the results. Requires API key and secret. ```python import asyncio from pymexc import spot async def main(): # Initialize async client async_client = spot.AsyncHTTP(api_key="YOUR_KEY", api_secret="YOUR_SECRET") # Make multiple requests concurrently tasks = [ async_client.ticker_price("BTCUSDT"), async_client.ticker_price("ETHUSDT"), async_client.ticker_24h("BTCUSDT"), async_client.account_information() ] results = await asyncio.gather(*tasks) btc_price, eth_price, btc_stats, account = results print(f"BTC Price: {btc_price['price']}") print(f"ETH Price: {eth_price['price']}") print(f"BTC 24h Change: {btc_stats['priceChangePercent']}") print(f"Account Balance: {len(account['balances'])} assets") # Run async function asyncio.run(main()) ``` -------------------------------- ### Get Currency Information Source: https://github.com/makarworld/pymexc/blob/master/README.md Retrieves information about supported currencies. Useful for understanding available assets. ```python result = spot_client.get_currency_info() ``` -------------------------------- ### Get Assets Convertible to MX Source: https://github.com/makarworld/pymexc/blob/master/README.md Fetches a list of assets that can be converted into MX tokens. Useful for understanding conversion options. ```python result = spot_client.get_assets_convert_into_mx() ``` -------------------------------- ### Get Rebate History Records Source: https://github.com/makarworld/pymexc/blob/master/README.md Retrieves a history of rebate records. Optional parameters include start time, end time, and pagination. ```python result = spot_client.get_rebate_history_records() ``` -------------------------------- ### Initialize Spot API Clients Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/1-spot-api-reference.md Instantiate synchronous and asynchronous HTTP and WebSocket clients for the Spot API. Ensure you provide your API key and secret for authenticated requests. ```python from pymexc import spot # Synchronous HTTP client client = spot.HTTP(api_key="...", api_secret="...") # Asynchronous HTTP client async_client = spot.AsyncHTTP(api_key="...", api_secret="...") # Synchronous WebSocket client ws_client = spot.WebSocket(api_key="...", api_secret="...") # Asynchronous WebSocket client async_ws_client = spot.AsyncWebSocket(api_key="...", api_secret="...") ``` -------------------------------- ### Get Current Open Spot Orders with PyMexc Source: https://github.com/makarworld/pymexc/blob/master/README.md Fetches a list of all orders that are currently open for a given symbol. ```python result = spot_client.current_open_orders("BTCUSDT") ``` -------------------------------- ### Get Kline Fair Price Candles Source: https://github.com/makarworld/pymexc/blob/master/README.md Retrieves candlestick data for the fair price of a symbol. Requires symbol and interval. Optional start and end times. ```python result = futures_client.kline_fair_price("BTC_USDT", interval="Min1") ``` -------------------------------- ### Get Kline Index Price Candles Source: https://github.com/makarworld/pymexc/blob/master/README.md Fetches candlestick data for the index price of a symbol. Requires symbol and interval. Optional start and end times. ```python result = futures_client.kline_index_price("BTC_USDT", interval="Min1") ``` -------------------------------- ### Configuring and Using Async PyMexc Client Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/5-configuration.md Illustrates the setup and usage of an asynchronous PyMexc client for making API calls. Async clients share the same configuration principles as sync clients. ```python from pymexc import spot import asyncio async def main(): client = spot.AsyncHTTP( api_key="YOUR_API_KEY", api_secret="YOUR_API_SECRET" ) result = await client.ticker_price(symbol="BTCUSDT") print(result) asyncio.run(main()) ``` -------------------------------- ### Get Spot Account Information with PyMexc Source: https://github.com/makarworld/pymexc/blob/master/README.md Fetches detailed information about your spot trading account, including balances and permissions. ```python result = spot_client.account_information() ``` -------------------------------- ### Placing a Spot Order Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/README.md This example demonstrates how to place a limit buy order for BTCUSDT using the PyMexc spot API. It includes error handling for potential API errors. ```APIDOC ## POST /api/v1/order ### Description Places a new order. This endpoint is used for placing various types of orders like LIMIT, MARKET, etc. ### Method POST ### Endpoint /api/v1/order ### Parameters #### Request Body - **symbol** (string) - Required - The trading pair symbol (e.g., BTCUSDT). - **side** (string) - Required - The order side (BUY or SELL). - **order_type** (string) - Required - The type of order (e.g., LIMIT, MARKET). - **quantity** (number) - Required - The amount of the asset to trade. - **price** (number) - Optional - The price at which to place the order (required for LIMIT orders). - **time_in_force** (string) - Optional - Specifies how long an order remains active (e.g., GTC - Good Till Cancelled). ### Request Example ```json { "symbol": "BTCUSDT", "side": "BUY", "order_type": "LIMIT", "quantity": 0.1, "price": 30000, "time_in_force": "GTC" } ``` ### Response #### Success Response (200) - **orderId** (string) - The unique identifier for the placed order. #### Response Example ```json { "orderId": "123456789" } ``` ### Error Handling - **MexcAPIError**: Raised when the API returns an error. ``` -------------------------------- ### Get Self Rebate Records Detail Source: https://github.com/makarworld/pymexc/blob/master/README.md Retrieves detailed rebate records for the current user. Optional parameters include start time, end time, and pagination. ```python result = spot_client.get_self_rebate_records_detail() ``` -------------------------------- ### Get Funding Fee Details Source: https://github.com/makarworld/pymexc/blob/master/README.md Fetches details of funding fees. Requires position type, start time, and end time. Optional symbol, position ID, and pagination. ```python result = futures_client.funding_records(1, start_time, end_time) ``` -------------------------------- ### Configure Spot HTTP Client Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/5-configuration.md Initialize the Spot HTTP client with API credentials and optional proxy settings. API key and secret are required for authenticated endpoints. ```python from pymexc import spot client = spot.HTTP( api_key="YOUR_API_KEY", api_secret="YOUR_API_SECRET", proxies={"https": "http://proxy.example.com:8080"} ) ``` -------------------------------- ### Get All Orders - Python Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/1-spot-api-reference.md Fetch all orders, both open and closed, for a specified trading symbol. You can filter results by order ID, start time, end time, and limit the number of returned orders. ```python orders = client.all_orders(symbol="BTCUSDT", limit=100) ``` -------------------------------- ### Configure Broker HTTP Client Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/5-configuration.md Initialize the Broker HTTP client. It uses the same configuration parameters as the Spot HTTP client, requiring API key and secret for authentication. ```python from pymexc import broker client = broker.HTTP( api_key="YOUR_API_KEY", api_secret="YOUR_API_SECRET", proxies={"https": "http://proxy.example.com:8080"} ) ``` -------------------------------- ### Getting Account Balance Source: https://github.com/makarworld/pymexc/blob/master/README.md This snippet demonstrates how to retrieve account information, including balances for all assets, and filter for those with non-zero amounts. ```APIDOC ## Getting Account Balance ### Description Retrieve account information, including balances for all assets, and filter for those with non-zero amounts. ### Method - `account_information()`: Retrieves the account's information and balances. ### Parameters None ### Examples ```python from pymexc import spot spot_client = spot.HTTP(api_key="YOUR_KEY", api_secret="YOUR_SECRET") # Get account information account = spot_client.account_information() # Print balances for assets with non-zero amounts for balance in account['balances']: free = float(balance['free']) locked = float(balance['locked']) total = free + locked if total > 0: print(f"{balance['asset']}: Free={free}, Locked={locked}, Total={total}") ``` ``` -------------------------------- ### Configure HTTP Proxies Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/5-configuration.md Set up proxy servers for HTTP and HTTPS requests. Ensure the proxy URL includes the protocol. ```python from pymexc import spot proxies = { "https": "http://proxy.example.com:8080", "http": "http://proxy.example.com:8080", } client = spot.HTTP( api_key="...", api_secret="...", proxies=proxies ) ``` -------------------------------- ### Initialize Broker HTTP Clients Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/3-broker-api-reference.md Instantiate synchronous or asynchronous HTTP clients for the Broker API. Requires API key and secret. ```python from pymexc import broker # Synchronous HTTP client client = broker.HTTP(api_key="...", api_secret="...") # Asynchronous HTTP client async_client = broker.AsyncHTTP(api_key="...", api_secret="...") ``` -------------------------------- ### Place Spot Order with PyMexc Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/README.md Demonstrates how to place a limit buy order for BTCUSDT using the spot API. Includes error handling for API exceptions. ```python from pymexc import spot from pymexc.base import MexcAPIError client = spot.HTTP(api_key="...", api_secret="...") try: order = client.order( symbol="BTCUSDT", side="BUY", order_type="LIMIT", quantity=0.1, price=30000, time_in_force="GTC" ) print(f"Order placed: {order['orderId']}") except MexcAPIError as e: print(f"Error: {e}") ``` -------------------------------- ### Configure Spot WebSocket Client Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/5-configuration.md Instantiate a Spot WebSocket client with custom connection parameters. Ensure you provide valid API credentials and a callback function to handle incoming messages. The `restart_on_error` parameter is set to True for automatic reconnection. ```python from pymexc import spot ws_client = spot.WebSocket( api_key="YOUR_API_KEY", api_secret="YOUR_API_SECRET", callback_function=handle_message, ping_interval=20, ping_timeout=10, retries=10, restart_on_error=True, trace_logging=False ) # Subscribe to stream ws_client.deals_stream(handle_message, "BTCUSDT") # Keep connection alive while True: pass ``` -------------------------------- ### Get All Spot Orders with PyMexc Source: https://github.com/makarworld/pymexc/blob/master/README.md Retrieves a comprehensive list of all orders (active, cancelled, completed) for a symbol, with optional limit. ```python result = spot_client.all_orders("BTCUSDT", limit=100) ``` -------------------------------- ### Get Contract Details Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/4-web-futures-api-reference.md Retrieve contract details for a specific symbol using the detail() method. Omit the symbol parameter to get details for all contracts. ```python contract = client.detail(symbol="ETH_USDT") ``` -------------------------------- ### Placing and Managing Orders Source: https://github.com/makarworld/pymexc/blob/master/README.md This snippet shows how to place various types of orders (limit, market) and manage them, including querying order status, listing open orders, and cancelling orders. ```APIDOC ## Placing and Managing Orders ### Description Place limit or market orders, query their status, list open orders, and cancel existing orders. ### Methods - `order(symbol, side, order_type, quantity, price, time_in_force, quote_order_qty)`: Places an order. - `query_order(symbol, order_id)`: Retrieves the status of a specific order. - `current_open_orders(symbol)`: Retrieves all currently open orders for a symbol. - `cancel_order(symbol, order_id)`: Cancels a specific order. ### Parameters - `symbol` (string): The trading pair (e.g., "BTCUSDT"). - `side` (string): Order side ('BUY' or 'SELL'). - `order_type` (string): Type of order ('LIMIT', 'MARKET'). - `quantity` (float): The amount of the base asset to trade. - `price` (float, optional): The price at which to execute a limit order. - `time_in_force` (string, optional): How long the order remains active (e.g., 'GTC' - Good Til Cancelled). - `quote_order_qty` (float, optional): For MARKET orders, the amount of quote currency to spend. - `order_id` (int): The ID of the order to query or cancel. ### Examples ```python from pymexc import spot spot_client = spot.HTTP(api_key="YOUR_KEY", api_secret="YOUR_SECRET") # Get current price first ticker = spot_client.ticker_price("BTCUSDT") current_price = float(ticker['price']) # Place a limit buy order 1% below current price buy_price = current_price * 0.99 result = spot_client.order( symbol="BTCUSDT", side="BUY", order_type="LIMIT", quantity=0.001, price=buy_price, time_in_force="GTC" ) print(f"Order placed: {result}") # Check order status order_status = spot_client.query_order("BTCUSDT", order_id=result['orderId']) print(f"Order status: {order_status['status']}") # Get all open orders open_orders = spot_client.current_open_orders("BTCUSDT") print(f"Open orders: {len(open_orders)}") # Cancel an order if open_orders: cancel_result = spot_client.cancel_order("BTCUSDT", order_id=open_orders[0]['orderId']) print(f"Order cancelled: {cancel_result}") # Place a market buy order for $100 worth of BTC market_result = spot_client.order( symbol="BTCUSDT", side="BUY", order_type="MARKET", quote_order_qty=100 # Buy $100 worth ) print(f"Market order executed: {market_result}") ``` ``` -------------------------------- ### account_information Source: https://github.com/makarworld/pymexc/blob/master/README.md Get account information. ```APIDOC ## account_information ### Description Retrieve detailed information about the user's account. ### Method GET (assumed for retrieving account info) ### Endpoint /api/v1/account (assumed) ### Parameters None ### Response #### Success Response (200) - **balances** (array) - Account balances for different assets. - **permissions** (array) - Account permissions. - **makerCommission** (integer) - Maker commission rate. - **takerCommission** (integer) - Taker commission rate. - **buyerCommission** (integer) - Buyer commission rate. - **sellerCommission** (integer) - Seller commission rate. ``` -------------------------------- ### create_listen_key Source: https://github.com/makarworld/pymexc/blob/master/README.md Create a listen key to establish a user data stream connection. ```APIDOC ## create_listen_key() ### Description Create a listen key for user data stream. ### Method ```python spot_client.create_listen_key() ``` ``` -------------------------------- ### get_position_mode Source: https://github.com/makarworld/pymexc/blob/master/README.md Get user position mode. ```APIDOC ## get_position_mode() ### Description Get user position mode. ### Method Not specified (assumed to be a client-side method call) ### Parameters None ### Request Example ```python result = futures_client.get_position_mode() ``` ``` -------------------------------- ### Client Initialization Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/2-futures-api-reference.md Initialize synchronous and asynchronous HTTP and WebSocket clients for the Futures API. ```APIDOC ## Client Initialization Initialize synchronous and asynchronous HTTP and WebSocket clients for the Futures API. ### Synchronous HTTP Client ```python from pymexc import futures client = futures.HTTP(api_key="...", api_secret="...") ``` ### Asynchronous HTTP Client ```python async_client = futures.AsyncHTTP(api_key="...", api_secret="...") ``` ### Synchronous WebSocket Client ```python ws_client = futures.WebSocket(api_key="...", api_secret="...") ``` ### Asynchronous WebSocket Client ```python async_ws_client = futures.AsyncWebSocket(api_key="...", api_secret="...") ``` ``` -------------------------------- ### get_leverage Source: https://github.com/makarworld/pymexc/blob/master/README.md Get position leverage multipliers. ```APIDOC ## get_leverage(symbol) ### Description Get position leverage multipliers. ### Method Not specified (assumed to be a client-side method call) ### Parameters - **symbol** (string) - Description not specified (e.g., "BTC_USDT") ### Request Example ```python result = futures_client.get_leverage("BTC_USDT") ``` ``` -------------------------------- ### account_trade_list Source: https://github.com/makarworld/pymexc/blob/master/README.md Get account trade list. ```APIDOC ## account_trade_list ### Description Retrieve a list of trades executed within the account for a given symbol. ### Method GET (assumed for retrieving trade lists) ### Endpoint /api/v1/myTrades (assumed) ### Parameters #### Path Parameters None #### Query Parameters - **symbol** (string) - Required - The trading symbol (e.g., BTCUSDT). - **order_id** (string) - Optional - Filter trades by order ID. - **start_time** (integer) - Optional - The start time for filtering trades (Unix timestamp). - **end_time** (integer) - Optional - The end time for filtering trades (Unix timestamp). - **limit** (integer) - Optional - The maximum number of trades to return. ### Response #### Success Response (200) - **trades** (array) - A list of trade records. ``` -------------------------------- ### current_open_orders Source: https://github.com/makarworld/pymexc/blob/master/README.md Get current open orders. ```APIDOC ## current_open_orders ### Description Retrieve a list of all current open orders for a given symbol. ### Method GET (assumed for retrieving lists) ### Endpoint /api/v1/openOrders (assumed) ### Parameters #### Path Parameters None #### Query Parameters - **symbol** (string) - Required - The trading symbol (e.g., BTCUSDT). ### Response #### Success Response (200) - **orders** (array) - A list of open orders. ``` -------------------------------- ### Handle Order Placement Errors Source: https://github.com/makarworld/pymexc/blob/master/README.md Demonstrates how to use a try-except block to catch and handle potential errors during order placement. Includes checks for common issues like insufficient balance or invalid symbols. ```python from pymexc import spot spot_client = spot.HTTP(api_key="YOUR_KEY", api_secret="YOUR_SECRET") try: # Attempt to place an order result = spot_client.order( symbol="BTCUSDT", side="BUY", order_type="LIMIT", quantity=0.001, price=50000 ) print(f"Order placed successfully: {result}") except Exception as e: print(f"Error placing order: {e}") # Handle specific error cases if "insufficient balance" in str(e).lower(): print("Not enough balance for this order") elif "invalid symbol" in str(e).lower(): print("Invalid trading pair") else: print(f"Unknown error: {e}") ``` -------------------------------- ### default_symbols() Source: https://github.com/makarworld/pymexc/blob/master/README.md Get API default symbols. ```APIDOC ## default_symbols() ### Description Get API default symbols. ### Method GET ### Endpoint /api/v3/defaultSymbols ### Request Example ```python result = spot_client.default_symbols() ``` ### Response #### Success Response (200) - **symbols** (array) - List of default trading symbols. ``` -------------------------------- ### all_orders Source: https://github.com/makarworld/pymexc/blob/master/README.md Get all orders (active, cancelled, or completed). ```APIDOC ## all_orders ### Description Retrieve all orders, including active, cancelled, and completed orders for a symbol. ### Method GET (assumed for retrieving lists) ### Endpoint /api/v1/allOrders (assumed) ### Parameters #### Path Parameters None #### Query Parameters - **symbol** (string) - Required - The trading symbol (e.g., BTCUSDT). - **start_time** (integer) - Optional - The start time for filtering orders (Unix timestamp). - **end_time** (integer) - Optional - The end time for filtering orders (Unix timestamp). - **limit** (integer) - Optional - The maximum number of orders to return. ### Response #### Success Response (200) - **orders** (array) - A list of all orders. ``` -------------------------------- ### Place and Manage Spot Orders Source: https://github.com/makarworld/pymexc/blob/master/README.md Demonstrates placing limit buy orders, checking order status, retrieving open orders, and cancelling orders. Requires API key and secret for authenticated requests. ```python from pymexc import spot spot_client = spot.HTTP(api_key="YOUR_KEY", api_secret="YOUR_SECRET") # Get current price first ticker = spot_client.ticker_price("BTCUSDT") current_price = float(ticker['price']) # Place a limit buy order 1% below current price buy_price = current_price * 0.99 result = spot_client.order( symbol="BTCUSDT", side="BUY", order_type="LIMIT", quantity=0.001, price=buy_price, time_in_force="GTC" ) print(f"Order placed: {result}") # Check order status order_status = spot_client.query_order("BTCUSDT", order_id=result['orderId']) print(f"Order status: {order_status['status']}") # Get all open orders open_orders = spot_client.current_open_orders("BTCUSDT") print(f"Open orders: {len(open_orders)}") # Cancel an order if open_orders: cancel_result = spot_client.cancel_order("BTCUSDT", order_id=open_orders[0]['orderId']) print(f"Order cancelled: {cancel_result}") ``` -------------------------------- ### get_default_symbols Source: https://github.com/makarworld/pymexc/blob/master/README.md Get user API default symbols. ```APIDOC ## get_default_symbols ### Description Get user API default symbols. ### Method GET (assumed based on common API patterns for retrieving lists) ### Endpoint /api/v1/symbols/default (assumed) ### Parameters None ### Response #### Success Response (200) - **symbols** (array) - A list of default symbols. ``` -------------------------------- ### Test New Spot Order with PyMexc Source: https://github.com/makarworld/pymexc/blob/master/README.md Simulates placing a new order without executing it. Useful for validating order parameters. ```python result = spot_client.test_order( symbol="BTCUSDT", side="BUY", order_type="LIMIT", quantity=0.001, price=50000 ) ``` -------------------------------- ### Import Main pymexc Clients Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/README.md Import the primary client modules for Spot, Futures, Broker, and asynchronous operations. Also imports the web futures client. ```python # Main clients from pymexc import spot, futures, broker, _async from pymexc.web import futures as web_futures ``` -------------------------------- ### avg_price(symbol) Source: https://github.com/makarworld/pymexc/blob/master/README.md Get current average price. ```APIDOC ## avg_price(symbol) ### Description Get current average price. ### Method GET ### Endpoint /api/v3/avgPrice ### Query Parameters - **symbol** (string) - Required - The trading pair symbol (e.g., BTCUSDT). ### Request Example ```python result = spot_client.avg_price("BTCUSDT") ``` ### Response #### Success Response (200) - **price** (string) - Average price. ``` -------------------------------- ### ticker_book_price(symbol=None) Source: https://github.com/makarworld/pymexc/blob/master/README.md Get best price/qty on the order book. ```APIDOC ## ticker_book_price(symbol=None) ### Description Get best price/qty on the order book. ### Method GET ### Endpoint /api/v3/ticker/bookTicker ### Query Parameters - **symbol** (string) - Optional - The trading pair symbol (e.g., BTCUSDT). ### Request Example ```python result = spot_client.ticker_book_price("BTCUSDT") ``` ### Response #### Success Response (200) - **symbol** (string) - Trading pair symbol. - **bidPrice** (string) - Best bid price. - **bidQty** (string) - Best bid quantity. - **askPrice** (string) - Best ask price. - **askQty** (string) - Best ask quantity. ``` -------------------------------- ### Initialize Futures Clients Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/2-futures-api-reference.md Instantiate synchronous and asynchronous clients for HTTP and WebSocket interactions with the MEXC Futures API. Requires API key and secret for authenticated requests. ```python from pymexc import futures # Synchronous HTTP client client = futures.HTTP(api_key="...", api_secret="...") # Asynchronous HTTP client async_client = futures.AsyncHTTP(api_key="...", api_secret="...") # Synchronous WebSocket client ws_client = futures.WebSocket(api_key="...", api_secret="...") # Asynchronous WebSocket client async_ws_client = futures.AsyncWebSocket(api_key="...", api_secret="...") ``` -------------------------------- ### Get Affiliate Campaign Data Source: https://github.com/makarworld/pymexc/blob/master/README.md Retrieves affiliate campaign data. This endpoint is for affiliates only and accepts optional time range and pagination parameters. ```python result = spot_client.affiliate_campaign() ``` -------------------------------- ### ticker_price(symbol=None, symbols=None) Source: https://github.com/makarworld/pymexc/blob/master/README.md Get symbol price ticker. ```APIDOC ## ticker_price(symbol=None, symbols=None) ### Description Get symbol price ticker. ### Method GET ### Endpoint /api/v3/ticker ### Query Parameters - **symbol** (string) - Optional - The trading pair symbol (e.g., BTCUSDT). - **symbols** (array) - Optional - A list of trading pair symbols. ### Request Example ```python result = spot_client.ticker_price("BTCUSDT") ``` ### Response #### Success Response (200) - **symbol** (string) - Trading pair symbol. - **price** (string) - Price. ``` -------------------------------- ### Import Direct pymexc Clients Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/README.md Import specific HTTP and WebSocket client classes directly for Spot, Futures, and Broker, including both synchronous and asynchronous versions. ```python # Direct imports from pymexc import SpotHTTP, SpotWebSocket, FuturesHTTP, FuturesWebSocket, BrokerHTTP from pymexc import AsyncSpotHTTP, AsyncSpotWebSocket, AsyncFuturesHTTP, AsyncFuturesWebSocket, AsyncBrokerHTTP ``` -------------------------------- ### Initialize Web Futures Client Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/4-web-futures-api-reference.md Instantiate the Web Futures HTTP client using a u_id token for authentication. This is the entry point for interacting with the Web Futures API. ```python from pymexc.web import futures # Web futures client (requires u_id) client = futures.HTTP(u_id="your_u_id_token") ``` -------------------------------- ### trades(symbol, limit=500) Source: https://github.com/makarworld/pymexc/blob/master/README.md Get recent trades list. ```APIDOC ## trades(symbol, limit=500) ### Description Get recent trades list. ### Method GET ### Endpoint /api/v3/trades ### Query Parameters - **symbol** (string) - Required - The trading pair symbol (e.g., BTCUSDT). - **limit** (integer) - Optional - Default 500. Maximum is 1000. ### Request Example ```python result = spot_client.trades("BTCUSDT", limit=100) ``` ### Response #### Success Response (200) - **id** (integer) - Trade ID. - **price** (string) - Price. - **qty** (string) - Quantity. - **quoteQty** (string) - Quote quantity. - **time** (integer) - Time. - **isBuyerMaker** (boolean) - Buyer is maker. ``` -------------------------------- ### Initialize WebSocket Client Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/1-spot-api-reference.md Instantiate the WebSocket client with optional API credentials and connection parameters. For private streams, provide API key and secret. ```python ws_client = spot.WebSocket() ws_client = spot.WebSocket(api_key="...", api_secret="...") ``` -------------------------------- ### open_positions Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/4-web-futures-api-reference.md Get all open positions. Can be filtered by contract symbol. ```APIDOC ## open_positions() ### Description Get all open positions. Can be filtered by contract symbol. ### Method `client.open_positions(symbol: Optional[str] = None)` ### Parameters #### Path Parameters None #### Query Parameters - **symbol** (Optional[str]) - Optional - Filter by contract symbol ### Request Example ```python positions = client.open_positions(symbol="BTC_USDT") ``` ### Response #### Success Response (200) - **dict** — List of open positions ``` -------------------------------- ### sub_account_list(sub_account=None, is_freeze=None, page=1, limit=10) Source: https://github.com/makarworld/pymexc/blob/master/README.md Get details of the sub-account list. ```APIDOC ## sub_account_list(sub_account=None, is_freeze=None, page=1, limit=10) ### Description Get details of the sub-account list. ### Method GET ### Endpoint /api/v3/sub-account/list ### Query Parameters - **subAccount** (string) - Optional - Filter by sub-account name. - **isFreeze** (boolean) - Optional - Filter by freeze status. - **page** (integer) - Optional - Page number, default 1. - **limit** (integer) - Optional - Number of results per page, default 10. ### Request Example ```python result = spot_client.sub_account_list() ``` ``` -------------------------------- ### Configure Proxies with Authentication Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/5-configuration.md Configure proxy servers that require authentication using username and password in the URL. ```python proxies = { "https": "http://username:password@proxy.example.com:8080", } client = spot.HTTP(api_key="...", api_secret="...", proxies=proxies) ``` -------------------------------- ### agg_trades(symbol, start_time=None, end_time=None, limit=500) Source: https://github.com/makarworld/pymexc/blob/master/README.md Get compressed/aggregate trades list. ```APIDOC ## agg_trades(symbol, start_time=None, end_time=None, limit=500) ### Description Get compressed/aggregate trades list. ### Method GET ### Endpoint /api/v3/aggTrades ### Query Parameters - **symbol** (string) - Required - The trading pair symbol (e.g., BTCUSDT). - **startTime** (integer) - Optional - UTC timestamp in ms. - **endTime** (integer) - Optional - UTC timestamp in ms. - **limit** (integer) - Optional - Default 500. Maximum is 1000. ### Request Example ```python result = spot_client.agg_trades("BTCUSDT", limit=100) ``` ### Response #### Success Response (200) - **a** (integer) - Aggregate tradeId. - **p** (string) - Price. - **q** (string) - Quantity. - **f** (integer) - First tradeId. - **l** (integer) - Last tradeId. - **T** (integer) - Timestamp. - **m** (boolean) - Was the buyer the maker? ``` -------------------------------- ### create_sub_account_api_key Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/3-broker-api-reference.md Creates an API key for a specified sub-account. This operation requires the `SPOT_ACCOUNT_READ` permission and allows for setting a note, permissions, and an optional IP whitelist. ```APIDOC ## create_sub_account_api_key() ### Description Create API key for a sub-account. Requires `SPOT_ACCOUNT_READ` permission. ### Method POST ### Endpoint /api/v1/broker/sub-account/api-key ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **sub_account** (str) - Required - Sub-account name - **note** (str) - Required - API key description/note - **permissions** (Union[str, List[str]]) - Required - Comma-separated or list of permissions - **ip** (Optional[str]) - Optional - Comma-separated IP whitelist (max 20) ### Request Example ```json { "sub_account": "trading_bot_1", "note": "Trading API", "permissions": ["SPOT_DEAL_READ", "SPOT_DEAL_WRITE"], "ip": "192.168.1.1,10.0.0.1" } ``` ### Response #### Success Response (200) - **api_key** (dict) - API key creation response #### Response Example ```json { "api_key": "" } ``` ``` -------------------------------- ### exchange_info(symbol=None, symbols=None) Source: https://github.com/makarworld/pymexc/blob/master/README.md Get exchange trading rules and symbol information. ```APIDOC ## exchange_info(symbol=None, symbols=None) ### Description Get exchange trading rules and symbol information. ### Method GET ### Endpoint /api/v3/exchangeInfo ### Query Parameters - **symbol** (string) - Optional - The trading pair symbol (e.g., BTCUSDT). - **symbols** (array) - Optional - A list of trading pair symbols. ``` -------------------------------- ### Test Order Placement Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/1-spot-api-reference.md Use this snippet to simulate placing an order without actual execution. This is helpful for validating order parameters before committing to a real trade. It requires the same parameters as the `order()` method. ```python response = client.test_order( symbol="BTCUSDT", side="BUY", order_type="LIMIT", quantity=0.001, price=30000 ) ``` -------------------------------- ### Get Position Mode Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/2-futures-api-reference.md Fetches the current position mode setting for your account. ```python result = client.get_position_mode() ``` -------------------------------- ### Create Sub-Account API Key Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/3-broker-api-reference.md Use this to create a new API key for a sub-account. Ensure you have the necessary SPOT_ACCOUNT_READ permission. You can specify a list of permissions and an IP whitelist. ```python api_key = client.create_sub_account_api_key( sub_account="trading_bot_1", note="Trading API", permissions=["SPOT_DEAL_READ", "SPOT_DEAL_WRITE"], ip="192.168.1.1,10.0.0.1" ) ``` -------------------------------- ### Get Open Positions Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/4-web-futures-api-reference.md Retrieves all open positions. Can be filtered by contract symbol. ```python positions = client.open_positions(symbol="BTC_USDT") ``` -------------------------------- ### Create Sub-Account Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/1-spot-api-reference.md Use this method to create a virtual sub-account under your master account. Ensure you have SPOT_ACCOUNT_READ permission. ```python response = client.create_sub_account( sub_account="my_sub_1", note="Trading bot account" ) ``` -------------------------------- ### create_sub_account(sub_account, note) Source: https://github.com/makarworld/pymexc/blob/master/README.md Create a sub-account from the master account. ```APIDOC ## create_sub_account(sub_account, note) ### Description Create a sub-account from the master account. ### Method POST ### Endpoint /api/v3/sub-account/virtualSubAccount ### Request Body - **subAccount** (string) - Required - The name of the sub-account to create. - **note** (string) - Required - A note for the sub-account. ### Request Example ```python result = spot_client.create_sub_account("sub_account_name", "note") ``` ``` -------------------------------- ### Get Transferable Currencies Source: https://github.com/makarworld/pymexc/blob/master/README.md Retrieves a list of currencies that can be transferred. This endpoint does not require any parameters. ```python result = futures_client.support_currencies() ``` -------------------------------- ### Spot Trading with pymexc Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/0-overview.md Use the HTTP client for spot trading operations. Instantiate with API key and secret. For real-time data, use the WebSocket client. ```python from pymexc import spot # HTTP client client = spot.HTTP(api_key="...", api_secret="...") price = client.ticker_price(symbol="BTCUSDT") # WebSocket ws = spot.WebSocket(api_key="...", api_secret="...") ws.deals_stream(lambda data: print(data), "BTCUSDT") ``` -------------------------------- ### create_sub_account_api_key(sub_account, note, permissions, ip=None) Source: https://github.com/makarworld/pymexc/blob/master/README.md Create an APIKey for a sub-account. ```APIDOC ## create_sub_account_api_key(sub_account, note, permissions, ip=None) ### Description Create an APIKey for a sub-account. ### Method POST ### Endpoint /api/v3/sub-account/apiKey ### Request Body - **subAccount** (string) - Required - The name of the sub-account. - **note** (string) - Required - A note for the API key. - **permissions** (array) - Required - List of permissions (e.g., ["SPOT_ACCOUNT_READ", "SPOT_DEAL_READ"]). - **ip** (string) - Optional - Allowed IP address. ### Request Example ```python result = spot_client.create_sub_account_api_key( "sub_account_name", "note", ["SPOT_ACCOUNT_READ", "SPOT_DEAL_READ"] ) ``` ``` -------------------------------- ### Get Withdraw History Source: https://github.com/makarworld/pymexc/blob/master/README.md Retrieves a history of withdrawal transactions. Can be filtered by coin and status. ```python result = spot_client.withdraw_history(coin="USDT", limit=100) ``` -------------------------------- ### Get Deposit History Source: https://github.com/makarworld/pymexc/blob/master/README.md Retrieves a history of deposit transactions. Can be filtered by coin and status. ```python result = spot_client.deposit_history(coin="USDT", limit=100) ``` -------------------------------- ### Configure Web Futures HTTP Client (Bypass API) Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/5-configuration.md Initialize the Web Futures HTTP client for bypassing the standard API. Authentication requires a user ID token and optional proxy settings. ```python from pymexc.web import futures client = futures.HTTP( u_id="YOUR_U_ID_TOKEN", proxies={"https": "http://proxy.example.com:8080"} ) ``` -------------------------------- ### WebSocket Constructor Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/1-spot-api-reference.md Initializes the WebSocket client with optional authentication and connection parameters. ```APIDOC ## WebSocket Class The WebSocket class provides real-time market data and account updates via WebSocket connections. ### Constructor ```python class WebSocket(_SpotWebSocket): def __init__( self, api_key: str = None, api_secret: str = None, callback_function: Callable = None, ping_interval: int = 20, ping_timeout: int = 10, retries: int = 10, restart_on_error: bool = True, trace_logging: bool = False, ) ``` **Parameters**: | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | api_key | str | None | API key for private streams | | api_secret | str | None | API secret for private streams | | callback_function | Callable | None | Default callback for all messages | | ping_interval | int | 20 | Seconds between pings | | ping_timeout | int | 10 | Seconds to wait for pong | | retries | int | 10 | Reconnection retries | | restart_on_error | bool | True | Auto-reconnect on error | | trace_logging | bool | False | Enable debug logging | **Source**: `pymexc/base_websocket.py:46-124` ``` -------------------------------- ### order_book(symbol, limit=100) / depth(symbol, limit=100) Source: https://github.com/makarworld/pymexc/blob/master/README.md Get order book depth. ```APIDOC ## order_book(symbol, limit=100) / depth(symbol, limit=100) ### Description Get order book depth. ### Method GET ### Endpoint /api/v3/depth ### Query Parameters - **symbol** (string) - Required - The trading pair symbol (e.g., BTCUSDT). - **limit** (integer) - Optional - Default 100. Valid limits are 5, 10, 20, 50, 100, 500, 1000, 5000. ### Request Example ```python # Using order_book result = spot_client.order_book("BTCUSDT", limit=100) # Using alias depth result = spot_client.depth("BTCUSDT", limit=100) ``` ### Response #### Success Response (200) - **lastUpdateId** (integer) - Order book last update ID. - **bids** (array) - Array of bid price and quantity pairs. - **asks** (array) - Array of ask price and quantity pairs. ``` -------------------------------- ### Create a Sub-Account Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/3-broker-api-reference.md Create a new sub-account for trading. Requires SPOT_ACCOUNT_READ permission. An optional MD5 encrypted password can be provided. ```python from pymexc import broker client = broker.HTTP(api_key="...", api_secret="...") response = client.create_sub_account( sub_account="trading_bot_1", note="Automated trading bot" ) ``` -------------------------------- ### Get Average Price Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/1-spot-api-reference.md Retrieve the current average price for a specific trading symbol. ```python response = client.avg_price(symbol="BTCUSDT") ``` -------------------------------- ### Get Current Position Mode Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/4-web-futures-api-reference.md Retrieve the current position mode setting for the account. ```python def get_position_mode(self) -> dict ``` -------------------------------- ### Create a Sub-Account Source: https://github.com/makarworld/pymexc/blob/master/README.md Create a new sub-account under the master account. Requires a unique sub-account name and an optional note. ```python result = spot_client.create_sub_account("sub_account_name", "note") ``` -------------------------------- ### history_positions Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/4-web-futures-api-reference.md Get historical position records. Supports filtering by symbol and type, and pagination. ```APIDOC ## history_positions() ### Description Get historical position records. Supports filtering by symbol and type, and pagination. ### Method `client.history_positions( symbol: Optional[str] = None, type: Optional[int] = None, page_num: Optional[int] = 1, page_size: Optional[int] = 20, )` ### Parameters #### Path Parameters None #### Query Parameters - **symbol** (Optional[str]) - Optional - Filter by contract symbol - **type** (Optional[int]) - Optional - Position type - **page_num** (Optional[int]) - Optional - Page number (default: 1) - **page_size** (Optional[int]) - Optional - Results per page (default: 20) ### Response #### Success Response (200) - **dict** — Historical positions ``` -------------------------------- ### HTTP Class Constructor Source: https://github.com/makarworld/pymexc/blob/master/_autodocs/2-futures-api-reference.md Constructor for the synchronous HTTP client, allowing API key, secret, proxies, and an ignore_ad flag. ```APIDOC ## HTTP Class Constructor ### Description Initializes the synchronous HTTP client with optional authentication credentials, proxy settings, and an advisory message suppression flag. ### Parameters - **api_key** (str) - Optional - API key for authenticated requests - **api_secret** (str) - Optional - API secret for request signing - **proxies** (dict) - Optional - Proxy settings for HTTP requests - **ignore_ad** (bool) - Optional - Suppress advisory message about futures API ```