### Java POST Request Example Source: https://www.weex.com/api-doc/ai/QuickStart/RequestInteraction This Java snippet shows an example of making a POST request to the Weex API. It includes setting up the request body and printing the response. This is a basic example and lacks signature generation and full header construction shown in the Python examples. ```java System.out.println("GET Response: " + response); // POST request example String body = "{\"symbol\": \"ETHUSDT_SPBL\", \"limit\": \"2\"}"; response = sendRequestPost(API_KEY, SECRET_KEY, ACCESS_PASSPHRASE, "POST", requestPath, "", body); System.out.println("POST Response: " + response); } catch (Exception e) { e.printStackTrace(); } } ``` -------------------------------- ### Request Formats (GET and POST) Source: https://www.weex.com/api-doc/ai/QuickStart/StandardSpecifications Explains the two supported request methods: GET for query string parameters and POST for JSON-formatted request bodies. ```APIDOC ## Request Formats ### Description Only two request methods are supported: GET and POST. * **GET**: Parameters are sent via the query string in the URL path to the server. * **POST**: Parameters are sent as a JSON-formatted body to the server. ### Method GET, POST ### Endpoint N/A (General Specification) ``` -------------------------------- ### WEEX API Account Balance Successful Response Example Source: https://www.weex.com/api-doc/ai/introduction/ParticipantGuide This is an example of a successful response from the WEEX API when querying account balance. It lists the USDT balance, including available, equity, frozen amounts, and unrealized profit and loss. ```json [ { "coinName": "USDT", "available": "5413.06877369", "equity": "5696.49288823", "frozen": "81.28240000", "unrealizePnl": "-34.55300000" } ] ``` -------------------------------- ### Generate and Send GET Request - Python Source: https://www.weex.com/api-doc/ai/QuickStart/RequestInteraction This snippet demonstrates how to generate a signature, construct headers, and send a GET request to the Weex API. It requires API credentials and specifies the request path and query parameters. The response status code and text are printed. ```python import time import hmac import hashlib import base64 import requests import json api_key = "" secret_key = "" access_passphrase = "" def generate_signature_get(secret_key, timestamp, method, request_path, query_string): message = timestamp + method.upper() + request_path + query_string signature = hmac.new(secret_key.encode(), message.encode(), hashlib.sha256).digest() return base64.b64encode(signature).decode() def send_request_get(api_key, secret_key, access_passphrase, method, request_path, query_string): timestamp = str(int(time.time() * 1000)) signature = generate_signature_get(secret_key, timestamp, method, request_path, query_string) headers = { "ACCESS-KEY": api_key, "ACCESS-SIGN": signature, "ACCESS-TIMESTAMP": timestamp, "ACCESS-PASSPHRASE": access_passphrase, "Content-Type": "application/json", "locale": "en-US" } url = "https://api-contract.weex.com/" # Please replace with the actual API address if method == "GET": response = requests.get(url + request_path+query_string, headers=headers) return response def get(): request_path = "/capi/v2/account/position/singlePosition" query_string = '?symbol=cmt_btcusdt' response = send_request_get(api_key, secret_key, access_passphrase, "GET", request_path, query_string) print(response.status_code) print(response.text) if __name__ == '__main__': get() ``` -------------------------------- ### Get Completed Orders Trade Details (Python) Source: https://www.weex.com/api-doc/ai/introduction/ParticipantGuide This Python script demonstrates how to use the WEEX Trade Details API to retrieve historical trade information for completed orders. It includes functions for generating signatures and sending authenticated GET requests. Dependencies include the 'requests', 'hmac', 'hashlib', 'base64', and 'time' libraries. The function 'fills' is designed to fetch specific order fills based on order ID and symbol. ```python import time import hmac import hashlib import base64 import requests api_key = "" secret_key = "" access_passphrase = "" def generate_signature_get(secret_key, timestamp, method, request_path, query_string): message = timestamp + method.upper() + request_path + query_string signature = hmac.new(secret_key.encode(), message.encode(), hashlib.sha256).digest() return base64.b64encode(signature).decode() def send_request_get(api_key, secret_key, access_passphrase, method, request_path, query_string): timestamp = str(int(time.time() * 1000)) signature = generate_signature_get(secret_key, timestamp, method, request_path, query_string) headers = { "ACCESS-KEY": api_key, "ACCESS-SIGN": signature, "ACCESS-TIMESTAMP": timestamp, "ACCESS-PASSPHRASE": access_passphrase, "Content-Type": "application/json", "locale": "en-US" } url = "https://api-contract.weex.com/" # Please replace with the actual API address if method == "GET": response = requests.get(url + request_path+query_string, headers=headers) return response def fills(): request_path = "/capi/v2/order/fills" query_string = "?symbol=cmt_btcusdt&orderId=YOUR_ORDER_ID" response = send_request_get(api_key, secret_key, access_passphrase, "GET", request_path, query_string) print(response.status_code) print(response.text) if __name__ == '__main__': fills() ``` -------------------------------- ### GET Request Endpoint Source: https://www.weex.com/api-doc/ai/QuickStart/RequestInteraction This endpoint enables sending GET requests to the Weex API. It correctly formats the URL with query parameters and sets authentication headers. ```APIDOC ## GET /api/endpoint ### Description Sends a GET request to a specified API endpoint with authentication headers and query parameters. ### Method GET ### Endpoint `BASE_URL + requestPath + queryString` ### Parameters #### Path Parameters - `apiKey` (string) - Required - Your API key. - `secretKey` (string) - Required - Your secret key for signature generation. - `accessPassphrase` (string) - Required - Your access passphrase. - `method` (string) - Required - The HTTP method, should be "GET". - `requestPath` (string) - Required - The specific API endpoint path. - `queryString` (string) - Required - The query parameters for the request, starting with '?'. ### Request Example ```java String requestPath = "/api/uni/v3/order/currentPlan"; String queryString = "?symbol=cmt_bchusdt&delegateType=0&startTime=1742213127794&endTime=1742213506548"; String response = ApiClient.sendRequestGet(API_KEY, SECRET_KEY, ACCESS_PASSPHRASE, "GET", requestPath, queryString); ``` ### Response #### Success Response (200) - `responseBody` (string) - The response from the API as a string, typically JSON. ``` -------------------------------- ### Upload AI Log using cURL Source: https://www.weex.com/api-doc/ai/UploadAiLog This snippet demonstrates how to upload an AI log using cURL. It includes setting the POST request to the correct endpoint, providing necessary headers such as API keys and timestamps, and sending a JSON payload with order details, AI model information, input/output data, and an explanation of the AI's reasoning. The example highlights the structure required for compliance in live trading phases. ```bash curl -X POST "https://api-contract.weex.com/capi/v2/order/uploadAiLog" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*" \ -H "ACCESS-PASSPHRASE:*" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "locale:zh-CN" \ -H "Content-Type: application/json" \ -d '{ "orderId": null, "stage": "Decision Making", "model": "GPT-5-mini", "input": {"prompt":"Summarize last 6h BTC/ETH correlation and give a directional signal."}, "output": {"response":"Sell ETH; correlation weakened, BTC showing dominance."}, "explanation": "Analysis of the past 6 hours of market data indicates a weakening correlation between BTC and ETH. BTC demonstrated relative strength and capital dominance, resulting in a directional signal favoring selling ETH." }' ``` ```bash curl -X POST "https://api-contract.weex.com/capi/v2/order/uploadAiLog" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*" \ -H "ACCESS-PASSPHRASE:*" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "locale:zh-CN" \ -H "Content-Type: application/json" \ -d '{ "orderId": null, "stage": "Strategy Generation", "model": "GPT-5-turbo", "input": { "prompt": "Predict BTC/USDT price trend for the next 3 hours.", "data": { "RSI_14": 36.8, "EMA_20": 68950.4, "FundingRate": -0.0021, "OpenInterest": 512.3 } }, "output": { "signal": "Buy", "confidence": 0.82, "target_price": 69300, "reason": "Negative funding + rising open interest implies short squeeze potential." }, "explanation": "Low RSI and price near the EMA20 suggest weakening downside momentum. Negative funding with rising open interest points to short-side pressure and potential squeeze risk, indicating a bullish bias for BTC over the next three hours." }' ``` -------------------------------- ### Check Account Balance using WEEX API (Python) Source: https://www.weex.com/api-doc/ai/introduction/ParticipantGuide This Python code snippet demonstrates how to retrieve your account balance using the WEEX API. It includes functions for generating HMAC-SHA256 signatures required for private API calls and sending authenticated GET requests. Ensure you replace placeholder API keys and secrets with your actual credentials. ```python import time import hmac import hashlib import base64 import requests api_key = "" secret_key = "" access_passphrase = "" def generate_signature_get(secret_key, timestamp, method, request_path, query_string): message = timestamp + method.upper() + request_path + query_string signature = hmac.new(secret_key.encode(), message.encode(), hashlib.sha256).digest() return base64.b64encode(signature).decode() def send_request_get(api_key, secret_key, access_passphrase, method, request_path, query_string): timestamp = str(int(time.time() * 1000)) signature = generate_signature_get(secret_key, timestamp, method, request_path, query_string) headers = { "ACCESS-KEY": api_key, "ACCESS-SIGN": signature, "ACCESS-TIMESTAMP": timestamp, "ACCESS-PASSPHRASE": access_passphrase, "Content-Type": "application/json", "locale": "en-US" } url = "https://api-contract.weex.com/" # Please replace with the actual API address if method == "GET": response = requests.get(url + request_path+query_string, headers=headers) return response def assets(): request_path = "/capi/v2/account/assets" query_string = "" response = send_request_get(api_key, secret_key, access_passphrase, "GET", request_path, query_string) print(response.status_code) print(response.text) if __name__ == '__main__': assets() ``` -------------------------------- ### Get Futures Contract Information for Trading Pair (Python) Source: https://www.weex.com/api-doc/ai/introduction/ParticipantGuide Retrieves contract details for a specified trading pair, such as order precision, price precision, and size limits. This information is crucial for constructing valid order parameters. It utilizes the `requests` library to make a GET request to the WEEX API. Dependencies: `requests` library. ```Python import requests def send_request_get( method, request_path, query_string): url = "https://api-contract.weex.com/" # Please replace with the actual API address if method == "GET": response = requests.get(url + request_path+query_string) return response def contracts(): request_path = "/capi/v2/market/contracts" query_string = "?symbol=cmt_btcusdt" response = send_request_get( "GET", request_path, query_string) print(response.status_code) print(response.text) if __name__ == '__main__': contracts() ``` -------------------------------- ### Get Asset Price Source: https://www.weex.com/api-doc/ai/introduction/ParticipantGuide This endpoint allows you to retrieve the latest price information for a specified asset. It is useful for real-time market monitoring. ```APIDOC ## GET /capi/v2/market/ticker ### Description Retrieves the latest price ticker information for a given trading symbol. ### Method GET ### Endpoint /capi/v2/market/ticker ### Parameters #### Query Parameters - **symbol** (string) - Required - The trading pair for which to get the price ticker (e.g., `cmt_btcusdt`). ### Request Example ``` GET /capi/v2/market/ticker?symbol=cmt_btcusdt ``` ### Response #### Success Response (200) - **symbol** (string) - The trading pair. - **last** (string) - The last traded price. - **best_ask** (string) - The best ask price. - **best_bid** (string) - The best bid price. - **high_24h** (string) - The highest price in the last 24 hours. - **low_24h** (string) - The lowest price in the last 24 hours. - **volume_24h** (string) - The trading volume in the last 24 hours. - **timestamp** (string) - The timestamp of the data. - **priceChangePercent** (string) - The percentage change in price over the last 24 hours. - **base_volume** (string) - The volume of the base currency traded. - **markPrice** (string) - The mark price. - **indexPrice** (string) - The index price. #### Response Example ```json { "symbol": "cmt_btcusdt", "last": "90755.3", "best_ask": "90755.4", "best_bid": "90755.3", "high_24h": "91130.0", "low_24h": "90097.3", "volume_24h": "2321170547.37995", "timestamp": "1764482511864", "priceChangePercent": "0.000474", "base_volume": "25615.0755", "markPrice": "90755.2", "indexPrice": "90797.161" } ``` ``` -------------------------------- ### Get Asset Price using Price Ticker API Source: https://www.weex.com/api-doc/ai/introduction/ParticipantGuide Requests the latest price for a given trading pair using the Price Ticker API. Requires the 'requests' library. Returns a JSON object with price and market data. Assumes a GET request to the specified API endpoint. ```python import requests def send_request_get( method, request_path, query_string): url = "https://api-contract.weex.com/" # Please replace with the actual API address if method == "GET": response = requests.get(url + request_path+query_string) return response def ticker(): request_path = "/capi/v2/market/ticker" query_string = "?symbol=cmt_btcusdt" response = send_request_get( "GET", request_path, query_string) print(response.status_code) print(response.text) if __name__ == '__main__': ticker() ``` -------------------------------- ### WEEX API Network Connectivity Response Source: https://www.weex.com/api-doc/ai/introduction/ParticipantGuide This is an example of a successful response when checking WEEX API network connectivity. It provides epoch, ISO, and Unix timestamp details, confirming that the API is reachable and responding correctly. ```json {"epoch":"1765423487.896","iso":"2025-12-11T03:24:47.896Z","timestamp":1765423487896} ``` -------------------------------- ### Check WEEX API Network Connectivity (curl) Source: https://www.weex.com/api-doc/ai/introduction/ParticipantGuide This snippet demonstrates how to verify your network connection to the WEEX API by making a simple market data request. It uses curl to send a GET request to the market time endpoint. A successful response confirms network connectivity. ```shell curl -s --max-time 10 "https://api-contract.weex.com/capi/v2/market/time" ``` -------------------------------- ### Java API Client for Weex API Source: https://www.weex.com/api-doc/ai/QuickStart/RequestInteraction This Java code provides a client for interacting with the Weex API. It includes methods for generating HMAC-SHA256 signatures for authentication and sending authenticated GET and POST requests. Dependencies include Apache HttpClient and Java's built-in crypto libraries. It takes API credentials, request details, and body (for POST) as input and returns the API response as a string. ```java package com.weex.lcp.utils; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.util.Base64; public class ApiClient { // API Info private static final String API_KEY = ""; // Replace with your actual API Key private static final String SECRET_KEY = ""; // Replace with your actual Secret Key private static final String ACCESS_PASSPHRASE = ""; // Replace with your actual Access Passphrase private static final String BASE_URL = ""; // Replace with your actual API address // Generate signature (POST request) public static String generateSignature(String secretKey, String timestamp, String method, String requestPath, String queryString, String body) throws Exception { String message = timestamp + method.toUpperCase() + requestPath + queryString + body; return generateHmacSha256Signature(secretKey, message); } // Generate signature (GET request) public static String generateSignatureGet(String secretKey, String timestamp, String method, String requestPath, String queryString) throws Exception { String message = timestamp + method.toUpperCase() + requestPath + queryString; return generateHmacSha256Signature(secretKey, message); } // Generate HMAC SHA256 signature private static String generateHmacSha256Signature(String secretKey, String message) throws Exception { SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256"); Mac mac = Mac.getInstance("HmacSHA256"); mac.init(secretKeySpec); byte[] signatureBytes = mac.doFinal(message.getBytes(StandardCharsets.UTF_8)); return Base64.getEncoder().encodeToString(signatureBytes); } // Send POST request public static String sendRequestPost(String apiKey, String secretKey, String accessPassphrase, String method, String requestPath, String queryString, String body) throws Exception { String timestamp = String.valueOf(System.currentTimeMillis()); String signature = generateSignature(secretKey, timestamp, method, requestPath, queryString, body); HttpPost postRequest = new HttpPost(BASE_URL + requestPath); postRequest.setHeader("ACCESS-KEY", apiKey); postRequest.setHeader("ACCESS-SIGN", signature); postRequest.setHeader("ACCESS-TIMESTAMP", timestamp); postRequest.setHeader("ACCESS-PASSPHRASE", accessPassphrase); postRequest.setHeader("Content-Type", "application/json"); postRequest.setHeader("locale", "en-US"); StringEntity entity = new StringEntity(body, StandardCharsets.UTF_8); postRequest.setEntity(entity); try (CloseableHttpClient httpClient = HttpClients.createDefault()) { CloseableHttpResponse response = httpClient.execute(postRequest); return EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8); } } // Send GET request public static String sendRequestGet(String apiKey, String secretKey, String accessPassphrase, String method, String requestPath, String queryString) throws Exception { String timestamp = String.valueOf(System.currentTimeMillis()); String signature = generateSignatureGet(secretKey, timestamp, method, requestPath, queryString); HttpGet getRequest = new HttpGet(BASE_URL + requestPath+queryString); getRequest.setHeader("ACCESS-KEY", apiKey); getRequest.setHeader("ACCESS-SIGN", signature); getRequest.setHeader("ACCESS-TIMESTAMP", timestamp); getRequest.setHeader("ACCESS-PASSPHRASE", accessPassphrase); getRequest.setHeader("Content-Type", "application/json"); getRequest.setHeader("locale", "en-US"); try (CloseableHttpClient httpClient = HttpClients.createDefault()) { CloseableHttpResponse response = httpClient.execute(getRequest); return EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8); } } // Example usage public static void main(String[] args) { try { // GET request example String requestPath = "/api/uni/v3/order/currentPlan"; String queryString = "?symbol=cmt_bchusdt&delegateType=0&startTime=1742213127794&endTime=1742213506548"; String response = sendRequestGet(API_KEY, SECRET_KEY, ACCESS_PASSPHRASE, "GET", requestPath, queryString); ``` -------------------------------- ### GET /capi/v2/account/position/singlePosition Source: https://www.weex.com/api-doc/ai/QuickStart/RequestInteraction Retrieves single position information for a specified symbol. ```APIDOC ## GET /capi/v2/account/position/singlePosition ### Description Retrieves the position details for a specific trading symbol. ### Method GET ### Endpoint /capi/v2/account/position/singlePosition ### Parameters #### Query Parameters - **symbol** (string) - Required - The trading symbol for which to retrieve position information (e.g., 'cmt_btcusdt'). ### Request Example ``` GET /capi/v2/account/position/singlePosition?symbol=cmt_btcusdt HTTP/1.1 Host: api-contract.weex.com ACCESS-KEY: YOUR_API_KEY ACCESS-SIGN: YOUR_SIGNATURE ACCESS-TIMESTAMP: TIMESTAMP ACCESS-PASSPHRASE: YOUR_PASSPHRASE Content-Type: application/json locale: en-US ``` ### Response #### Success Response (200) - **data** (object) - Contains the position data. - **symbol** (string) - The trading symbol. - **available_size** (string) - The available size for the position. - **frozen_size** (string) - The frozen size of the position. - **position** (string) - The current position size. - **lever_rate** (string) - The leverage rate applied. - **margin** (string) - The margin used for the position. - **liquidation_price** (string) - The liquidation price for the position. - **entry_price** (string) - The entry price of the position. - **unrealized_profit** (string) - The unrealized profit or loss. - **realized_profit** (string) - The realized profit or loss. - **created_at** (string) - Timestamp of position creation. - **updated_at** (string) - Timestamp of last position update. #### Response Example ```json { "code": "0", "msg": "ok", "data": { "symbol": "cmt_btcusdt", "available_size": "0.000", "frozen_size": "0.000", "position": "0.000", "lever_rate": "5", "margin": "0.00000000", "liquidation_price": "0.00000", "entry_price": "0.00000", "unrealized_profit": "0.00000000", "realized_profit": "0.00000000", "created_at": "1589033211000", "updated_at": "1589033211000" } } ``` ``` -------------------------------- ### Get Futures Information Source: https://www.weex.com/api-doc/ai/introduction/ParticipantGuide Retrieves contract information for a specified trading pair, including order precision, price precision, and size limits. This is crucial for constructing valid orders. ```APIDOC ## GET /capi/v2/market/contracts ### Description Retrieves detailed contract information for a given symbol. ### Method GET ### Endpoint /capi/v2/market/contracts ### Parameters #### Query Parameters - **symbol** (string) - Required - The trading pair for which to retrieve contract information (e.g., `cmt_btcusdt`). ### Request Example ```python import requests def send_request_get( method, request_path, query_string): url = "https://api-contract.weex.com/" if method == "GET": response = requests.get(url + request_path+query_string) return response def contracts(): request_path = "/capi/v2/market/contracts" query_string = "?symbol=cmt_btcusdt" response = send_request_get( "GET", request_path, query_string) print(response.status_code) print(response.text) if __name__ == '__main__': contracts() ``` ### Response #### Success Response (200) - **symbol** (string) - The trading pair. - **underlying_index** (string) - The underlying asset index. - **quote_currency** (string) - The quote currency. - **coin** (string) - The coin associated with the contract. - **contract_val** (string) - The contract value. - **delivery** (array) - Delivery times. - **size_increment** (string) - The minimum order size increment. - **tick_size** (string) - The minimum price movement. - **forwardContractFlag** (boolean) - Indicates if it's a forward contract. - **priceEndStep** (integer) - Price end step. - **minLeverage** (integer) - Minimum leverage allowed. - **maxLeverage** (integer) - Maximum leverage allowed. - **buyLimitPriceRatio** (string) - Ratio for buy limit price. - **sellLimitPriceRatio** (string) - Ratio for sell limit price. - **makerFeeRate** (string) - Maker fee rate. - **takerFeeRate** (string) - Taker fee rate. - **minOrderSize** (string) - Minimum order size. - **maxOrderSize** (string) - Maximum order size. - **maxPositionSize** (string) - Maximum position size. - **marketOpenLimitSize** (string) - Market open limit size. #### Response Example ```json [ { "symbol": "cmt_btcusdt", "underlying_index": "BTC", "quote_currency": "USDT", "coin": "USDT", "contract_val": "0.0001", "delivery": [ "00:00:00", "08:00:00", "16:00:00" ], "size_increment": "4", "tick_size": "1", "forwardContractFlag": true, "priceEndStep": 1, "minLeverage": 1, "maxLeverage": 400, "buyLimitPriceRatio": "0.01", "sellLimitPriceRatio": "0.01", "makerFeeRate": "0.0002", "takerFeeRate": "0.0008", "minOrderSize": "0.0001", "maxOrderSize": "1200", "maxPositionSize": "1000000", "marketOpenLimitSize": "100" } ] ``` ``` -------------------------------- ### Constructing the String to Sign Source: https://www.weex.com/api-doc/ai/QuickStart/Signature This snippet illustrates how to construct the message string that will be signed. It concatenates timestamp, method, request path, query string (if present), and request body (if present). The exact format depends on whether a query string exists. ```text timestamp + method.toUpperCase() + requestPath + "?" + queryString + body OR timestamp + method.toUpperCase() + requestPath + body ``` -------------------------------- ### Place Order Source: https://www.weex.com/api-doc/ai/introduction/ParticipantGuide Places a new order on the futures market. Requires authentication and precise parameter construction based on contract information. ```APIDOC ## POST /capi/v2/order/placeOrder ### Description Places an order on the futures market. This endpoint requires authentication and specific parameters to be correctly set. ### Method POST ### Endpoint /capi/v2/order/placeOrder ### Parameters #### Request Body - **symbol** (string) - Required - The trading pair for the order (e.g., `cmt_btcusdt`). - **client_oid** (string) - Optional - A unique identifier for the client's order. - **size** (string) - Required - The quantity of the asset to trade. - **type** (string) - Required - The type of order. '1' for open position. - **order_type** (string) - Required - The type of order placement. '0' for limit order. - **match_price** (string) - Required - Typically '0' for limit orders. - **price** (string) - Required - The limit price for the order. ### Request Example ```python import time import hmac import hashlib import base64 import requests import json api_key = "" secret_key = "" access_passphrase = "" def generate_signature(secret_key, timestamp, method, request_path, query_string, body): message = timestamp + method.upper() + request_path + query_string + str(body) signature = hmac.new(secret_key.encode(), message.encode(), hashlib.sha256).digest() return base64.b64encode(signature).decode() def send_request_post(api_key, secret_key, access_passphrase, method, request_path, query_string, body): timestamp = str(int(time.time() * 1000)) body = json.dumps(body) signature = generate_signature(secret_key, timestamp, method, request_path, query_string, body) headers = { "ACCESS-KEY": api_key, "ACCESS-SIGN": signature, "ACCESS-TIMESTAMP": timestamp, "ACCESS-PASSPHRASE": access_passphrase, "Content-Type": "application/json", "locale": "en-US" } url = "https://api-contract.weex.com/" if method == "POST": response = requests.post(url + request_path, headers=headers, data=body) return response def placeOrder(): request_path = "/capi/v2/order/placeOrder" body = { "symbol": "cmt_btcusdt", "client_oid": "test", "size": "0.0001", "type": "1", "order_type": "0", "match_price": "0", "price": "100000.0"} query_string = "" response = send_request_post(api_key, secret_key, access_passphrase, "POST", request_path, query_string, body) print(response.status_code) print(response.text) if __name__ == '__main__': placeOrder() ``` ### Response #### Success Response (200) - **client_oid** (string) - The client order ID, if provided. - **order_id** (string) - The unique identifier for the placed order. #### Response Example ```json { "client_oid": null, "order_id": "596471064624628269" } ``` ``` -------------------------------- ### POST /capi/v2/order/placeOrder Source: https://www.weex.com/api-doc/ai/QuickStart/RequestInteraction Places a new order for a specified trading symbol. ```APIDOC ## POST /capi/v2/order/placeOrder ### Description Submits a new order to the trading system. Supports various order types and configurations. ### Method POST ### Endpoint /capi/v2/order/placeOrder ### Parameters #### Request Body - **symbol** (string) - Required - The trading symbol (e.g., 'cmt_btcusdt'). - **client_oid** (string) - Optional - A unique client-generated order ID. - **size** (string) - Required - The quantity of the asset to trade. - **type** (string) - Required - The type of order (e.g., '1' for limit order, '2' for market order). - **order_type** (string) - Required - The type of order placement (e.g., '0' for open, '1' for close). - **match_price** (string) - Optional - The price at which to match the order (used for specific order types). - **price** (string) - Required for limit orders - The price at which to place the limit order. ### Request Example ```json { "symbol": "cmt_btcusdt", "client_oid": "71557515757447", "size": "0.01", "type": "1", "order_type": "0", "match_price": "1", "price": "80000" } ``` ### Response #### Success Response (200) - **order_id** (string) - The unique identifier for the placed order. - **client_oid** (string) - The client-generated order ID, if provided. #### Response Example ```json { "code": "0", "msg": "ok", "data": { "order_id": "1234567890", "client_oid": "71557515757447" } } ``` ``` -------------------------------- ### Place Limit Order on WEEX (Python) Source: https://www.weex.com/api-doc/ai/introduction/ParticipantGuide Submits a limit order to place a long position for a specified trading pair with a given price and size. This function generates a signature for authentication and sends a POST request to the WEEX API. It requires API key, secret key, and passphrase for authentication. Dependencies: `time`, `hmac`, `hashlib`, `base64`, `requests`, `json` libraries. ```Python import time import hmac import hashlib import base64 import requests import json api_key = "" secret_key = "" access_passphrase = "" def generate_signature(secret_key, timestamp, method, request_path, query_string, body): message = timestamp + method.upper() + request_path + query_string + str(body) signature = hmac.new(secret_key.encode(), message.encode(), hashlib.sha256).digest() return base64.b64encode(signature).decode() def send_request_post(api_key, secret_key, access_passphrase, method, request_path, query_string, body): timestamp = str(int(time.time() * 1000)) body = json.dumps(body) signature = generate_signature(secret_key, timestamp, method, request_path, query_string, body) headers = { "ACCESS-KEY": api_key, "ACCESS-SIGN": signature, "ACCESS-TIMESTAMP": timestamp, "ACCESS-PASSPHRASE": access_passphrase, "Content-Type": "application/json", "locale": "en-US" } url = "https://api-contract.weex.com/" # Please replace with the actual API address if method == "POST": response = requests.post(url + request_path, headers=headers, data=body) return response def placeOrder(): request_path = "/capi/v2/order/placeOrder" body = { "symbol": "cmt_btcusdt", "client_oid": "test", "size": "0.0001", "type": "1", "order_type": "0", "match_price": "0", "price": "100000.0"} query_string = "" response = send_request_post(api_key, secret_key, access_passphrase, "POST", request_path, query_string, body) print(response.status_code) print(response.text) if __name__ == '__main__': placeOrder() ``` -------------------------------- ### POST /capi/v2/order/uploadAiLog Source: https://www.weex.com/api-doc/ai/UploadAiLog Uploads the AI log containing model version, input/output data, and order execution details. This is mandatory for BUIDLs in the live trading phase to prove AI involvement. ```APIDOC ## POST /capi/v2/order/uploadAiLog ### Description Uploads the AI log containing model version, input/output data, and order execution details. This is mandatory for BUIDLs in the live trading phase to prove AI involvement. Failure to provide a valid AI log may result in disqualification from rankings. ### Method POST ### Endpoint `/capi/v2/order/uploadAiLog` ### Parameters #### Query Parameters - **orderId** (Long) - Optional - The order ID returned from your WEEX order API #### Request Body - **stage** (String) - Required - The trading stage where AI participated (e.g., "Strategy Generation") - **model** (String) - Required - The name or version of the AI model used (e.g., "GPT-4-turbo") - **input** (JSON) - Required - The prompt, query, or input text given to the AI model. If the input includes attachments (e.g., files, images), please provide links. - **output** (JSON) - Required - The AI model's generated output, including predictions or decision recommendations. For inference models, show the inference process. - **explanation** (String) - Required - A concise explanation summarizing the AI's analysis and reasoning in natural language. Maximum length: 1000 characters. ### Request Example ```json { "orderId": null, "stage": "Decision Making", "model": "GPT-5-mini", "input": {"prompt":"Summarize last 6h BTC/ETH correlation and give a directional signal."}, "output": {"response":"Sell ETH; correlation weakened, BTC showing dominance."}, "explanation": "Analysis of the past 6 hours of market data indicates a weakening correlation between BTC and ETH. BTC demonstrated relative strength and capital dominance, resulting in a directional signal favoring selling ETH." } ``` ### Response #### Success Response (200) - **code** (String) - Request status code, "00000" indicates success - **msg** (String) - Request result description, "success" indicates success - **requestTime** (Long) - Request timestamp (milliseconds) - **data** (String) - Returned business data, "upload success" indicates upload successful #### Response Example ```json { "code": "00000", "msg": "success", "requestTime": 1763103201300, "data": "upload success" } ``` ``` -------------------------------- ### Generate and Send POST Request - Python Source: https://www.weex.com/api-doc/ai/QuickStart/RequestInteraction This snippet shows how to generate a signature, create a JSON request body, construct headers, and send a POST request to the Weex API. It utilizes API credentials and specifies the request path. The response status code and text are printed. ```python import time import hmac import hashlib import base64 import requests import json api_key = "" secret_key = "" access_passphrase = "" def generate_signature(secret_key, timestamp, method, request_path, query_string, body): message = timestamp + method.upper() + request_path + query_string + str(body) signature = hmac.new(secret_key.encode(), message.encode(), hashlib.sha256).digest() return base64.b64encode(signature).decode() def send_request_post(api_key, secret_key, access_passphrase, method, request_path, query_string, body): timestamp = str(int(time.time() * 1000)) body = json.dumps(body) signature = generate_signature(secret_key, timestamp, method, request_path, query_string, body) headers = { "ACCESS-KEY": api_key, "ACCESS-SIGN": signature, "ACCESS-TIMESTAMP": timestamp, "ACCESS-PASSPHRASE": access_passphrase, "Content-Type": "application/json", "locale": "en-US" } url = "https://api-contract.weex.com/" # Please replace with the actual API address if method == "POST": response = requests.post(url + request_path, headers=headers, data=body) return response def post(): request_path = "/capi/v2/order/placeOrder" body = { "symbol": "cmt_btcusdt", "client_oid": "71557515757447", "size": "0.01", "type": "1", "order_type": "0", "match_price": "1", "price": "80000"} query_string = "" response = send_request_post(api_key, secret_key, access_passphrase, "POST", request_path, query_string, body) print(response.status_code) print(response.text) if __name__ == '__main__': post() ``` -------------------------------- ### Set Leverage using Leverage Adjustment API Source: https://www.weex.com/api-doc/ai/introduction/ParticipantGuide Modifies the cross-margin leverage for a specified trading pair using the Leverage Adjustment API. Requires libraries for time, HMAC, hashlib, base64, requests, and json. It generates a signature for authentication and sends a POST request. The request body specifies the symbol, margin mode, and leverage for long and short positions. ```python import time import hmac import hashlib import base64 import requests import json api_key = "" secret_key = "" access_passphrase = "" def generate_signature(secret_key, timestamp, method, request_path, query_string, body): message = timestamp + method.upper() + request_path + query_string + str(body) signature = hmac.new(secret_key.encode(), message.encode(), hashlib.sha256).digest() return base64.b64encode(signature).decode() def send_request_post(api_key, secret_key, access_passphrase, method, request_path, query_string, body): timestamp = str(int(time.time() * 1000)) body = json.dumps(body) signature = generate_signature(secret_key, timestamp, method, request_path, query_string, body) headers = { "ACCESS-KEY": api_key, "ACCESS-SIGN": signature, "ACCESS-TIMESTAMP": timestamp, "ACCESS-PASSPHRASE": access_passphrase, "Content-Type": "application/json", "locale": "en-US" } url = "https://api-contract.weex.com/" # Please replace with the actual API address if method == "POST": response = requests.post(url + request_path, headers=headers, data=body) return response def leverage(): request_path = "/capi/v2/account/leverage" body = {"symbol":"cmt_btcusdt","marginMode":1,"longLeverage":"1","shortLeverage":"1"} query_string = "" response = send_request_post(api_key, secret_key, access_passphrase, "POST", request_path, query_string, body) print(response.status_code) print(response.text) if __name__ == '__main__': leverage() ``` -------------------------------- ### Set Leverage Source: https://www.weex.com/api-doc/ai/introduction/ParticipantGuide This endpoint allows you to modify the cross-margin leverage for a specific trading pair. Ensure compliance with competition rules regarding maximum leverage. ```APIDOC ## POST /capi/v2/account/leverage ### Description Modifies the cross-margin leverage for a specified trading symbol. ### Method POST ### Endpoint /capi/v2/account/leverage ### Parameters #### Request Body - **symbol** (string) - Required - The trading pair for which to set leverage (e.g., `cmt_btcusdt`). - **marginMode** (integer) - Required - The margin mode (e.g., 1 for cross-margin). - **longLeverage** (string) - Required - The leverage for long positions (e.g., "1" to "20"). - **shortLeverage** (string) - Required - The leverage for short positions (e.g., "1" to "20"). ### Request Example ```json { "symbol":"cmt_btcusdt", "marginMode":1, "longLeverage":"1", "shortLeverage":"1" } ``` ### Response #### Success Response (200) - **msg** (string) - Success message. - **requestTime** (integer) - Timestamp of the request. - **code** (string) - Response code, "200" indicates success. #### Response Example ```json { "msg": "success", "requestTime": 1713339011237, "code": "200" } ``` ``` -------------------------------- ### Network Connection Test API Source: https://www.weex.com/api-doc/ai/introduction/ParticipantGuide This endpoint tests the network connection to the WEEX API. It returns a JSON object with epoch, ISO, and timestamp details upon successful connection. ```APIDOC ## GET /capi/v2/market/time ### Description Tests the network connection to the WEEX API. ### Method GET ### Endpoint /capi/v2/market/time ### Parameters None ### Request Example ```bash curl -s --max-time 10 "https://api-contract.weex.com/capi/v2/market/time" ``` ### Response #### Success Response (200) - **epoch** (string) - The current epoch time. - **iso** (string) - The current ISO 8601 formatted time. - **timestamp** (number) - The current Unix timestamp in milliseconds. #### Response Example ```json { "epoch": "1765423487.896", "iso": "2025-12-11T03:24:47.896Z", "timestamp": 1765423487896 } ``` ```