# WEEX API Documentation > Complete documentation for Large Language Models --- ## Document: Get Account Information (USER_DATA) URL: /api-doc/spot/AccountAPI/GetAccountBalance # Get Account Information (USER_DATA) - **GET** ```/api/v3/account``` Weight(IP): 5
**Request parameters** NONE
**Request example** ```powershell curl "https://api-spot.weex.com/api/v3/account" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ ```
**Response parameters** | Field | Type | Description | |----------------------------|---------------------|----------------------------------------------| | makerCommission | Integer | User-level maker fee rate (basis points). | | takerCommission | Integer | User-level taker fee rate (basis points). | | commissionRates.maker | String | Maker fee rate as a decimal string. | | commissionRates.taker | String | Taker fee rate as a decimal string. | | canTrade | Boolean | Whether trading is enabled. | | canWithdraw | Boolean | Whether withdrawals are enabled. | | canDeposit | Boolean | Whether deposits are enabled. | | brokered | Boolean | Whether the account is broker managed. | | requireSelfTradePrevention | Boolean | Whether self-trade prevention is enforced. | | preventSor | Boolean | Whether smart order routing is disabled. | | updateTime | Long | Last account update time (ms). | | accountType | String | Account type, e.g. `SPOT`. | | balances | Array<Object> | Asset balances. | | → asset | String | Asset symbol. | | → free | String | Free balance. | | → locked | String | Locked balance. | | permissions | Array<String> | Granted permissions (e.g. `SPOT_TRADING`). | | uid | Long | Account UID. | | symbolCommissions | Object | Per-symbol maker/taker commission overrides. |
**Response example** ```json { "makerCommission": 10, "takerCommission": 10, "commissionRates": { "maker": "0.0010", "taker": "0.0010" }, "canTrade": true, "canWithdraw": true, "canDeposit": true, "permissions": ["SPOT_TRADING"], "balances": [ { "asset": "BTC", "free": "0.004", "locked": "0" }, { "asset": "USDT", "free": "1200.00000000", "locked": "0" } ], "uid": 1002003004 } ```
--- ## Document: Get Spot Account Bills (USER_DATA) URL: /api-doc/spot/AccountAPI/GetBillRecords # Get Spot Account Bills (USER_DATA) - **POST** ```/api/v3/account/bills``` Weight(IP): 5
**Request parameters** | Parameter | Type | Required? | Description | |-------------|---------|-------------|-----------------------------------------------------------------| | coinId | Integer | No | Filter by asset ID. | | bizType | String | No | Business type filter (e.g. `deposit`, `withdraw`, `trade_out`). | | after | Long | No | Records created AFTER this timestamp | | before | Long | No | Records created BEFORE this timestamp | | limit | Integer | No | Number of records to return (default `10`, maximum `100`). |
**Request example** ```powershell curl -X POST "https://api-spot.weex.com/api/v3/account/bills" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "Content-Type: application/json" \ -d '{ "bizType": "trade_out", "limit": 50 }' ```
**Response parameters** Each item in the response array contains: | Field | Type | Description | |---------------|--------|-------------| | billId | String | Bill identifier. | | coinId | Integer| Asset ID. | | coinName | String | Asset symbol. | | bizType | String | Business type. | | fillSize | String | Filled quantity (if applicable). | | fillValue | String | Filled value (if applicable). | | deltaAmount | String | Amount change. | | afterAmount | String | Balance after the change. | | fees | String | Fees charged. | | cTime | String | Creation time (ms). |
**Response example** ```json [ { "billId": "701234567890123456", "coinId": 2, "coinName": "USDT", "bizType": "trade_out", "fillSize": "0.005", "fillValue": "0", "deltaAmount": "-100.00000000", "afterAmount": "900.00000000", "fees": "0.10000000", "cTime": "1764505800123" } ] ```
--- ## Document: Get Funding Account Bills (USER_DATA) URL: /api-doc/spot/AccountAPI/GetFundBillRecords # Get Funding Account Bills (USER_DATA) - **POST** ```/api/v3/account/fundingBills``` Weight(IP): 5
**Request parameters** | Parameter | Type | Required? | Description | |-----------|---------|-----------|-------------| | coinId | Integer | No | Asset ID filter. | | bizType | String | No | Business type filter. | | startTime | Long | No | Start time (ms). | | endTime | Long | No | End time (ms). | | pageIndex | Integer | No | Page number (default 1). | | pageSize | Integer | No | Page size (default 10, maximum 100). |
**Request example** ```powershell curl -X POST "https://api-spot.weex.com/api/v3/account/fundingBills" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "Content-Type: application/json" \ -d '{ "coinId": 2, "pageSize": 20 }' ```
**Response parameters** | Field | Type | Description | |--------------|---------------------|-------------| | total | Long | Total number of records. | | pageSize | Integer | Page size. | | pages | Integer | Total number of pages. | | page | Integer | Current page number. | | hasNextPage | Boolean | Whether another page is available. | | items | Array<Object> | List of bill entries (see [Get Spot Account Bills](./GetBillRecords.md#response-parameters) for field details). |
**Response example** ```json { "total": 12, "pageSize": 20, "pages": 1, "page": 1, "hasNextPage": false, "items": [ { "billId": "701234567890123456", "coinId": 2, "coinName": "USDT", "bizType": "transfer_in", "deltaAmount": "100.00000000", "afterAmount": "910.00000000", "fees": "0", "cTime": "1764505800123" } ] } ```
--- ## Document: Account URL: /api-doc/spot/AccountAPI # Account --- ## Document: Get Transfer Records (USER_DATA) URL: /api-doc/spot/AccountAPI/TransferRecords # Get Transfer Records (USER_DATA) - **GET** ```/api/v3/account/transferRecords``` Weight(IP): 3
**Request parameters** | Parameter | Type | Required? | Description | |-----------|---------|-----------|-------------| | coinId | Integer | No | Filter by asset ID. | | fromType | String | No | Source account type. | | limit | Integer | No | Number of records to return (default 100). | | after | Long | No | Return records after this time (ms). | | before | Long | No | Return records before this time (ms). |
**Request example** ```powershell curl "https://api-spot.weex.com/api/v3/account/transferRecords?coinId=2&limit=50" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ ```
**Response parameters** | Field | Type | Description | |------------|--------|-------------| | coinName | String | Asset symbol. | | status | String | Transfer status. | | toType | String | Destination account type. | | toSymbol | String | Destination symbol (if applicable). | | fromType | String | Source account type. | | fromSymbol | String | Source symbol (if applicable). | | amount | String | Transfer amount. | | tradeTime | String | Transfer time (ms). |
**Response example** ```json [ { "coinName": "USDT", "status": "SUCCESS", "toType": "FUNDING", "toSymbol": "", "fromType": "SPOT", "fromSymbol": "", "amount": "100.00000000", "tradeTime": "1764505800123" } ] ```
--- ## Document: llms.txt URL: /api-doc/spot/AIResources/llms-txt # llms.txt --- ## Document: FAQs URL: /api-doc/spot/apifaq # FAQs > **Last Updated:** 2026-04-14
> **Document Summary:** This guide is designed to assist developers in quickly integrating the WEEX Spot API, addressing common technical issues regarding permission configurations, rate limits, and trading processes. --- ## 1. Account & Permission Configuration ### API Key Permission Types When creating an API Key, please check the corresponding permission options based on your business needs: | Permission | Description | Use Case | |:-------------|:-------------------------------------------------------------------------------------------------------------------------------------------|:---------------------------------------------------| | **Readonly** | **Read-only permission**. Only allows calling query-based endpoints (e.g., balance, trade history). No trading operations allowed. | Asset monitoring, ledger syncing, market analysis. | | **Spot** | **Spot trading permission**. Allows placing/canceling orders and querying assets specifically in the Spot market. | Spot quant bots, automated rebalancing. | **Note: These permissions are independent. If you need Spot trading operations, ensure the Spot permission is checked.** ### Why is my API permission disabled or returning an "API Restricted" error? * **Risk Control Trigger:** If the account triggers platform security risk controls (e.g., suspicious logins, high-frequency invalid requests), API permissions may be automatically disabled. * **Reactivation Process:** Please contact Customer Support. * **Effective Time:** Newly created or modified API Keys usually take approximately **15 minutes** to propagate globally across the system. ### Security Recommendations for Creating API Keys * **Passphrase:** When setting your API Passphrase, **do not include special characters** (alphanumeric only). * **IP Whitelist:** It is highly recommended to enable an IP Whitelist to enhance security. --- ## 2. Rate Limits WEEX imposes strict weight limits on different types of interfaces to ensure system stability. If limits are exceeded, the system will return an `HTTP 429` error. | Business Type | Operation Type | Rate Limit | |:-----------------------|:--------------------|:------------------------------------| | **Spot Trading** | Cancel Order | 80 times / 10s or 200 times / 1 min | | **Spot Trading** | Place Order | 100 times / 10s | | **Network Connection** | IP Weight | 500 weight / 10 sec / per IP | | **WebSocket** | Maximum Connections | 20 connections / per IP | --- ## 3. Technical Q&A ### Q1: Why does placing an order return `-1052` (Insufficient permissions)? **A:** This error is usually caused by: 1. **Permission Check:** The "Spot" trading permission was not checked in the API management page. 2. **Unsupported Trading Pair:** Certain tokens may not support API trading yet. 3. **Interface Version:** It is recommended to use **V3 interfaces**, as V1/V2 are being deprecated. ### Q2: Why does the WebSocket connection return a 403 error? **A:** When establishing a WebSocket connection, you **must include `User-Agent` info in the Header** (content can be custom). If this field is missing, the request will be blocked by the firewall. ### Q3: Why does canceling an order return `-1054`? **A:** Order does not exist. This is typically due to providing an incorrect order ID during the cancellation request. ### Q4: How do I get all tradable symbols? **A:** Visit [Get Spot Trading Pairs Interface](/api-doc/spot/ConfigAPI/GetAllProductInfo). ### Q5: Are TradingView or FIX API supported? **A:** Currently, neither is supported. --- ## 4. Common Problems - **Q1: How to get API support?** A: Join our official API support group and our admins will answer your questions. https://t.me/+Y72JdNeHcUw3NWQ1 - **Q2: Should I use BTCUSDT_SPBL or BTCUSDT for the symbol parameter?** A: The symbol parameter for all order APIs should use the values returned by the [/products](/api-doc/spot/ConfigAPI/GetProductInfo) interface. - **Q3: What is the rate limit of API?** A: 1. The rate limit of each API endpoint is marked on the doc page; 2. The rate limit of each API interface is calculated independently. - **Q4: Are symbols case-sensitive in API endpoints?** A: Yes. Symbols are case-sensitive and must be in all uppercase letters. - **Q5: If I forget the passphrase of API key, what should I do?** A: The passphrase of API Key can not be modified, please recreate your API Key. --- ## 5. More Support If you encounter technical difficulties during development, you can obtain support through the following channels: * **Official API Docs:** [WEEX API Documentation](/api-doc/spot/changelog) * **Telegram Tech Support Groups:** * **[WEEX API Tech Support (Chinese)](https://t.me/+7jac6zttXxZjOTRl)** * **[WEEX API Tech Support (English)](https://t.me/+Y72JdNeHcUw3NWQ1)** --- :::tip Developer Tips 1. API trading involves high risk; ensure your code includes robust error-handling logic. 2. Never disclose your API Key or Secret Key to third parties. 3. The content of this document may change with system upgrades. Please refer to the latest official API documentation. ::: --- ## Document: Update log URL: /api-doc/spot/changelog # Update log | Effective Time (UTC+8) | API | Update Type | Description | |------------------------|-----------------------------------------------------------------------------------|----------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------| | 2026-07-15 | * | Launched | API key trading-pair configuration is now available. | | 2026-06-22 | [Access Restrictions](/api-doc/spot/QuickStart/AccessRestrictions) | Modify | Updated access restriction rules. | | 2026-05-28 | [Batch Place Orders](/api-doc/spot/orderApi/BulkOrder) | Launched | Opened the batch order placement API. | | 2026-03-31 | [Exchange information](/api-doc/spot/ConfigAPI/GetProductInfo) | Modify | Modify the return parameters tickSize and stepSize of the API to String type | | 2026-03-18 | * | Launched | Spot Websocket V3 service officially launched; V2 will be decommissioned and no longer maintained. V3 delivers faster streaming speed and enhanced stability. | | 2026-03-09 | * | Launched | Spot Market V3 launched with improved performance and stability; V3 will continue to be maintained while V2 support is discontinued. | --- ## Document: Error Codes URL: /api-doc/spot/CommonErrorCodes # Error Codes Here is the error JSON payload: ```json { "code": -1121, "msg": "Invalid symbol." } ``` Errors consist of two parts: an error code and a message. Codes are universal, but messages can vary. ## 10xx - General Server or Network issues ### -1000 UNKNOWN_ERROR - An unknown error occurred. ### -1054 SYSTEM_ERROR - System error, please retry later. ## 10xx - Authentication / Access ### -1040 ACCESS_KEY_EMPTY - ACCESS_KEY header is required. ### -1041 ACCESS_SIGN_EMPTY - ACCESS_SIGN header is required. ### -1042 ACCESS_TIMESTAMP_EMPTY - ACCESS_TIMESTAMP header is required. ### -1043 INVALID_ACCESS_TIMESTAMP - Invalid ACCESS_TIMESTAMP. ### -1044 INVALID_ACCESS_KEY - Invalid ACCESS_KEY. ### -1045 INVALID_CONTENT_TYPE - Invalid Content-Type, please use application/json. ### -1046 ACCESS_TIMESTAMP_EXPIRED - Request timestamp expired. ### -1047 API_AUTH_ERROR - API authentication failed. ### -1049 API_KEY_OR_PASSPHRASE_INCORRECT - API key or passphrase incorrect. ### -1050 USER_STATUS_FORBIDDEN - User status is abnormal. ### -1051 PERMISSION_DENIED - Permission denied. ### -1052 INSUFFICIENT_PERMISSIONS - Insufficient permissions for this action. ### -1053 PERMISSION_VALIDATION_FAILED - Permission validation failed. ### -1055 USER_AUTH_NOT_SAFE - User must bind phone or Google authenticator. ### -1056 ILLEGAL_IP - Invalid IP address. ### -1057 USER_LOCKED - User account is locked. ### -1058 NO_PERMISSION_TRADE_PAIR - The trading pair is not supported via the API. Check the supported symbols here: [https://api-spot.weex.com/api/v3/apiTradingSymbols](https://api-spot.weex.com/api/v3/apiTradingSymbols). ### -1059 HIGH_FREQUENCY_ORDER_LIMITED - Too many high-frequency order requests in current window. ### -1060 API_KEY_SYMBOL_NOT_BOUND - This API key is not bound to the trading pair. ## 11xx - Request Content / Parameters ### -1115 INVALID_TIME_IN_FORCE - Invalid timeInForce. ### -1116 INVALID_ORDER_TYPE - Invalid order type. ### -1117 INVALID_SIDE - Invalid side. ### -1121 INVALID_SYMBOL - Invalid symbol. ### -1128 INVALID_PARAM_COMBINATION - Combination of optional parameters invalid. ### -1135 INVALID_JSON - Invalid JSON request. ### -1140 PARAM_VALIDATE_ERROR - Parameter validation failed. - limit must be between %d and %d. - startTime must be a valid millisecond timestamp. - endTime must be a valid millisecond timestamp. ### -1141 PARAM_EMPTY - Parameter '%s' cannot be empty. ### -1142 PARAM_ERROR - Parameter '%s' is invalid. ### -1150 REQUEST_METHOD_NOT_SUPPORTED - Request method not supported. ### -1160 DECIMAL_PRECISION_ERROR - Decimal precision error. ### -1170 QUERY_TIME_OUT_OF_RANGE - startTime must be within the last %d days. - Time range cannot exceed %d days. ### -1171 START_TIME_AFTER_END_TIME - startTime cannot be greater than endTime. ### -1180 CLIENT_OID_LENGTH_ERROR - client_oid length must not exceed 40 and must not contain special characters. ### -1190 FORBIDDEN_ACCESS - Access forbidden. Please contact support. ## 20xx - Spot Config / Validation ### -2007 SPOT_SYMBOL_NOT_EXIST - Symbol does not exist. ## 22xx - Spot Trading ### -2200 SPOT_ORDER_NOT_EXIST - Order does not exist. ### -2201 SPOT_ORDER_QUANTITY_EXCEEDS_LIMIT - Order quantity cannot exceed %d. --- ## Document: Get Coin Information URL: /api-doc/spot/ConfigAPI/CurrencyInfo # Get Coin Information - **GET** ```/api/v3/coins``` Weight(IP): 5
**Request parameters** NONE
**Request example** ```powershell curl "https://api-spot.weex.com/api/v3/coins" ```
**Response parameters** | Field | Type | Description | |------------------------------|---------------------|------------------------------------------------------------------| | coin | String | Coin symbol, e.g. `BTC`. | | name | String | Coin full name. | | depositAllEnable | Boolean | Whether deposits are enabled. | | withdrawAllEnable | Boolean | Whether withdrawals are enabled. | | networkList | Array<Object> | Supported network information. | | → network | String | Network name (e.g. `ERC20`). | | → isDefault | Boolean | Whether this is the default network. | | → depositEnable | Boolean | Whether deposits via this network are enabled. | | → withdrawEnable | Boolean | Whether withdrawals via this network are enabled. | | → withdrawFee | String | Withdrawal fee. | | → withdrawMin | String | Minimum withdrawal amount. | | → withdrawIntegerMultiple | BigDecimal | Required multiple for withdrawals. | | → minConfirm | Integer | Minimum confirmations required for deposits. | | → withdrawTag | Boolean | Whether a tag/memo is required. | | → depositDust | String | Minimum deposit amount that will be credited. | | → contractAddress | String | Contract address (if applicable). | | → contractAddressUrl | String | Explorer URL for the contract. | | → depositDesc / withdrawDesc | String | Optional status messages when deposits/withdrawals are disabled. |
**Response example** ```json [ { "coin": "USDT", "name": "USDT", "depositAllEnable": true, "withdrawAllEnable": true, "networkList": [ { "network": "BEP20(BSC)", "coin": "USDT", "withdrawIntegerMultiple": 1e-8, "isDefault": false, "depositEnable": true, "withdrawEnable": true, "depositDesc": null, "withdrawDesc": null, "name": "BEP20(BSC)", "withdrawFee": "0.000002", "withdrawMin": "0.00001", "withdrawInternalMin": null, "depositDust": "0.0001", "minConfirm": 11, "withdrawTag": false, "contractAddressUrl": "https://bscscan.com/token/", "contractAddress": "0x55d39832789f99059ff7545246999027b3197955" } ] } ] ```
--- ## Document: Get Spot API Trading Symbols URL: /api-doc/spot/ConfigAPI/GetAllProductInfo # Get Spot API Trading Symbols - **GET** ```/api/v3/apiTradingSymbols``` Weight(IP): 5
**Request parameters** No parameters.
**Request example** ```powershell curl "https://api-spot.weex.com/api/v3/apiTradingSymbols" ```
**Response** Returns an array of trading pairs that are currently approved for API spot trading.
**Response example** ```json [ "BTCUSDT", "ETHUSDT", "SOLUSDT" ] ```
--- ## Document: Exchange information URL: /api-doc/spot/ConfigAPI/GetProductInfo # Exchange information - **GET** ```/api/v3/exchangeInfo``` Weight(IP): 20
**Request parameters** | Parameter | Type | Required? | Description | |----------------|----------|-------------|-------------------------------------------------------------------------| | symbol | String | No | Single trading pair. Mutually exclusive with `symbols`. | | symbols | Array | No | Multiple trading pairs. Accepts comma-separated values or a JSON array. | | symbolStatus | String | No | Filter by symbol status. Values: `TRADING` (normal trading), `HALT` (trading suspended), `BREAK` (market closed). |
**Request example** ```powershell curl "https://api-spot.weex.com/api/v3/exchangeInfo?symbolStatus=TRADING" ```
**Response parameters** | Field | Type | Description | |----------------------------|---------------------|----------------------------------------------------------------------------------------------------------| | timezone | String | Exchange timezone (e.g. `UTC`). | | serverTime | Long | Current server time in milliseconds. | | rateLimits | Array<Object> | API access rate limits. | | → interval | String | Rate-limit interval unit, e.g. `MINUTE`. | | → intervalNum | Integer | Number of interval units, e.g. `1`. | | → limit | Integer | Maximum allowed count within the interval. | | → rateLimitType | String | Rate-limit type, e.g. `REQUEST_WEIGHT` or `ORDERS`. | | symbols | Array<Object> | Trading pair definitions. | | → symbol | String | Trading pair code, e.g. `BTCUSDT`. | | → status | String | Trading status. Values: `TRADING` (normal trading), `HALT` (trading suspended), `BREAK` (market closed). | | → baseAsset | String | Base asset symbol. | | → baseAssetPrecision | Integer | Base asset precision. | | → quoteAsset | String | Quote asset symbol. | | → quoteAssetPrecision | Integer | Quote asset precision. | | → tickSize | String | Minimum price increment (for quoteCoin) | | → stepSize | String | Minimum quantity increment (for baseCoin) | | → minTradeAmount | BigDecimal | Minimum order quantity. | | → maxTradeAmount | BigDecimal | Maximum order quantity. | | → takerFeeRate | BigDecimal | Taker fee rate. | | → makerFeeRate | BigDecimal | Maker fee rate. | | → buyLimitPriceRatio | BigDecimal | Maximum allowed deviation for buy limit orders. | | → sellLimitPriceRatio | BigDecimal | Maximum allowed deviation for sell limit orders. | | → marketBuyLimitSize | BigDecimal | Per-order size limit for market buys. | | → marketSellLimitSize | BigDecimal | Per-order size limit for market sells. | | → marketFallbackPriceRatio | BigDecimal | Fallback price ratio for market orders. | | → enableTrade | Boolean | Whether trading is enabled. | | → enableDisplay | Boolean | Whether the symbol is displayed. | | → displayDigitMerge | String | Depth merge configuration. | | → displayNew | Boolean | Whether the symbol is marked as “new”. | | → displayHot | Boolean | Whether the symbol is marked as “hot”. |
**Response example** ```json { "timezone": "UTC", "serverTime": 1764506000123, "rateLimits": [ { "rateLimitType": "REQUEST_WEIGHT", "interval": "SECOND", "intervalNum": 10, "limit": 2000 }, { "rateLimitType": "ORDERS", "interval": "SECOND", "intervalNum": 10, "limit": 5 } ], "symbols": [ { "symbol": "BTCUSDT", "status": "TRADING", "baseAsset": "BTC", "baseAssetPrecision": 8, "quoteAsset": "USDT", "quoteAssetPrecision": 8, "minTradeAmount": "0.0001", "maxTradeAmount": "1000", "takerFeeRate": "0.001", "makerFeeRate": "0.001", "buyLimitPriceRatio": "0.1", "sellLimitPriceRatio": "0.1", "marketBuyLimitSize": "50", "marketSellLimitSize": "50", "marketFallbackPriceRatio": "0.2", "enableTrade": true, "enableDisplay": true, "displayDigitMerge": "1,0.1,0.01", "displayNew": false, "displayHot": true } ] } ```
--- ## Document: Get Server Time URL: /api-doc/spot/ConfigAPI/GetServerTime # Get Server Time - **GET** ```/api/v3/time``` Weight(IP): 1
**Request parameters** NONE
**Request example** ```powershell curl "https://api-spot.weex.com/api/v3/time" ```
**Response parameters** | Field | Type | Description | |-------------|------|-------------| | serverTime | Long | Current server time in milliseconds. |
**Response example** ```json { "serverTime": 1764506000123 } ```
--- ## Document: Configuration Settings URL: /api-doc/spot/ConfigAPI # Configuration Settings --- ## Document: Test Connectivity URL: /api-doc/spot/ConfigAPI/Ping # Test Connectivity - **GET** ```/api/v3/ping``` Weight(IP): 1
**Request parameters** NONE
**Request example** ```powershell curl "https://api-spot.weex.com/api/v3/ping" ```
**Response parameters** Returns an empty JSON object on success.
**Response example** ```json {} ```
--- ## Document: Contact Us URL: /api-doc/spot/ContactUs # Contact Us For technical issues or any feedback, feel free to reach out to us via the following methods: - Email us at support@weex.com - Join our [Telegram community](https://t.me/+Y72JdNeHcUw3NWQ1) to stay updated and engage with the community. --- ## Document: API Introduction URL: /api-doc/spot/introduction/APIBriefIntroduction # API Introduction Get started with WEEX API. This is the official WEEX API guide. Features are updated regularly. Use the menu to view API docs for different products or switch languages. Each endpoint includes sample requests and responses for quick integration. --- ## Document: Market Making/Quantitative Trading URL: /api-doc/spot/introduction/MarketNegotiation # Market Making/Quantitative Trading We welcome institutional partners with proven market-making strategies and substantial trading volumes to join our Market Maker Program.To apply, please provide the following information in an email to us: - support@weex.com (for market maker application) 1. Your UID (ensure no commission affiliations exist for this UID) 2. Screenshots as proof of 30-day market-making volume from other exchanges 3. A brief description of your market-making strategy (no details required) --- ## Document: API Update Notifications URL: /api-doc/spot/introduction/UpdateFollow # API Update Notifications WEEX will announce API additions, updates, deprecations, and other critical changes through official notices in advance. It is recommended to follow and subscribe to API change notifications to stay updated. Click [here](https://weexsupport.zendesk.com/hc/en-us) to subscribe to announcements. --- ## Document: Get 24h Ticker Statistics URL: /api-doc/spot/MarketDataAPI/GetAllTickerInfo # Get 24h Ticker Statistics - **GET** ```/api/v3/market/ticker/24hr``` Weight(IP): 2
**Request parameters** | Parameter | Type | Required? | Description | |-------------|---------|-------------|-------------------------------------------------------------------------| | symbol | String | No | Single trading pair (mutually exclusive with `symbols`). | | symbols | Array | No | Multiple trading pairs. Accepts comma-separated values or a JSON array. |
**Request example** ```powershell curl "https://api-spot.weex.com/api/v3/market/ticker/24hr?symbols=BTCUSDT,ETHUSDT" ```
**Response parameters** | Field | Type | Description | |--------------------|--------|-------------------------------------------------| | symbol | String | Trading pair. | | priceChange | String | Absolute price change over the last 24 hours. | | priceChangePercent | String | Percentage price change over the last 24 hours. | | lastPrice | String | Last traded price. | | bidPrice | String | Best bid price. | | bidQty | String | Best bid quantity. | | askPrice | String | Best ask price. | | askQty | String | Best ask quantity. | | openPrice | String | Opening price 24 hours ago. | | highPrice | String | Highest price in the last 24 hours. | | lowPrice | String | Lowest price in the last 24 hours. | | volume | String | Base asset volume in the last 24 hours. | | quoteVolume | String | Quote asset volume in the last 24 hours. | | openTime | Long | First trade timestamp in the 24h window (ms). | | closeTime | Long | Last trade timestamp in the 24h window (ms). | | count | Long | Number of trades in the 24h window. | When `symbol` is provided, the endpoint returns a single object; otherwise, it returns an array of objects.
**Response example** ```json [ { "symbol": "BTCUSDT", "priceChange": "-350.50", "priceChangePercent": "-0.0051", "lastPrice": "68920.40", "bidPrice": "68919.90", "bidQty": "2.480", "askPrice": "68920.70", "askQty": "1.375", "openPrice": "69270.90", "highPrice": "70110.00", "lowPrice": "68500.10", "volume": "1524.361", "quoteVolume": "105060432.75", "openTime": 1764412800000, "closeTime": 1764499200000, "count": 98642 } ] ```
--- ## Document: Get Best Bid/Ask URL: /api-doc/spot/MarketDataAPI/GetBookTicker # Get Best Bid/Ask - **GET** ```/api/v3/market/ticker/bookTicker``` Weight(IP): 4
**Request parameters** | Parameter | Type | Required? | Description | |-----------|--------|-----------|-------------| | symbol | String | No | Single trading pair (mutually exclusive with `symbols`). | | symbols | Array | No | Multiple trading pairs. Accepts comma-separated values or a JSON array. |
**Request example** ```powershell curl "https://api-spot.weex.com/api/v3/market/ticker/bookTicker?symbols=BTCUSDT,ETHUSDT" ```
**Response parameters** | Field | Type | Description | |----------|--------|-------------| | symbol | String | Trading pair. | | bidPrice | String | Best bid price. | | bidQty | String | Best bid quantity. | | askPrice | String | Best ask price. | | askQty | String | Best ask quantity. | If `symbol` is supplied the response is a single object; otherwise, it is an array.
**Response example** ```json [ { "symbol": "BTCUSDT", "bidPrice": "68919.90", "bidQty": "2.480", "askPrice": "68920.60", "askQty": "1.102" } ] ```
--- ## Document: Get Order Book Depth URL: /api-doc/spot/MarketDataAPI/GetDepthData # Get Order Book Depth - **GET** ```/api/v3/market/depth``` Weight(IP): 5
**Request parameters** | Parameter | Type | Required? | Description | |-----------|--------|-----------|-------------| | symbol | String | Yes | Trading pair, e.g. `BTCUSDT`. | | limit | Integer| No | Number of depth entries. Supported values: `15`, `200`. Default `15`. |
**Request example** ```powershell curl "https://api-spot.weex.com/api/v3/market/depth?symbol=BTCUSDT&limit=200" ```
**Response parameters** | Field | Type | Description | |--------------|-----------------|-------------| | lastUpdateId | Long | Order book snapshot ID. | | bids | Array<Array> | Bid depth entries formatted as `[price, quantity]`. | | asks | Array<Array> | Ask depth entries formatted as `[price, quantity]`. |
**Response example** ```json { "lastUpdateId": 451234567890, "bids": [ ["68950.10", "2.345"], ["68949.80", "0.512"] ], "asks": [ ["68950.20", "1.104"], ["68950.40", "3.872"] ] } ```
--- ## Document: Get Kline Data URL: /api-doc/spot/MarketDataAPI/GetKLineData # Get Kline Data - **GET** ```/api/v3/market/klines``` Weight(IP): 2
**Request parameters** | Parameter | Type | Required? | Description | |-------------|--------|-------------|-----------------------------------------------------------------------| | symbol | String | Yes | Trading pair, e.g. `BTCUSDT`. | | interval | String | Yes | Candlestick interval (e.g. [1m,5m,15m,30m,1h,2h,4h,6h,8h,12h,1d,1w]). |
**Request example** ```powershell curl "https://api-spot.weex.com/api/v3/market/klines?symbol=BTCUSDT&interval=1m&limit=3" ```
**Response parameters** Each kline is an array with the following indexes: | Index | Description | |-------|---------------------------------| | 0 | Open time (ms). | | 1 | Open price. | | 2 | High price. | | 3 | Low price. | | 4 | Close price. | | 5 | Volume (base asset). | | 6 | Close time (ms). | | 7 | Quote asset volume. | | 8 | Number of trades. | | 9 | Taker buy volume (base asset). | | 10 | Taker buy volume (quote asset). |
**Response example** ```json [ [ 1764505860000, "68940.10", "68955.00", "68938.50", "68952.40", "12.345", 1764505919999, "850760.12", 124, "6.789", "468123.77" ] ] ```
--- ## Document: Get Latest Price URL: /api-doc/spot/MarketDataAPI/GetTickerInfo # Get Latest Price - **GET** ```/api/v3/market/ticker/price``` Weight(IP): 4
**Request parameters** | Parameter | Type | Required? | Description | |-----------|--------|-----------|-------------| | symbol | String | No | Single trading pair (mutually exclusive with `symbols`). | | symbols | Array | No | Multiple trading pairs. Accepts comma-separated values or a JSON array. |
**Request example** ```powershell curl "https://api-spot.weex.com/api/v3/market/ticker/price?symbol=BTCUSDT" ```
**Response parameters** | Field | Type | Description | |---------|--------|-------------| | symbol | String | Trading pair. | | price | String | Latest traded price. | The endpoint returns either a single object or an array of objects depending on whether `symbol` was supplied.
**Response example** ```json { "symbol": "BTCUSDT", "price": "68920.40" } ```
--- ## Document: Get Recent Trades URL: /api-doc/spot/MarketDataAPI/GetTradeData # Get Recent Trades - **GET** ```/api/v3/market/trades``` Weight(IP): 25
**Request parameters** | Parameter | Type | Required? | Description | |-----------|---------|-----------|-------------| | symbol | String | Yes | Trading pair, e.g. `BTCUSDT`. | | limit | Integer | No | Number of trades to return. Range `1`–`1000`, default `100`. |
**Request example** ```powershell curl "https://api-spot.weex.com/api/v3/market/trades?symbol=BTCUSDT&limit=50" ```
**Response parameters** | Field | Type | Description | |---------------|---------|-------------| | id | String | Trade identifier. | | price | String | Trade price. | | qty | String | Executed quantity (base asset). | | quoteQty | String | Executed amount (quote asset). | | time | Long | Trade time (milliseconds). | | isBuyerMaker | Boolean | `true` if the buyer was the maker side. | | isBestMatch | Boolean | `true` if the trade matched the best price level. |
**Response example** ```json [ { "id": "120045678901", "price": "68950.00", "qty": "0.002", "quoteQty": "137.90000", "time": 1764506000456, "isBuyerMaker": true, "isBestMatch": true } ] ```
--- ## Document: Market URL: /api-doc/spot/MarketDataAPI # Market --- ## Document: Batch Cancel Orders (TRADE) URL: /api-doc/spot/orderApi/BulkCancel # Batch Cancel Orders (TRADE) - **DELETE** ```/api/v3/order/batch``` Weight(IP): 5
**Request parameters** | Parameter | Type | Required? | Description | |---------------------|----------|-------------|-------------------------------------------------------------------| | orderIds | Array | Conditional | Order IDs to cancel. Required when `origClientOrderIds` is empty. | | origClientOrderIds | Array | Conditional | Client order IDs to cancel. Required when `orderIds` is empty. |
**Request example** ```powershell curl -X DELETE "https://api-spot.weex.com/api/v3/order/batch" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "Content-Type: application/json" \ -d '{ "symbol": "BTCUSDT", "orderIds": [702345678901234567, 702345678901234568] }' ```
**Response parameters** | Field | Type | Description | |---------------------|---------------------|-----------------------------------------| | orderList | Array<Object> | Per-order cancel result. | | → orderId | Long | Cancelled order ID (if found). | | → status | String | Final status, e.g. `CANCELED`. | | → errorMsg | String | Error message when cancellation failed. |
**Response example** ```json { "orderList": [ { "orderId": 702345678901234567, "status": "CANCELED" }, { "orderId": 702345678901234568, "status": "EXPIRED", "errorMsg": "order not found" } ] } ```
--- ## Document: Batch Place Orders (TRADE) URL: /api-doc/spot/orderApi/BulkOrder # Batch Place Orders (TRADE) - **POST** ```/api/v3/order/batch``` **Request Weight** 5 on 10s order rate limit(X-ORDER-COUNT-10S); 5 on 1min order rate limit(X-ORDER-COUNT-1M); 0 on IP rate limit(X-USED-WEIGHT-1M);
**Request parameters** | Parameter | Type | Required? | Description | |------------|---------------------|-----------|-------------| | symbol | String | Yes | Trading pair, e.g. `BTCUSDT`. | | orderList | Array<Object> | Yes | Up to 10 order definitions. | Each element of `orderList` supports the following fields: | Field | Type | Required? | Description | |-------------------|--------|-----------|-------------| | side | String | Yes | `BUY` or `SELL`. | | type | String | Yes | `LIMIT` or `MARKET`. | | timeInForce | String | Conditional | Required when `type = LIMIT`. Values: `GTC`, `IOC`, `FOK`. | | quantity | String | Yes | Order quantity. | | price | String | Conditional | Limit price when `type = LIMIT`. | | newClientOrderId | String | No | Client-defined order ID. |
**Request example** ```powershell curl -X POST "https://api-spot.weex.com/api/v3/order/batch" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "Content-Type: application/json" \ -d '{ "symbol": "BTCUSDT", "orderList": [ { "side": "BUY", "type": "LIMIT", "timeInForce": "GTC", "quantity": "0.01", "price": "68850", "newClientOrderId": "batch-1" }, { "side": "SELL", "type": "MARKET", "quantity": "0.02", "newClientOrderId": "batch-2" } ] }' ```
**Response parameters** | Field | Type | Description | |-------------|---------------------|-------------| | orderList | Array<Object> | Per-order result list. | | → symbol | String | Trading pair. | | → orderId | Long | Created order ID (present when successful). | | → clientOrderId | String | Client-defined order ID. | | → transactTime | Long | Order acceptance time (ms). | | → errorCode | String | Error code when the order failed. | | → errorMsg | String | Error message when the order failed. |
**Response example** ```json { "orderList": [ { "symbol": "BTCUSDT", "orderId": 702345678901234700, "clientOrderId": "batch-1", "transactTime": 1764506000456 }, { "symbol": "BTCUSDT", "clientOrderId": "batch-2", "errorCode": "INSUFFICIENT_BALANCE", "errorMsg": "insufficient balance" } ] } ```
--- ## Document: Cancel All Orders by Symbol (TRADE) URL: /api-doc/spot/orderApi/Cancel-Symbol-Orders # Cancel All Orders by Symbol (TRADE) - **DELETE** ```/api/v3/openOrders``` Weight(IP): 5
**Request parameters** | Parameter | Type | Required? | Description | |-----------|--------|-----------|-------------| | symbol | String | Yes | Trading pair whose open orders should be cancelled. |
**Request example** ```powershell curl -X DELETE "https://api-spot.weex.com/api/v3/openOrders?symbol=BTCUSDT" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ ```
**Response parameters** Returns an array of cancelled orders with the following fields: | Field | Type | Description | |---------------|---------|---------------------| | orderId | Long | Cancelled order ID. | | status | String | Final order status. |
**Response example** ```json [ { "orderId": 702345678901234567, "status": "CANCELED" } ] ```
--- ## Document: Cancel Order (TRADE) URL: /api-doc/spot/orderApi/CancelOrder # Cancel Order (TRADE) - **DELETE** ```/api/v3/order``` Weight(IP): 1
**Request parameters** | Parameter | Type | Required? | Description | |-------------------|--------|-----------|-------------| | orderId | Long | Conditional | Order ID to cancel. Required when `origClientOrderId` is not supplied. | | origClientOrderId | String | Conditional | Client order ID to cancel. Required when `orderId` is not supplied. |
**Request example** ```powershell curl -X DELETE "https://api-spot.weex.com/api/v3/order?symbol=BTCUSDT&orderId=702345678901234567" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ ```
**Response parameters** | Field | Type | Description | |-------------------|----------|---------------------------------| | orderId | Long | Cancelled order ID. | | status | String | Final status (e.g. `CANCELED`). |
**Response example** ```json { "orderId": 702345678901234567, "status": "CANCELED" } ```
--- ## Document: Get All Orders (USER_DATA) URL: /api-doc/spot/orderApi/HistoryOrders # Get All Orders (USER_DATA) - **GET** ```/api/v3/allOrders``` Weight(IP): 10
**Request parameters** | Parameter | Type | Required? | Description | |-----------|---------|-----------|-------------| | symbol | String | Yes | Trading pair to query. | | startTime | Long | No | Start time in milliseconds. | | endTime | Long | No | End time in milliseconds. Must be greater than or equal to `startTime`. | | limit | Integer | No | Number of records per page (default 100, maximum 200). | - If `startTime` and `endTime` are not provided, the default query range is the last 7 days. - The interval between `startTime` and `endTime` cannot exceed 90 days. - Only data from the last 1 year can be queried.
**Request example** ```powershell curl "https://api-spot.weex.com/api/v3/allOrders?symbol=BTCUSDT&limit=200" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ ```
**Response parameters** Returns a list of order objects with the same fields described in [Get Order Details](./OrderDetails.md#response-parameters).
**Response example** ```json [ { "symbol": "BTCUSDT", "orderId": 702345678901234567, "clientOrderId": "my-spot-order-001", "price": "68900", "origQty": "0.01", "executedQty": "0.01", "cummulativeQuoteQty": "689.00", "status": "FILLED", "timeInForce": "GTC", "type": "LIMIT", "side": "BUY", "time": 1764506000456, "updateTime": 1764506001556, "isWorking": false } ] ```
--- ## Document: Trade URL: /api-doc/spot/orderApi # Trade --- ## Document: Get Order Details (USER_DATA) URL: /api-doc/spot/orderApi/OrderDetails # Get Order Details (USER_DATA) - **GET** ```/api/v3/order``` Weight(IP): 2
**Request parameters** | Parameter | Type | Required? | Description | |-------------------|--------|-----------|-------------| | orderId | Long | Conditional | Order ID. Required when `origClientOrderId` is not supplied. | | origClientOrderId | String | Conditional | Client order ID. Required when `orderId` is not supplied. |
**Request example** ```powershell curl "https://api-spot.weex.com/api/v3/order?orderId=702345678901234567" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ ```
**Response parameters** | Field | Type | Description | |---------------------|---------|-------------| | symbol | String | Trading pair. | | orderId | Long | Order ID. | | clientOrderId | String | Client-defined order ID. | | price | String | Order price. | | origQty | String | Original order quantity. | | executedQty | String | Filled quantity. | | cummulativeQuoteQty | String | Filled amount in quote asset. | | status | String | Order status (e.g. `NEW`, `FILLED`, `CANCELED`). | | timeInForce | String | Time-in-force policy. | | type | String | Order type. | | side | String | `BUY` or `SELL`. | | time | Long | Creation time (ms). | | updateTime | Long | Last update time (ms). | | isWorking | Boolean | Whether the order is active. |
**Response example** ```json { "symbol": "BTCUSDT", "orderId": 702345678901234567, "clientOrderId": "my-spot-order-001", "price": "68900", "origQty": "0.01", "executedQty": "0.01", "cummulativeQuoteQty": "689.00", "status": "FILLED", "timeInForce": "GTC", "type": "LIMIT", "side": "BUY", "time": 1764506000456, "updateTime": 1764506001556, "isWorking": false } ```
--- ## Document: Place Order (TRADE) URL: /api-doc/spot/orderApi/PlaceOrder # Place Order (TRADE) - **POST** ```/api/v3/order``` **Request Weight** 1 on 10s order rate limit(X-ORDER-COUNT-10S); 1 on 1min order rate limit(X-ORDER-COUNT-1M); 0 on IP rate limit(X-USED-WEIGHT-1M);
**Request parameters** | Parameter | Type | Required? | Description | |------------------|--------|-----------|-------------| | symbol | String | Yes | Trading pair, e.g. `BTCUSDT`. | | side | String | Yes | Order side. Supported values: `BUY`, `SELL`. | | type | String | Yes | Order type. Supported values: `LIMIT`, `MARKET`. | | timeInForce | String | Conditional | Time-in-force policy. Required when `type = LIMIT`. Supported values: `GTC`, `IOC`, `FOK`. | | quantity | String | Yes | Order quantity. | | price | String | Conditional | Limit price. Required when `type = LIMIT`. | | newClientOrderId | String | No | Client-defined order ID (if omitted, the system assigns one). If an active order already uses the same `newClientOrderId`, the API returns success but does not create a duplicate order. |
**Request example** ```powershell curl -X POST "https://api-spot.weex.com/api/v3/order" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "Content-Type: application/json" \ -d '{ "symbol": "BTCUSDT", "side": "BUY", "type": "LIMIT", "timeInForce": "GTC", "quantity": "0.01", "price": "68900", "newClientOrderId": "my-spot-order-001" }' ```
**Response parameters** | Field | Type | Description | |----------------|--------|-------------| | symbol | String | Trading pair. | | orderId | Long | Order ID generated by the system. | | clientOrderId | String | Client-defined order ID. | | transactTime | Long | Order acceptance timestamp (ms). |
**Response example** ```json { "symbol": "BTCUSDT", "orderId": 702345678901234567, "clientOrderId": "my-spot-order-001", "transactTime": 1764506000456 } ```
--- ## Document: Get Trade History (USER_DATA) URL: /api-doc/spot/orderApi/TransactionDetails # Get Trade History (USER_DATA) - **GET** ```/api/v3/myTrades``` Weight(IP): 5
**Request parameters** | Parameter | Type | Required? | Description | |-------------|----------|-------------|---------------------------------------| | symbol | String | Yes | Trading pair. | | orderId | Long | No | Filter by order ID. | | startTime | Long | No | Start time (ms). | | endTime | Long | No | End time (ms). Must be ≥ `startTime`. | | limit | Integer | No | Page size (default 100, maximum 200). | - If `startTime` and `endTime` are not provided, the default query range is the last 7 days. - The interval between `startTime` and `endTime` cannot exceed 90 days. - Only data from the last 1 year can be queried.
**Request example** ```powershell curl "https://api-spot.weex.com/api/v3/myTrades?symbol=BTCUSDT&limit=50" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ ```
**Response parameters** | Field | Type | Description | |-------------|----------|---------------------------------| | symbol | String | Trading pair. | | id | Long | Trade identifier. | | orderId | Long | Related order ID. | | price | String | Trade price. | | qty | String | Filled quantity (base asset). | | quoteQty | String | Filled amount (quote asset). | | commission | String | Commission amount. | | time | Long | Trade time (ms). | | isBuyer | Boolean | Whether the user was the buyer. |
**Response example** ```json [ { "symbol": "BTCUSDT", "id": 801234567890123456, "orderId": 702345678901234567, "price": "68950.00", "qty": "0.01", "quoteQty": "689.50", "commission": "0.138", "time": 1764506001556, "isBuyer": true } ] ```
--- ## Document: Get Current Open Orders (USER_DATA) URL: /api-doc/spot/orderApi/UnfinishedOrders # Get Current Open Orders (USER_DATA) - **GET** ```/api/v3/openOrders``` Weight(IP): 3
**Request parameters** | Parameter | Type | Required? | Description | |-----------|--------|-----------|-------------| | symbol | String | No | Filter by trading pair. If omitted, returns open orders for all symbols. |
**Request example** ```powershell curl "https://api-spot.weex.com/api/v3/openOrders?symbol=BTCUSDT" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ ```
**Response parameters** Each returned object contains the fields below: | Field | Type | Description | |---------------------|---------|-------------| | symbol | String | Trading pair. | | orderId | Long | Order ID. | | clientOrderId | String | Client-defined order ID. | | price | String | Order price. | | origQty | String | Original order quantity. | | executedQty | String | Filled quantity. | | cummulativeQuoteQty | String | Filled amount in quote asset. | | status | String | Order status (e.g. `NEW`, `PARTIALLY_FILLED`). | | timeInForce | String | Time-in-force policy. | | type | String | Order type. | | side | String | `BUY` or `SELL`. | | time | Long | Creation time (ms). | | updateTime | Long | Last update time (ms). | | isWorking | Boolean | Whether the order is currently working. |
**Response example** ```json [ { "symbol": "BTCUSDT", "orderId": 702345678901234567, "clientOrderId": "my-spot-order-001", "price": "68900", "origQty": "0.01", "executedQty": "0", "cummulativeQuoteQty": "0", "status": "NEW", "timeInForce": "GTC", "type": "LIMIT", "side": "BUY", "time": 1764506000456, "updateTime": 1764506000456, "isWorking": true } ] ```
--- ## Document: Access Restrictions URL: /api-doc/spot/QuickStart/AccessRestrictions # Access Restrictions REST API access is rate limited. Except for order placement endpoints, all endpoints are rate limited by IP. Order placement endpoints are rate limited by the `ORDERS` type. Order placement endpoints refer to single order placement and batch order placement endpoints; other order-related endpoints such as canceling orders and querying orders are still rate limited by IP. When you exceed a request rate limit, the request fails with HTTP status code `429`. When you receive `429`, you are responsible for stopping requests and must not abuse the API. Violating the limits results in a `10s` ban. ## Basic Information The following `intervalLetter` values are used in response headers: | interval | intervalLetter | |----------|----------------| | SECOND | S | | MINUTE | M | | HOUR | H | | DAY | D | The `rateLimits` array in `/api/v3/exchangeInfo` contains REST API rate limits, including but not limited to the REST endpoints in this document. These limits include weighted request limits and order rate limits. For more information about limit types, see the enum definitions. ## IP Rate Limits Except for order placement endpoints, all endpoints use IP rate limits. These limits are based on IP, not API Key or UID. Each endpoint has a corresponding `weight`. Some endpoints may have different weights depending on request parameters. Endpoints that consume more resources have higher weights. Each request includes the following response headers: | Header | Description | |--------|-------------| | `X-USED-WEIGHT-(intervalNum)(intervalLetter)` | Used weight for the current IP within the interval. | | `X-REMAINING-WEIGHT-(intervalNum)(intervalLetter)` | Remaining weight for the current IP within the interval. | For example, `X-USED-WEIGHT-1M` indicates the used weight for the current IP within a 1-minute interval. ## ORDERS Rate Limits Order placement endpoints are rate limited by the `ORDERS` type. Order placement endpoints refer to single order placement and batch order placement endpoints. This limit is based on the account, that is, `userId`. Order placement endpoints do not consume IP weight. The IP rate limit count in response headers is `0`. Each order placement request includes the following response headers: | Header | Description | |--------|-------------| | `X-ORDER-COUNT-(intervalNum)(intervalLetter)` | Used order count for the current account within the interval. | | `X-ORDER-REMAINING-(intervalNum)(intervalLetter)` | Remaining order count for the current account within the interval. | --- ## Document: API Domain URL: /api-doc/spot/QuickStart/APIDomain # API Domain You can use different domain as below Rest API. | Domain Name | API | Description | |----------------------|-------------------------------|-------| | Spot REST Domain | https://api-spot.weex.com | Main Domain | --- ## Document: Preparation URL: /api-doc/spot/QuickStart/IntegrationPreparation # Preparation To use the API, please log in to the web platform, create and configure API keys with proper permissions, then proceed with development and trading as detailed in this documentation. Click [here](https://www.weex.com/account/newapi) to create an API Key. Each user can create up to 10 API Key groups. Each key can be configured for "Read" and/or "Trade" permissions. Permission details: - The default permission for newly created APIs is `Read Only` - If you need to trade via API, select the corresponding trading permission `Spot` After creating an API Key, securely store the following: - `APIKey` — The unique identifier for API authentication which is algorithmically generated. - `SecretKey` — The system-generated private key for signature encryption. - `Passphrase` —A user-defined access phrase. Note: If lost, the Passphrase cannot be recovered. You must create a new API key. :::tip You can bind IP addresses to API keys when creating API keys. Unrestricted API keys (with no IP address binding) pose security risks. ::: :::warning ::: --- ## Document: API Types URL: /api-doc/spot/QuickStart/InterfaceType # API Types This section categorizes APIs into two types: - Public APIs - Private APIs **Public APIs** Public APIs allow users to retrieve configuration and market data.These requests do not require authentication. **Private APIs** Private APIs enable order management and account management.Each private request must be authenticated using a standardized signature method. Private APIs require validation with your API key. --- ## Document: API Public Parameters URL: /api-doc/spot/QuickStart/PublicAPIParameters # API Public Parameters **side(order direction)** | Field | Description | | :----- | :---------- | | `sell` | Sell order | | `buy` | Buy order | **orderType (Order Type)** | Field | Description | | :------- | :----------- | | `limit` | Limit order | | `market` | Market order | **force (Order Type)** | Field | Description | | :--------- | :---------------------------------------- | | `normal` | Default order, no special controls needed | | `postOnly` | Post-only order | | `fok` | Fill-Or-Kill order | | `ioc` | Immediate-Or-Cancel order | **status (Order Status)** | Field | Description | | :------------- | :--------------- | | `new` | Unfilled | | `partial_fill` | Partially filled | | `full_fill` | All Filled | | `cancelled` | Canceled | **groupType (Major transaction types)** | Field | Description | | :------------ | :---------- | | `deposit` | Deposit | | `withdraw` | Withdraw | | `transaction` | Trade | | `transfer` | Transfer | | `other` | Others | **bizType (Account capital flow operation type)** **bizType (Account capital flow operation type)** | Field | Description | |:--------------------------------------|:--------------------------------| | `deposit` | Deposit | | `withdraw` | Withdrawal | | `transfer_in` | Transfer-in | | `transfer_out` | Transfer-out | | `trade_in` | Asset purchase | | `trade_out` | Asset sale | | `rake_back_reward` | Commission rebate reward | | `airdrop_reward` | Financial airdrop reward | | `rr_agent_reward` | Referral commission reward | | `launch_pad_airdrop_in` | LaunchPool airdrop transfer in | | `launch_pad_airdrop_out` | LaunchPool airdrop transfer out | | `system_issued` | System issued | | `airdrop_reward_for_product_activity` | Product activity airdrop reward | | `red_packet_create` | Red packet creation | | `red_packet_claim` | Red packet claim | | `red_packet_refund` | Red packet refund | **status (Order status)** | Field | Description | | :------------------ | :--------------------- | | `cancel` | Canceled | | `reject` | Rejected | | `success` | Success | | `wallet-fail` | Wallet failed | | `wallet-processing` | Wallet is processing | | `first-audit` | First review | | `recheck` | Second review | | `first-reject` | First review rejected | | `recheck-reject` | Second review rejected | **type (Withdrawal address query)** | Field | Description | | :--------------- | :--------------- | | `chain-on` | On-chain | | `inner-transfer` | Internal address | **accountType (Account type)** Not case-sensitive | Field | Description | | :--------- | :------------------------------- | | `EXCHANGE` | Spot account | | `OTC_SGD` | OTC account | | `CONTRACT` | Futures account | | `USD_MIX` | Quanto swap account | | `USDT_MIX` | USDT-M perpetual futures account | **Candlestick intervals (granularity)** - 1min (1 minute) - 5min (5 minutes) - 15min (15 minutes) - 30min (30 minutes) - 1h (1 hour) - 4h (4 hours) - 12h (12 hours) - 1day (1 day) - 1week (1 week) --- ## Document: Request Processing URL: /api-doc/spot/QuickStart/RequestInteraction # Request Processing ```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 = "https://api-spot.weex.com"; // 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"); 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"); 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/v3/openOrders"; String queryString = "?symbol=BTCUSDT"; String response = sendRequestGet(API_KEY, SECRET_KEY, ACCESS_PASSPHRASE, "GET", requestPath, queryString); System.out.println("GET Response: " + response); // POST request example String postPath = "/api/v3/order"; String body = "{\"symbol\":\"BTCUSDT\",\"side\":\"BUY\",\"type\":\"LIMIT\",\"timeInForce\":\"GTC\",\"quantity\":\"0.01\",\"price\":\"68900\"}"; response = sendRequestPost(API_KEY, SECRET_KEY, ACCESS_PASSPHRASE, "POST", postPath, "", body); System.out.println("POST Response: " + response); } catch (Exception e) { e.printStackTrace(); } } } ``` ```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() # print(base64.b64encode(signature).decode()) return base64.b64encode(signature).decode() 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() # print(base64.b64encode(signature).decode()) 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)) # print(timestamp) 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" } url = "https://api-spot.weex.com" # Please replace with the actual API address if method == "GET": response = requests.get(url + request_path, headers=headers) elif method == "POST": response = requests.post(url + request_path, headers=headers, data=body) return response def send_request_get(api_key, secret_key, access_passphrase, method, request_path, query_string): timestamp = str(int(time.time() * 1000)) # print(timestamp) 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" } url = "https://api-spot.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(): # Example of calling a GET request request_path = "/api/v3/openOrders" query_string = '?symbol=BTCUSDT' response = send_request_get(api_key, secret_key, access_passphrase, "GET", request_path, query_string) print(response.status_code) print(response.text) def post(): # Example of calling a POST request request_path = "/api/v3/order" body = { "symbol": "BTCUSDT", "side": "BUY", "type": "LIMIT", "timeInForce": "GTC", "quantity": "0.01", "price": "68900" } 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__': get() post() ``` All requests are based on the HTTPS protocol. The Content-Type in the request headers must be set to 'application/json'. **Request Processing** - Request parameters: Parameter encapsulation according to endpoint request parameter specification. - Submit request: Submit the encapsulated parameters to the server via GET/POST. - Server response: The server first performs security checks on the request data, and after passing the check, returns the response data to the user in the JSON format based on the operation logic. - Data processing: Process the server response data. **Success** HTTP 200 status codes indicates success and may contain content.Response content (if any) will be included in the returned data. **Common error codes** - 400 Bad Request – Invalid request format - 401 Unauthorized – Invalid API Key - 403 Forbidden – You do not have access to the requested resource - 404 Not Found — No requests found - 429 Too Many Requests – Rate limit exceeded - 500 Internal Server Error – We had a problem with our server - Failed responses include error descriptions in the body. --- ## Document: Signature URL: /api-doc/spot/QuickStart/Signature # Signature The ACCESS-SIGN request header is generated by using the **HMAC SHA256** method encryption on the **timestamp + method.toUpperCase() + requestPath + "?" + queryString + body** string (+ denotes string concatenation), and putting the result through **BASE64** encoding. **Timestamp** The `ACCESS-TIMESTAMP` in request signatures is in milliseconds. Requests are rejected if the timestamp deviates by more than 30 seconds from the API server time. If the local server time deviates significantly from the API server time, we recommend querying the API server time and using it to update the HTTP Header. **Request Formats** The following request methods are currently supported: - GET: Parameters are sent to the server in the path through queryString. - POST: Parameters are sent to the server in the body as JSON. - DELETE: Parameters are sent to the server through queryString or a JSON body, according to the endpoint documentation. When generating the signature, concatenate `requestPath`, `queryString`, and `body` according to the actual request content. **Signature Field Description** - timestamp: This matches the ACCESS-TIMESTAMP header. - method: The request method (GET/POST/DELETE), with all letters in uppercase. - requestPath: API endpoint path. - queryString: The query parameters after the "?" in the URL. - body: The string that corresponds to the request body. It can be omitted if the request has no body. **Signature format rules if queryString is empty** - timestamp + method.toUpperCase() + requestPath + body **Signature format rules if queryString is not empty** - timestamp + method.toUpperCase() + requestPath + "?" + queryString + body **Examples** Fetching market depth, using BTCUSDT as an example: - Timestamp = 1591089508404 - Method = "GET" - requestPath = "/api/v3/market/depth" - queryString= "symbol=BTCUSDT&limit=20" **Generate the string to be signed:** - '1591089508404GET/api/v3/market/depth?symbol=BTCUSDT&limit=20' Placing an order, using BTCUSDT_SPBL as an example: - Timestamp = 1561022985382 - Method = "POST" - requestPath = "/api/v3/order" - body = ```json {"symbol":"BTCUSDT","side":"BUY","type":"LIMIT","timeInForce":"GTC","quantity":"1","price":"68900","newClientOrderId":"my-order-001"} ``` **Generate the string to be signed:** - ``` '1561022985382POST/api/v3/order{"symbol":"BTCUSDT","side":"BUY","type":"LIMIT","timeInForce":"GTC","quantity":"1","price":"68900","newClientOrderId":"my-order-001"}' ``` **Steps to generate the final signature** 1. Encrypt the unsigned string with HMAC SHA256 using your secretKey - Signature = hmac_sha256(secretkey, Message) 2. Encode the signature using Base64 - Signature = base64.encode(Signature) --- ## Document: Spot Transaction Records (USER_DATA) URL: /api-doc/spot/tax/GetSpotAccountRecord # Spot Transaction Records (USER_DATA) - **POST** ```/api/v3/tax/income``` Weight(IP): 5
**Request parameters** | Parameter | Type | Required | Description | |-------------|---------|-----------|--------------------------------------------------------------------------------------------------| | coin | String | No | Filter by asset name (exact match). Example: `USDT`. | | bizType | String | No | Filter by business type. Supported values: `deposit`, `withdraw`, `trade_out`, etc. | | month | String | No | Query month in `YYYY-mm` format, e.g., `2026-01`. Defaults to the current month if not provided. | | limit | Integer | No | Number of records per page. Default: `10`. Maximum: `200`. | | page | Integer | No | Page number (starting from `1`). Default: `1`. |
**Request example** ```powershell curl -X POST "https://api-spot.weex.com/api/v3/tax/income" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "Content-Type: application/json" \ -d '{ "bizType": "trade_out", "limit": 50 }' ```
**Response parameters** Each item in the response array contains: | Field | Type | Description | |---------------|--------|-------------| | billId | String | Bill identifier. | | coinId | Integer| Asset ID. | | coinName | String | Asset symbol. | | bizType | String | Business type. | | fillSize | String | Filled quantity (if applicable). | | fillValue | String | Filled value (if applicable). | | deltaAmount | String | Amount change. | | afterAmount | String | Balance after the change. | | fees | String | Fees charged. | | cTime | String | Creation time (ms). |
**Response example** ```json [ { "billId": "701234567890123456", "coinId": 2, "coinName": "USDT", "bizType": "trade_out", "fillSize": "0.005", "fillValue": "0", "deltaAmount": "-100.00000000", "afterAmount": "900.00000000", "fees": "0.10000000", "cTime": "1764505800123" } ] ```
--- ## Document: Tax URL: /api-doc/spot/tax # Tax --- ## Document: Account Channel URL: /api-doc/spot/Websocket/private/Account-Channel # Account Channel **Description** Streams balance and asset updates (`account`) for the authenticated spot account. Events are pushed when deposits, withdrawals, transfers, or order operations change available balances.
**Subscription Request Parameters** | Field | Type | Required | Description | |:-------|:---------------|:---------|:------------| | method | String | Yes | `SUBSCRIBE` or `UNSUBSCRIBE`. | | params | Array\ | Yes | Use `account`. | | id | Number | Optional | Client-defined identifier echoed in the acknowledgement. |
**Subscription Request Example** ```json { "method": "SUBSCRIBE", "params": [ "account" ], "id": 1 } ```
**Acknowledgement** | Field | Type | Description | |:-------|:--------|:------------| | result | Boolean | `true` when the command succeeds. | | id | Number | Echo of the request id. | | msg | String | Error message when `result` is `false`. |
**Acknowledgement Example** ```json { "result": true, "id": 1 } ```
**Push Payload** | Field | Type | Description | |:------|:-----|:------------| | e | String | Event type, `account`. | | E | Number | Event time in milliseconds. | | v | Number | Account version. | | msgEvent | String | Upstream event name (e.g. `DepositUpdate`, `WithdrawUpdate`, `OrderUpdate`). | | d | Array\ | Asset list describing the latest balances. | | > coin | String | Asset symbol in uppercase. | | > equity | String | Total equity for the asset. | | > available | String | Available balance. | | > frozen | String | Frozen balance. |
**Push Example** ```json { "e": "account", "E": 1773295738123, "v": 1024, "msgEvent": "DepositUpdate", "d": [ { "coin": "USDT", "equity": "1200.00000000", "available": "950.00000000", "frozen": "250.00000000" } ] } ```
--- ## Document: Fill Channel URL: /api-doc/spot/Websocket/private/Fill-Channel # Fill Channel **Description** Streams execution details (`fill`) for orders belonging to the authenticated account.
**Subscription Request Parameters** | Field | Type | Required | Description | |:-------|:---------------|:---------|:------------| | method | String | Yes | `SUBSCRIBE` or `UNSUBSCRIBE`. | | params | Array\ | Yes | Use `fill`. | | id | Number | Optional | Client-defined identifier echoed in the acknowledgement. |
**Subscription Request Example** ```json { "method": "SUBSCRIBE", "params": [ "fill" ], "id": 2 } ```
**Acknowledgement** | Field | Type | Description | |:-------|:--------|:------------| | result | Boolean | `true` when the command succeeds. | | id | Number | Echo of the request id. | | msg | String | Error message when `result` is `false`. |
**Acknowledgement Example** ```json { "result": true, "id": 2 } ```
**Push Payload** | Field | Type | Description | |:------|:-----|:------------| | e | String | Event type, `fill`. | | E | Number | Event time in milliseconds. | | v | Number | Account version. | | msgEvent | String | Upstream event name (for example `OrderUpdate`). | | d | Array\ | Fill entries. | | > id | String | Fill identifier. | | > symbol | String | Trading pair (uppercase). | | > baseCoin | String | Base asset. | | > quoteCoin | String | Quote asset. | | > orderId | String | Related order ID. | | > orderSide | String | `BUY` or `SELL`. | | > fillSize | String | Executed quantity. | | > fillValue | String | Executed value. | | > fillFee | String | Fee charged for this execution. | | > direction | String | Liquidity indicator (`MAKER`, `TAKER`). | | > createdTime | String | Execution time (ms). | | > updatedTime | String | Update time (ms). |
**Push Example** ```json { "e": "fill", "E": 1773295739001, "v": 39, "msgEvent": "OrderUpdate", "d": [ { "id": "7423916138", "symbol": "BTCUSDT", "baseCoin": "BTC", "quoteCoin": "USDT", "orderId": "625138763307155610", "orderSide": "BUY", "fillSize": "0.000952", "fillValue": "99.9676160", "fillFee": "0.00000095", "direction": "TAKER", "createdTime": "1749044695718", "updatedTime": "1749044695718" } ] } ```
--- ## Document: Order Channel URL: /api-doc/spot/Websocket/private/Order-Channel # Order Channel **Description** Streams real-time order lifecycle updates for the authenticated spot account.
**Subscription Request Parameters** | Field | Type | Required | Description | |:-------|:---------------|:---------|:------------| | method | String | Yes | `SUBSCRIBE` or `UNSUBSCRIBE`. | | params | Array\ | Yes | Use `orders`. Only a single private channel may be subscribed per entry. | | id | Number | Optional | Client-provided identifier echoed in the acknowledgement. |
**Subscription Request Example** ```json { "method": "SUBSCRIBE", "params": [ "orders" ], "id": 1 } ```
**Acknowledgement** | Field | Type | Description | |:-------|:--------|:------------| | result | Boolean | `true` when the command succeeds. | | id | Number | Echo of the request id (if provided). | | msg | String | Error information when `result` is `false`. |
**Acknowledgement Example** ```json { "result": true, "id": 1 } ```
**Push Payload** | Field | Type | Description | |:------|:-----|:------------| | e | String | Event type, always `orders`. | | E | Number | Event time in milliseconds. | | v | Number | Account version associated with the update. | | msgEvent | String | Upstream event name (for example `OrderUpdate`). | | d | Array\ | Updated order entries. | | > id | String | Order ID. | | > symbol | String | Trading pair (uppercase, e.g. `BTCUSDT`). | | > baseCoin | String | Base asset. | | > quoteCoin | String | Quote asset. | | > orderSide | String | `BUY` or `SELL`. | | > price | String | Order price. | | > size | String | Order quantity. | | > value | String | Order notional value. | | > clientOrderId | String | Client-specified identifier. | | > type | String | Order type (`LIMIT`, `MARKET`, `STOP`, `TAKE_PROFIT`, etc.). | | > timeInForce | String | `GTC`, `IOC`, `FOK`, or `POST_ONLY`. | | > reduceOnly | Boolean | Whether the order is reduce-only. | | > triggerPrice | String | Trigger price when applicable. | | > orderSource | String | Order source (for example `WEB`, `API`). | | > openTpslParentOrderId | String | Opening order ID for TP/SL orders. | | > setOpenTp | Boolean | Whether take-profit parameters were set. | | > openTpParam | Object | Take-profit configuration (present when `setOpenTp` is true). | | > setOpenSl | Boolean | Whether stop-loss parameters were set. | | > openSlParam | Object | Stop-loss configuration (present when `setOpenSl` is true). | | > takerFeeRate | String | Taker fee rate configured when placing the order. | | > makerFeeRate | String | Maker fee rate configured when placing the order. | | > feeDiscount | String | Fee discount ratio. | | > takerFeeDiscount | String | Taker fee discount ratio. | | > makerFeeDiscount | String | Maker fee discount ratio. | | > status | String | Order status (`NEW`, `PENDING`, `UNTRIGGERED`, `FILLED`, `CANCELED`, etc.). | | > triggerTime | String | Trigger time for conditional orders. | | > triggerPriceTime | String | Trigger price event time. | | > triggerPriceValue | String | Recorded trigger price. | | > cancelReason | String | Cancellation reason (enum label). | | > latestFillPrice | String | Latest fill price. | | > maxFillPrice | String | Maximum fill price. | | > minFillPrice | String | Minimum fill price. | | > cumFillSize | String | Cumulative filled quantity. | | > cumFillValue | String | Cumulative filled value. | | > cumFillFee | String | Cumulative trading fee. | | > createdTime | String | Order creation timestamp (ms). | | > updatedTime | String | Last update timestamp (ms). |
**Push Example** ```json { "e": "orders", "E": 1773295738939, "v": 38, "msgEvent": "OrderUpdate", "d": [ { "id": "625138763307155610", "symbol": "BTCUSDT", "baseCoin": "BTC", "quoteCoin": "USDT", "orderSide": "BUY", "price": "0", "size": "0", "value": "100.0000000", "clientOrderId": "1749044695347g1xrdKa2xuDzbDHgTTkbu", "type": "MARKET", "timeInForce": "IOC", "reduceOnly": false, "triggerPrice": "0", "orderSource": "API", "openTpslParentOrderId": "0", "setOpenTp": false, "setOpenSl": false, "takerFeeRate": "0.001", "makerFeeRate": "0", "feeDiscount": "1", "takerFeeDiscount": "1", "makerFeeDiscount": "1", "status": "FILLED", "triggerTime": "0", "triggerPriceTime": "0", "triggerPriceValue": "0", "cancelReason": "UNKNOWN_ORDER_CANCEL_REASON", "latestFillPrice": "105008.0", "maxFillPrice": "105008.0", "minFillPrice": "105008.0", "cumFillSize": "0.000952", "cumFillValue": "99.9676160", "cumFillFee": "0.00000095", "createdTime": "1749044695689", "updatedTime": "1749044695720" } ] } ```
--- ## Document: Book Ticker Channel URL: /api-doc/spot/Websocket/public/BookTicker-Channel # Book Ticker Channel **Description** Streams best bid/ask quotes for a symbol. Messages are pushed whenever the top of book changes.
**Subscription Request Parameters** | Field | Type | Required | Description | |:-------|:---------------|:---------|:------------| | method | String | Yes | Use `SUBSCRIBE` to add, `UNSUBSCRIBE` to remove subscriptions. | | params | Array\ | Yes | Each entry uses the format `@bookTicker`, e.g. `BTCUSDT@bookTicker`. | | id | Number | Optional | Client-defined identifier echoed in the acknowledgement. |
**Subscription Request Example** ```json { "method": "SUBSCRIBE", "params": [ "BTCUSDT@bookTicker" ], "id": 1 } ```
**Acknowledgement** | Field | Type | Description | |:-------|:--------|:------------| | result | Boolean | `true` for success, `false` for failure. | | id | Number | Echo of the request id (if provided). | | msg | String | Error message when `result` is `false`. |
**Acknowledgement Example** ```json { "result": true, "id": 1 } ```
**Push Payload** | Field | Type | Description | |:------|:-----|:------------| | e | String | Event type, `bookTicker`. | | E | Number | Event time in milliseconds. | | s | String | Trading pair in uppercase (e.g. `BTCUSDT`). | | d | Object | Best bid/ask snapshot. | | > u | Number | Order book update ID. | | > b | String | Best bid price. | | > B | String | Best bid quantity. | | > a | String | Best ask price. | | > A | String | Best ask quantity. |
**Push Example** ```json { "e": "bookTicker", "E": 1672515782136, "s": "BNBUSDT", "d": { "u": 400900217, "b": "25.35190000", "B": "31.21000000", "a": "25.36520000", "A": "40.66000000" } } ```
--- ## Document: Candlestick Channel URL: /api-doc/spot/Websocket/public/Candlesticks-Channel # Candlestick Channel **Description** Streams candlestick (K-line) data for the requested symbol. Each update contains the latest bar for the specified interval and price type.
**Subscription Request Parameters** | Field | Type | Required | Description | |:-------|:---------------|:---------|:------------| | method | String | Yes | `SUBSCRIBE` or `UNSUBSCRIBE`. | | params | Array\ | Yes | `@kline__`, e.g. `BTCUSDT@kline_1m_LAST_PRICE`. | | id | Number | Optional | Client identifier echoed in the acknowledgement. | **Interval Tokens** | Token | Description | |:------|:------------| | 1m | 1 minute | | 5m | 5 minutes | | 15m | 15 minutes | | 30m | 30 minutes | | 1h | 1 hour | | 2h | 2 hours | | 4h | 4 hours | | 6h | 6 hours | | 8h | 8 hours | | 12h | 12 hours | | 1d | 1 day | | 1w | 1 week | | 1M | 1 calendar month (uppercase `M`). | **Price Types** | Token | Description | |:------|:------------| | LAST_PRICE | Last trade price candles. | | MARK_PRICE | Mark price candles. |
**Subscription Request Example** ```json { "method": "SUBSCRIBE", "params": [ "ETHUSDT@kline_1m_LAST_PRICE" ], "id": 4 } ```
**Acknowledgement** | Field | Type | Description | |:-------|:--------|:------------| | result | Boolean | `true` when the operation succeeds. | | id | Number | Echo of the request id. | | msg | String | Error details when `result` is `false`. |
**Acknowledgement Example** ```json { "result": true, "id": 4 } ```
**Update Payload (`kline`)** | Field | Type | Description | |:------|:-----|:------------| | e | String | Event type, `kline`. | | E | Number | Event time (milliseconds). | | s | String | Trading pair (e.g. `ETHUSDT`). | | p | String | Price type (`LAST_PRICE`, `MARK_PRICE`). | | d | Array\ | Candlestick entries (typically the most recent bar). | | > t | Number | Bar start time (milliseconds). | | > T | Number | Bar close time (milliseconds). | | > s | String | Trading pair. | | > i | String | Interval token exactly as subscribed (e.g. `1m`). | | > o | String | Open price. | | > c | String | Close price. | | > h | String | High price. | | > l | String | Low price. | | > v | String | Volume (base asset). | | > n | Number | Number of trades. | | > q | String | Quote asset volume. | | > V | String | Taker buy volume. | | > Q | String | Taker buy quote volume. |
**Update Example** ```json { "e": "kline", "E": 1773295738000, "s": "ETHUSDT", "p": "LAST_PRICE", "d": [ { "t": 1773295680000, "T": 1773295739999, "s": "ETHUSDT", "i": "1m", "o": "3572.10", "c": "3573.40", "h": "3574.00", "l": "3571.80", "v": "18.2", "n": 9, "q": "65035.88", "V": "9.4", "Q": "33590.96" } ] } ```
> **Interval tokens are case-sensitive.** `1m` (minutes) and `1M` (months) represent different bars. --- ## Document: Depth Channel URL: /api-doc/spot/Websocket/public/Depth-Channel # Depth Channel **Description** Streams order book depth changes (`depth`) for the requested trading pair and aggregation level. A snapshot is delivered automatically after subscribing, followed by incremental updates.
**Subscription Request Parameters** | Field | Type | Required | Description | |:-------|:---------------|:---------|:------------| | method | String | Yes | `SUBSCRIBE` to add, `UNSUBSCRIBE` to remove. | | params | Array\ | Yes | `@depth{level}`. Supported levels: `15`, `200`. Example: `BTCUSDT@depth15`. | | id | Number | Optional | Client-defined identifier echoed in the acknowledgement. |
**Subscription Request Example** ```json { "method": "SUBSCRIBE", "params": [ "BTCUSDT@depth15" ], "id": 2 } ```
**Acknowledgement** | Field | Type | Description | |:-------|:--------|:------------| | result | Boolean | `true` for success, `false` for failure. | | id | Number | Echo of the request id. | | msg | String | Error details when `result` is `false`. |
**Acknowledgement Example** ```json { "result": true, "id": 2 } ```
**Update Payload (`depth`)** | Field | Type | Description | |:------|:-----|:------------| | e | String | Event type, `depth`. | | E | Number | Event time in milliseconds. | | s | String | Trading pair (uppercase, e.g. `BTCUSDT`). | | U | Number | First update ID in this message. | | u | Number | Last update ID in this message. | | l | Number | Depth level (`15` or `200`). | | d | String | Depth type (`SNAPSHOT` on the initial response, `CHANGED` afterwards). | | b | Array\> | Bid updates in `[price, size]` format. | | a | Array\> | Ask updates in `[price, size]` format. | | f | String | Merge factor (only present when merged depths are enabled). |
**Update Example** ```json { "e": "depth", "E": 1773295701456, "s": "BTCUSDT", "U": 161, "u": 161, "l": 15, "d": "CHANGED", "b": [ ["103435.90", "2.10000"] ], "a": [ ["103436.10", "1.21500"] ] } ```
> **Processing tip:** Consume update IDs sequentially (`U` through `u`). If an update is missed, resubscribe to obtain a fresh snapshot. --- ## Document: Market Channel URL: /api-doc/spot/Websocket/public/Tickers-Channel # Market Channel **Description** Streams 24‑hour ticker statistics for a symbol, including last price, price change, weighted averages, and top-of-book quotes. Updates are pushed whenever upstream metrics change (typically within 100‑300 ms).
**Subscription Request Parameters** | Field | Type | Required | Description | |:-------|:---------------|:---------|:------------| | method | String | Yes | Use `SUBSCRIBE` to add, `UNSUBSCRIBE` to remove subscriptions. | | params | Array\ | Yes | Each entry uses the format `@ticker`, e.g. `BTCUSDT@ticker`. | | id | Number | Optional | Client-defined identifier echoed in the acknowledgement. |
**Subscription Request Example** ```json { "method": "SUBSCRIBE", "params": [ "BTCUSDT@ticker" ], "id": 1 } ```
**Acknowledgement** | Field | Type | Description | |:-------|:--------|:------------| | result | Boolean | `true` for success, `false` for failure. | | id | Number | Echo of the request id (if provided). | | msg | String | Error message when `result` is `false`. |
**Acknowledgement Example** ```json { "result": true, "id": 1 } ```
**Push Payload** | Field | Type | Description | |:------|:-----|:------------| | e | String | Event type, `24hrTicker`. | | E | Number | Event time in milliseconds. | | s | String | Trading pair in uppercase (e.g. `BTCUSDT`). | | d | Object | 24‑hour statistics. | | > p | String | Absolute price change in the last 24 hours. | | > P | String | Percentage price change in the last 24 hours. | | > w | String | 24‑hour weighted average price. | | > x | String | Last price 24 hours ago. | | > c | String | Latest traded price. | | > Q | String | Quantity of the latest trade. | | > b | String | Best bid price. | | > B | String | Best bid quantity. | | > a | String | Best ask price. | | > A | String | Best ask quantity. | | > o | String | Opening price 24 hours ago. | | > h | String | Highest price in the last 24 hours. | | > l | String | Lowest price in the last 24 hours. | | > v | String | 24‑hour trading volume (base asset). | | > q | String | 24‑hour trading value (quote asset). | | > O | Number | Window start time in milliseconds. | | > C | Number | Window end time in milliseconds. | | > F | Number | First trade ID in the window. | | > L | Number | Last trade ID in the window. | | > n | Number | Total trade count in the window. |
**Push Example** ```json { "e": "24hrTicker", "E": 1672515782136, "s": "BNBUSDT", "d": { "p": "0.0015", "P": "250.00", "w": "0.0018", "x": "0.0009", "c": "0.0025", "Q": "10", "b": "0.0024", "B": "10", "a": "0.0026", "A": "100", "o": "0.0010", "h": "0.0025", "l": "0.0010", "v": "10000", "q": "18", "O": 1672515782136, "C": 1675216573749, "F": 0, "L": 18150, "n": 18151 } } ```
--- ## Document: Public Trade Channel URL: /api-doc/spot/Websocket/public/Trades-Channel # Public Trade Channel **Description** Streams taker trades for the subscribed symbol. Each `trade` update represents one or more recent executions.
**Subscription Request Parameters** | Field | Type | Required | Description | |:-------|:---------------|:---------|:------------| | method | String | Yes | `SUBSCRIBE` or `UNSUBSCRIBE`. | | params | Array\ | Yes | `@trade`, e.g. `BTCUSDT@trade`. | | id | Number | Optional | Client identifier echoed in the acknowledgement. |
**Subscription Request Example** ```json { "method": "SUBSCRIBE", "params": [ "BTCUSDT@trade" ], "id": 3 } ```
**Acknowledgement** | Field | Type | Description | |:-------|:--------|:------------| | result | Boolean | `true` when the subscription succeeds. | | id | Number | Echo of the request id. | | msg | String | Error message when `result` is `false`. |
**Acknowledgement Example** ```json { "result": true, "id": 3 } ```
**Update Payload (`trade`)** | Field | Type | Description | |:------|:-----|:------------| | e | String | Event type, `trade`. | | E | Number | Event time in milliseconds. | | s | String | Trading pair (uppercase). | | d | Array\ | Trade entries. | | > T | Number | Trade execution time (milliseconds). | | > t | Number | Trade ID. | | > p | String | Trade price. | | > q | String | Trade quantity. | | > v | String | Trade value (price × quantity). | | > m | Boolean | `true` if the trade was an aggressive sell (maker is the buyer). |
**Update Example** ```json { "e": "trade", "E": 1773295739001, "s": "BTCUSDT", "d": [ { "T": 1773295739001, "t": 7423916138, "p": "69382.20", "q": "0.014", "v": "971.3508", "m": false } ] } ```
> Reconnect and resubscribe if update IDs (`t`) are observed out of order or skipped beyond the exchange tolerance window. --- ## Document: Overview URL: /api-doc/spot/Websocket/websocket-intro # Overview WebSocket is a new protocol in HTML5 that enables full-duplex communication between clients and servers, allowing rapid bidirectional data transmission. Through a simple handshake, a connection can be established between client and server, enabling the server to actively push information to the client based on business rules. Its advantages include: - Small header size (~2 bytes) during data transmission between client and server - Both client and server can actively send data - Eliminates the need for repeated TCP connection setup/teardown, conserving bandwidth and server resources - Strongly recommended for developers to obtain market data, order book depth, and other information | Domain | WebSocket API | Recommended Use | |-----------------|--------------------------------------|----------------------------------| | Public Channel | wss://ws-spot.weex.com/v3/ws/public | Primary domain, public channels | | Private Channel | wss://ws-spot.weex.com/v3/ws/private | Primary domain, private channels | ## Connection Connection Specifications: - Connection limit: 300 connection requests/IP/5 minutes, maximum 20 concurrent connections per IP - Subscription limit: 240 operations/hour/connection, maximum 100 channels per connection - Public channel requirement: Public channel connections require header authentication(User-Agent) - Private channel requirement: Private channel connections require header authentication - To maintain stable and effective connections, we recommend: - After successful WebSocket connection establishment, the server will periodically send Ping messages to the client. Public channels use the format: `{"event":"ping","time":"1693208170000"}`, while private channels use the format: `{"type":"ping","time":"1693208170000"}`. In both formats, "time" represents the server's timestamp. Upon receiving either message, the client should respond with the same Pong message: `{"method":"PONG","id":1}`. The server will actively terminate connections that fail to respond more than 10 times. ## Header Authentication for Private Channels **User-Agent**:Client identification **ACCESS-KEY**: Unique identifier for API user authentication (requires application) **ACCESS-PASSPHRASE**: Password for the API Key **ACCESS-TIMESTAMP**: Unix Epoch timestamp in milliseconds (expires after 30 seconds, must match signature timestamp) **ACCESS-SIGN**: Signature string generated as follows: The message (string to be signed) consists of: timestamp + requestPath Example timestamp (in milliseconds): `const timestamp = '' + Date.now()` Where requestPath is `/v3/ws/private` **Signature Generation Process** 1. Encrypt the message string using HMAC SHA256 with the secret key: - Signature = hmac_sha256(secretkey, Message) 2. Encode the Signature using Base64: - Signature = base64.encode(Signature) ## Subscription Subscription Specification: ```json { "method": "SUBSCRIBE", "params": ["BTCUSDT@ticker", "BTCUSDT@depth15"], "id": 1 } ``` ## Unsubscription Unsubscription Specification: ```json { "result": true, "id": 1 } ``` --- ## Document: Adjust Isolated Margin (TRADE) URL: /api-doc/contract/Account_API/AdjustPositionMarginTRADE # Adjust Isolated Margin (TRADE) - **POST** ```/capi/v3/account/positionMargin``` Weight(IP): 15
**Request parameters** | Parameter | Type | Required? | Description | |--------------------|--------|-----------|-------------------------------------------------------------------------------------------------------| | isolatedPositionId | Long | Yes | Isolated position ID. Obtain via [Get Single Position](/api-doc/contract/Account_API/GetSinglePosition). | | amount | String | Yes | Margin amount to adjust. Must be greater than 0. | | type | Integer| Yes | Adjustment direction. `1` = increase isolated margin; `2` = decrease isolated margin. |
**Request example** ```powershell curl -X POST "https://api-contract.weex.com/capi/v3/account/positionMargin" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "Content-Type: application/json" \ -d '{"isolatedPositionId":689987235755328154,"amount":"10","type":1}' ```
**Response parameters** | Parameter | Type | Description | |--------------|--------|------------------------------------------| | code | String | Response code | | msg | String | Response message | | requestTime | Long | Timestamp
Unix millisecond timestamp |
**Response example** ```json { "code": "200", "msg": "success", "requestTime": 1764505776347 } ```
--- ## Document: Change Margin Mode (TRADE) URL: /api-doc/contract/Account_API/ChangeMarginModeTRADE # Change Margin Mode (TRADE) - **POST** ```/capi/v3/account/marginType``` Weight(IP): 20
**Request parameters** | Parameter | Type | Required? | Description | |---------------|--------|-----------|---------------------------------------------------------------------------------------------------------| | symbol | String | Yes | Trading pair | | marginType | String | Yes | Margin mode.
Supported values: CROSSED (cross margin), ISOLATED (isolated margin). | | separatedType | String | No | Position mode.
COMBINED keeps both long and short in one position.
SEPARATED splits positions. |
**Request example** ```powershell curl -X POST "https://api-contract.weex.com/capi/v3/account/marginType" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "Content-Type: application/json" \ -d '{"symbol":"BTCUSDT","marginType":"ISOLATED","separatedType":"COMBINED"}' ```
**Response parameters** | Parameter | Type | Description | |--------------|--------|------------------------------------------| | code | String | Response code | | msg | String | Response message | | requestTime | Long | Timestamp
Unix millisecond timestamp |
**Response example** ```json { "code": "200", "msg": "success", "requestTime": 1764505776347 } ```
--- ## Document: Get Account Balance (USER_DATA) URL: /api-doc/contract/Account_API/GetAccountBalance # Get Account Balance (USER_DATA) - **GET** ```/capi/v3/account/balance``` Weight(IP): 5
**Request parameters** NONE
**Request example** ```powershell curl "https://api-contract.weex.com/capi/v3/account/balance" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "Content-Type: application/json" ```
**Response parameters** | Parameter | Type | Description | |:-----------------|:-------|:-------------------------| | asset | String | Asset name | | balance | String | Total balance | | availableBalance | String | Available balance | | frozen | String | Frozen amount | | unrealizePnl | String | Unrealized Profit and Loss |
**Response example** ```json [ { "asset": "USDT", "balance": "5696.49288823", "availableBalance": "5413.06877369", "frozen": "81.28240000", "unrealizePnl": "-34.55300000" } ] ```
--- ## Document: Get Account Configuration (USER_DATA) URL: /api-doc/contract/Account_API/GetAccountConfig # Get Account Configuration (USER_DATA) - **GET** ```/capi/v3/account/accountConfig``` Weight(IP): 5
**Request parameters** NONE
**Request example** ```powershell curl "https://api-contract.weex.com/capi/v3/account/accountConfig" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "Content-Type: application/json" ```
**Response parameters** | Parameter | Type | Description | |:-----------------|:--------|:----------------------------------------------------------------------------------------------------------------| | canTrade | Boolean | Whether trading is enabled | | canDeposit | Boolean | Whether deposits are enabled | | canWithdraw | Boolean | Whether withdrawals are enabled | | dualSidePosition | Boolean | Whether dual-side position mode is enabled
true: Can hold both long and short positions simultaneously
false: One-way position mode | | updateTime | Long | Update time
Unix millisecond timestamp |
**Response example** ```json { "canTrade": true, "canDeposit": true, "canWithdraw": true, "dualSidePosition": true, "updateTime": 1713339011237 } ```
--- ## Document: Get All Positions (USER_DATA) URL: /api-doc/contract/Account_API/GetAllPositions # Get All Positions (USER_DATA) - **GET** ```/capi/v3/account/position/allPosition``` Weight(IP): 10
**Request parameters** NONE
**Request example** ```powershell curl "https://api-contract.weex.com/capi/v3/account/position/allPosition" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "Content-Type: application/json" ```
**Response parameters** | Parameter | Type | Description | |----------------------------|---------|----------------------------------------------------------------------------------------------------------------------------------------| | id | Long | Position ID | | asset | String | Associated collateral asset | | symbol | String | Trading pair | | side | String | Position direction such as LONG or SHORT | | marginType | String | Margin mode of current position
CROSSED: Cross Mode
ISOLATED: Isolated Mode | | separatedMode | String | Current position's separated mode
COMBINED: Combined mode
SEPARATED: Separated mode | | separatedOpenOrderId | Long | Opening order ID of separated position | | leverage | String | Position leverage | | size | String | Current position size | | openValue | String | Initial value at position opening | | openFee | String | Opening fee | | fundingFee | String | Funding fee | | marginSize | String | Margin amount (margin coin) | | isolatedMargin | String | Isolated margin | | isAutoAppendIsolatedMargin | Boolean | Whether the auto-adding of funds for the isolated margin is enabled (only for isolated mode) | | cumOpenSize | String | Accumulated opened positions | | cumOpenValue | String | Accumulated value of opened positions | | cumOpenFee | String | Accumulated fees paid for opened positions | | cumCloseSize | String | Accumulated closed positions | | cumCloseValue | String | Accumulated value of closed positions | | cumCloseFee | String | Accumulated fees paid for closing positions | | cumFundingFee | String | Accumulated settled funding fees | | cumLiquidateFee | String | Accumulated liquidation fees | | createdMatchSequenceId | Long | Matching engine sequence ID at creation | | updatedMatchSequenceId | Long | Matching engine sequence ID at last update | | createdTime | Long | Creation time
Unix millisecond timestamp | | updatedTime | Long | Update time
Unix millisecond timestamp | | unrealizePnl | String | Unrealized PnL | | liquidatePrice | String | Estimated liquidation price
If the value = 0, it means the position is at low risk and there is no liquidation price at this time |
**Response example** ```json [ { "id": 689987235755328154, "asset": "USDT", "symbol": "BTCUSDT", "side": "LONG", "marginType": "CROSSED", "separatedMode": "COMBINED", "separatedOpenOrderId": 0, "leverage": "100", "size": "0.020000", "openValue": "1801.0670000", "openFee": "0.70731060", "fundingFee": "1.22618160", "marginSize": "17.154980", "isolatedMargin": "0", "isAutoAppendIsolatedMargin": false, "cumOpenSize": "0.020000", "cumOpenValue": "1801.0670000", "cumOpenFee": "0.70731060", "cumCloseSize": "0", "cumCloseValue": "0", "cumCloseFee": "0", "cumFundingFee": "1.22618160", "cumLiquidateFee": "0", "createdMatchSequenceId": 7027745116, "updatedMatchSequenceId": 7040274110, "createdTime": 1764505776347, "updatedTime": 1764588886461, "unrealizePnl": "-85.5690000", "liquidatePrice": "0" } ] ```
--- ## Document: Get Commission Rate (USER_DATA) URL: /api-doc/contract/Account_API/GetCommissionRate # Get Commission Rate (USER_DATA) - **GET** ```/capi/v3/account/commissionRate``` Weight(IP): 5
**Request parameters** | Parameter | Type | Required? | Description | |-----------|--------|-----------|--------------| | symbol | String | Yes | Trading pair |
**Request example** ```powershell curl "https://api-contract.weex.com/capi/v3/account/commissionRate?symbol=BTCUSDT" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "Content-Type: application/json" ```
**Response parameters** | Parameter | Type | Description | |:-------------------|:-------|:-----------------------------------------------| | symbol | String | Trading pair | | makerCommissionRate | String | Maker commission rate applicable to orders manually placed by the current user, e.g. "0.0002" means 0.02% | | takerCommissionRate | String | Taker commission rate applicable to orders manually placed by the current user, e.g. "0.0004" means 0.04% | | apiMakerCommissionRate | String | Maker commission rate applicable to orders placed via API by the current user, e.g. "0.0002" means 0.02% | | apiTakerCommissionRate | String | Taker commission rate applicable to orders placed via API by the current user, e.g. "0.0004" means 0.04% |
**Response example** ```json { "symbol": "BTCUSDT", "makerCommissionRate": "0.0002", "takerCommissionRate": "0.0004", "apiMakerCommissionRate": "0.0002", "apiTakerCommissionRate": "0.0004" } ```
--- ## Document: Get Account Income (USER_DATA) URL: /api-doc/contract/Account_API/GetContractBills # Get Account Income (USER_DATA) **HTTP request** Get Account Income History - **POST** ```/capi/v3/account/income``` Weight(IP): 2
**Request parameters** | Parameter | Type | Required? | Description | |:--------------|:--------|:-------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | asset | String | No | Asset name | | symbol | String | No | Trading pair | | incomeType | String | No | Business type
deposit : Deposit
withdraw : Withdrawal
transfer_in : Transfer between different accounts (in)
transfer_out : Transfer between different accounts (out)
margin_move_in : Collateral transferred within the same account due to opening/closing positions, manual/auto addition
margin_move_out : Collateral transferred out within the same account due to opening/closing positions, manual/auto addition
position_open_long : Collateral change from opening long positions (buying decreases collateral)
position_open_short : Collateral change from opening short positions (selling increases collateral)
position_close_long : Collateral change from closing long positions (selling increases collateral)
position_close_short : Collateral change from closing short positions (buying decreases collateral)
position_funding : Collateral change from position funding fee settlement
order_fill_fee_income : Order fill fee income (specific to fee account)
order_liquidate_fee_income : Order liquidation fee income (specific to fee account)
start_liquidate : Start liquidation
finish_liquidate : Finish liquidation
order_fix_margin_amount : Compensation for liquidation loss
tracking_follow_pay : Copy trading payment, pre-deducted from followers after position closing if profitable
tracking_system_pre_receive : Pre-received commission, commission system account receives pre-deducted amount from followers
tracking_follow_back : Copy trading commission refund
tracking_trader_income : Lead trader income
tracking_third_party_share : Profit sharing (shared by lead trader with others) | | startTime | Long | No | Start timestamp
Unit: milliseconds.
If only `endTime` is provided, the system defaults `startTime` to 30 days before `endTime` (not earlier than current time). | | endTime | Long | No | End timestamp
Unit: milliseconds.
If only `startTime` is provided, `endTime` defaults to the current time.
When both are provided, the range must not exceed 100 days. | | limit | Integer | No | Return record limit, default: 20
Minimum: 1
Maximum: 100 | | nextKeyId | Long | No | Cursor ID returned from the previous page. | | nextKeyTime | Long | No | Cursor time returned from the previous page. |
**Request example** ```powershell curl -X POST "https://api-contract.weex.com/capi/v3/account/income" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "Content-Type: application/json" \ -d '{ "asset": "", "symbol": "", "incomeType": "", "startTime": null, "endTime": null, "limit": 10, "nextKeyId": null, "nextKeyTime": null}' ```
**Response parameters** | Parameter | Type | Description | |:---------------|:--------|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | hasNextPage | Boolean | Whether there is a next page | | nextKey | Object | Cursor for the next page. | | nextKey.nextKeyId | Long | Cursor ID. | | nextKey.nextKeyTime | Long | Cursor time in milliseconds. | | items | Array | Data list | | > billId | Long | Bill ID | | > asset | String | Asset name | | > symbol | String | Trading pair | | > income | String | Amount | | > incomeType | String | Income type | | > balance | String | Balance | | > fillFee | String | Transaction fee | | > time | Long | Creation time
Unix millisecond timestamp | | > transferReason | String | Transfer Reason
UNKNOWN_TRANSFER_REASON: Unknown transfer reason
USER_TRANSFER: User manual transfer
INCREASE_CONTRACT_CASH_GIFT: Increase contract cash gift
REDUCE_CONTRACT_CASH_GIFT: Reduce contract cash gift
REFUND_WXB_DISCOUNT_FEE: Refund WXB discount fee |
**Response example** ```json { "hasNextPage": true, "nextKey": { "nextKeyId": 686960019383517338, "nextKeyTime": 1763784031721 }, "items": [ { "billId": 686960019383517338, "asset": "USDT", "symbol": "BTCUSDT", "income": "0.08266646", "incomeType": "position_funding", "balance": "4738.70667369", "fillFee": "0", "time": 1763784031721, "transferReason": "UNKNOWN_TRANSFER_REASON" } ] } ```
--- ## Document: Get Single Position (USER_DATA) URL: /api-doc/contract/Account_API/GetSinglePosition # Get Single Position (USER_DATA) - **GET** ```/capi/v3/account/position/singlePosition``` Weight(IP): 2
**Request parameters** | Parameter | Type | Required? | Description | |-----------|--------|-----------|--------------| | symbol | String | Yes | Trading pair |
**Request example** ```powershell curl "https://api-contract.weex.com/capi/v3/account/position/singlePosition?symbol=BTCUSDT" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "Content-Type: application/json" ```
**Response parameters** Equivalent to [Get All Positions](/api-doc/contract/Account_API/GetAllPositions).
**Response example** ```json [ { "id": 689987235755328154, "asset": "USDT", "symbol": "BTCUSDT", "side": "LONG", "marginType": "CROSSED", "separatedMode": "COMBINED", "separatedOpenOrderId": 0, "leverage": "100", "size": "0.020000", "openValue": "1801.0670000", "openFee": "0.70731060", "fundingFee": "1.22618160", "marginSize": "17.154980", "isolatedMargin": "0", "isAutoAppendIsolatedMargin": false, "cumOpenSize": "0.020000", "cumOpenValue": "1801.0670000", "cumOpenFee": "0.70731060", "cumCloseSize": "0", "cumCloseValue": "0", "cumCloseFee": "0", "cumFundingFee": "1.22618160", "cumLiquidateFee": "0", "createdMatchSequenceId": 7027745116, "updatedMatchSequenceId": 7040274110, "createdTime": 1764505776347, "updatedTime": 1764588886461, "unrealizePnl": "-85.5690000", "liquidatePrice": "0" } ] ```
--- ## Document: Get Symbol Configuration (USER_DATA) URL: /api-doc/contract/Account_API/GetSymbolConfig # Get Symbol Configuration (USER_DATA) - **GET** ```/capi/v3/account/symbolConfig``` Weight(IP): 5
**Request parameters** | Parameter | Type | Required? | Description | |-----------|--------|-----------|-------------------------------------------------------------| | symbol | String | No | Trading pair
If not provided, all will be returned by default |
**Request example** ```powershell curl "https://api-contract.weex.com/capi/v3/account/symbolConfig?symbol=BTCUSDT" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "Content-Type: application/json" ```
**Response parameters** | Parameter | Type | Description | |:---------------------|:-------|:-------------------------------------------------------------------------------------------------| | symbol | String | Trading pair | | marginType | String | Margin mode
CROSSED: Cross Mode
ISOLATED: Isolated Mode | | separatedType | String | Position segregation mode
COMBINED: Combined mode
SEPARATED: Separated mode | | crossLeverage | String | Cross margin leverage | | isolatedLongLeverage | String | Isolated long position leverage | | isolatedShortLeverage| String | Isolated short position leverage |
**Response example** ```json [ { "symbol": "BTCUSDT", "marginType": "CROSSED", "separatedType": "COMBINED", "crossLeverage": "20", "isolatedLongLeverage": "20", "isolatedShortLeverage": "20" } ] ```
--- ## Document: Account URL: /api-doc/contract/Account_API # Account --- ## Document: Modify Auto-Append Margin (TRADE) URL: /api-doc/contract/Account_API/ModifyAutoAppendMarginTRADE # Modify Auto-Append Margin (TRADE) - **POST** ```/capi/v3/account/modifyAutoAppendMargin``` Weight(IP): 15
**Request parameters** | Parameter | Type | Required? | Description | |------------------|---------|-----------|--------------------------------------------------------| | positionId | Long | Yes | Isolated position ID | | autoAppendMargin | Boolean | Yes | Whether to enable automatic isolated margin top-up |
**Request example** ```powershell curl -X POST "https://api-contract.weex.com/capi/v3/account/modifyAutoAppendMargin" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "Content-Type: application/json" \ -d '{"positionId":689987235755328154,"autoAppendMargin":false}' ```
**Response parameters** | Parameter | Type | Description | |--------------|--------|------------------------------------------| | code | String | Response code | | msg | String | Response message | | requestTime | Long | Timestamp
Unix millisecond timestamp |
**Response example** ```json { "code": "200", "msg": "success", "requestTime": 1764505776347 } ```
--- ## Document: Update Leverage Settings (TRADE) URL: /api-doc/contract/Account_API/UpdateLeverageTRADE # Update Leverage Settings (TRADE) - **POST** ```/capi/v3/account/leverage``` Weight(IP): 10
**Request parameters** | Parameter | Type | Required? | Description | |------------------------|--------|-----------|---------------------------------------------------------------------------------------------------------------------------------------------| | symbol | String | Yes | Trading pair | | marginType | String | No | Target margin mode.
Supported values: CROSSED (cross margin), ISOLATED (isolated margin). | | crossLeverage | String | No | Cross leverage to apply when marginType is CROSSED. | | isolatedLongLeverage | String | No | Isolated long leverage. Required when updating the isolated long position. | | isolatedShortLeverage | String | No | Isolated short leverage. Required when updating the isolated short position. |
At least one of `crossLeverage`, `isolatedLongLeverage`, or `isolatedShortLeverage` must be provided.
**Request example** ```powershell curl -X POST "https://api-contract.weex.com/capi/v3/account/leverage" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "Content-Type: application/json" \ -d '{"symbol":"BTCUSDT","marginType":"ISOLATED","isolatedLongLeverage":"20","isolatedShortLeverage":"20"}' ```
**Response parameters** | Parameter | Type | Description | |------------------------|--------|-----------------------------------------------------------------| | symbol | String | Trading pair | | marginType | String | Applied margin mode
CROSSED or ISOLATED | | crossLeverage | String | Resulting cross leverage | | isolatedLongLeverage | String | Resulting isolated long leverage | | isolatedShortLeverage | String | Resulting isolated short leverage |
**Response example** ```json { "symbol": "BTCUSDT", "marginType": "ISOLATED", "crossLeverage": "0", "isolatedLongLeverage": "20", "isolatedShortLeverage": "20" } ```
--- ## Document: llms.txt URL: /api-doc/contract/AIResources/llms-txt # llms.txt --- ## Document: FAQs URL: /api-doc/contract/apifaq # FAQs > **Last Updated:** 2026-04-14
> **Document Summary:** This guide is designed to assist developers in quickly integrating the WEEX Futures API, addressing common technical issues regarding permission configurations, rate limits, and trading processes. --- ## 1. Account & Permission Configuration ### API Key Permission Types When creating an API Key, please check the corresponding permission options based on your business needs: | Permission | Description | Use Case | |:-------------|:----------------------------------------------------------------------------------------------------------------------------------------------|:-----------------------------------------------------| | **Readonly** | **Read-only permission**. Only allows calling query-based endpoints (e.g., balance, positions, trade history). No trading operations allowed. | Asset monitoring, ledger syncing, market analysis. | | **Futures** | **Futures trading permission**. Allows opening/closing positions, setting TP/SL, and querying positions in Futures markets. | Futures hedging, high-frequency contract strategies. | **Note: These permissions are independent. If you need Futures trading operations, ensure the Futures permission is checked.** ### Why is my API permission disabled or returning an "API Restricted" error? * **Risk Control Trigger:** If the account triggers platform security risk controls (e.g., suspicious logins, high-frequency invalid requests), API permissions may be automatically disabled. * **Reactivation Process:** Please contact Customer Support. * **Effective Time:** Newly created or modified API Keys usually take approximately **15 minutes** to propagate globally across the system. ### Security Recommendations for Creating API Keys * **Passphrase:** When setting your API Passphrase, **do not include special characters** (alphanumeric only). * **IP Whitelist:** It is highly recommended to enable an IP Whitelist to enhance security. --- ## 2. Rate Limits WEEX imposes strict weight limits on different types of interfaces to ensure system stability. If limits are exceeded, the system will return an `HTTP 429` error. | Business Type | Operation Type | Rate Limit | |:-----------------------|:--------------------|:-----------------------------| | **Futures Trading** | Place Order | 300 times / min | | **Network Connection** | REST | 500 weight / 10 sec / per IP | | **WebSocket** | Maximum Connections | 20 connections / per IP | --- ## 3. Paper Trading Interface (NEW) To facilitate strategy debugging and hedge mode testing, WEEX has officially launched **Paper Trading endpoints**. You can fully simulate the trading process without consuming real assets. ### New Demo Endpoints: * **Get Account Balance**: View simulated funds (SUSDT).
`GET /capi/v3/sim/balance` * **Get All Positions**: Supports viewing long/short dual-direction (Hedge Mode) positions.
`GET /capi/v3/sim/position/allPosition` * **Place Order**: Supports Market, Limit, and other order types.
`POST /capi/v3/sim/order` * **Get Order History**: Track and analyze historical simulated trade records.
`GET /capi/v3/sim/order/history` --- ## 4. Technical Q&A ### Q1: Why does placing an order return `-1052` (Insufficient permissions)? **A:** This error is usually caused by: 1. **Permission Check:** The "Futures" trading permission was not checked in the API management page. 2. **Unsupported Trading Pair:** Certain contracts may not support API trading yet. 3. **Interface Version:** It is recommended to use **V3 interfaces**, as V1/V2 are being deprecated. ### Q2: Why does the WebSocket connection return a 403 error? **A:** When establishing a WebSocket connection, you **must include `User-Agent` info in the Header** (content can be custom). If this field is missing, the request will be blocked by the firewall. ### Q3: Why does canceling an order return `-1054`? **A:** Order does not exist. This is typically due to providing an incorrect order ID during the cancellation request. ### Q4: How do I get all tradable symbols? **A:** Visit [Get Futures Trading Symbols Interface](/api-doc/contract/Market_API/GetApiTradingSymbols). ### Q5: Why am I getting a 404 error? **A:** Check your path. For example, to get all positions, use `GET /capi/v3/account/position/allPosition`. ### Q6: Does changing leverage trigger a WebSocket push? **A:** Yes. Only placing orders, closing positions, and adjusting margin will trigger updates. ### Q7: Are TradingView or FIX API supported? **A:** Currently, neither is supported. --- ## 5. Common Problems - **Q1: How to get API support?** A: Join our official API support group and our admins will answer your questions. https://t.me/+Y72JdNeHcUw3NWQ1 - **Q2: What is the rate limit of API?** A: 1. The rate limit of each API endpoint is marked on the doc page; 2. The rate limit of each API interface is calculated independently. - **Q3: Are symbols case-sensitive in API endpoints?** A: Yes. Symbols are case-sensitive and must be in all uppercase letters. - **Q4: If I forget the passphrase of API key, what should I do?** A: The passphrase of API Key can not be modified, please recreate your API Key. --- ## 6. More Support If you encounter technical difficulties during development, you can obtain support through the following channels: * **Official API Docs:** [WEEX API Documentation](/api-doc/contract/changelog) * **Telegram Tech Support Groups:** * **[WEEX API Tech Support (Chinese)](https://t.me/+7jac6zttXxZjOTRl)** * **[WEEX API Tech Support (English)](https://t.me/+Y72JdNeHcUw3NWQ1)** --- :::tip Developer Tips 1. API trading involves high risk; ensure your code includes robust error-handling logic. 2. Never disclose your API Key or Secret Key to third parties. 3. The content of this document may change with system upgrades. Please refer to the latest official API documentation. ::: --- ## Document: Common Definition URL: /api-doc/contract/APIPublicParameters # Public API Parameters ## Terminology - **base asset** — the asset listed first in a symbol, representing the contract size (e.g., `BTC` in `BTCUSDT`). - **quote asset** — the pricing asset listed second in a symbol (e.g., `USDT` in `BTCUSDT`). ## Enum Definitions **Margin Mode (`marginType`):** - CROSSED — Cross margin (shared) mode - ISOLATED — Isolated margin mode **Position Mode (`separatedType` / `separatedMode`):** - COMBINED — Combined-position mode. Orders in the same direction for a symbol are merged into a single long or short position; leverage is unified and all positions under that symbol share the margin pool. - SEPARATED — Split-position mode. Orders remain isolated per direction; long and short sides maintain independent positions, margin, and leverage settings. **Order Side (`side` / `buyer` flag):** - BUY — Buy side - SELL — Sell side **Position Side (`positionSide`):** - LONG — Long position - SHORT — Short position **Order Type (`type` / `orderType`):** - LIMIT — Limit order - MARKET — Market order - STOP — Stop-limit conditional order - TAKE_PROFIT — Take-profit limit conditional order - STOP_MARKET — Stop market conditional order - TAKE_PROFIT_MARKET — Take-profit market conditional order - TRAILING_MARKET — Trailing market order **Time in Force (`timeInForce`):** - GTC — Good-Till-Cancelled - IOC — Immediate-Or-Cancel - FOK — Fill-Or-Kill - POST_ONLY — Post-only (maker only) **Order Status (`status` / `algoStatus`):** - NEW — Accepted and working - PENDING — Pending activation - UNTRIGGERED — Conditional order waiting for trigger - UNACTIVATED — Trailing order waiting for activation - FILLED — Fully filled - CANCELED — Canceled - CANCELING — Cancel request in progress **Trigger Price Type (`workingType` / `tpOrderType`):** - CONTRACT_PRICE — Trigger off the latest contract price - MARK_PRICE — Trigger off the mark price **Conditional Order Category (`algoType`):** - CONDITIONAL — Standard conditional order **Income Type (`incomeType`):** - deposit — Asset deposit - withdraw — Asset withdrawal - transfer_in — Transfer in from another account - transfer_out — Transfer out to another account - margin_move_in — Margin moved in (open/close/manual/auto add) - margin_move_out — Margin moved out (open/close/manual/auto reduce) - position_open_long — Opening long position adjustment - position_open_short — Opening short position adjustment - position_close_long — Closing long position adjustment - position_close_short — Closing short position adjustment - position_funding — Funding fee settlement - order_fill_fee_income — Order fill fee income - order_liquidate_fee_income — Liquidation fee income - start_liquidate — Start liquidation - finish_liquidate — Finish liquidation - order_fix_margin_amount — Compensation for liquidation loss - tracking_follow_pay — Copy-trading follower payment - tracking_system_pre_receive — Copy-trading system pre-receive - tracking_follow_back — Copy-trading commission refund - tracking_trader_income — Copy-trading trader income - tracking_trader_share — Trader share of profits - tracking_third_party_share — Third-party share of profits --- ## Document: Change Log URL: /api-doc/contract/changelog # Change Log | Effective Time (UTC+8) | API | Update Type | Description | |--------------------------|------------------------------------------------------------------|---------------|--------------------------------------------------------------------------------------------------------------------------------------------| | 2026-09-01 | [Place Order](/api-doc/contract/Transaction_API/PlaceOrder), [Place Orders Batch](/api-doc/contract/Transaction_API/PlaceOrdersBatch), [Place TP/SL Conditional Orders](/api-doc/contract/Transaction_API/PlaceTpSlOrder) | Modify | Added `reduceOnly`. | | 2026-09-01 | [Place Conditional Order](/api-doc/contract/Transaction_API/PlacePendingOrder) | Modify | Added `TRAILING_MARKET`, trailing order parameters, and `reduceOnly`. | | 2026-08-27 | [Get Exchange Information](/api-doc/contract/Market_API/GetContractInfo) | Modify | Added contract classification fields and optional filters. | | 2026-07-14 | [Place Order](/api-doc/contract/Transaction_API/PlaceOrder) | Modify | Added `POST_ONLY` as a supported value for the `timeInForce` parameter. | | 2026-07-14 | [Close Positions](/api-doc/contract/Transaction_API/ClosePositions) | Modify | Added the `positionId` request parameter to support closing a position by position ID. | | 2026-06-22 | [Access Restrictions](/api-doc/contract/QuickStart/AccessRestrictions) | Modify | Updated access restriction rules. | | 2026-05-28 | [Place Orders Batch](/api-doc/contract/Transaction_API/PlaceOrdersBatch) | Launched | Opened the batch order placement API. | | 2026-04-09 | Demo | New | Added demo endpoints: Get Account Balance, Get All Positions, Place Order, and Get Order History. | | 2026-03-18 | * | Launched | Contract Websocket V3 service officially launched; V2 will be retired and no longer maintained. V3 streams data faster with lower latency. | | 2026-03-09 | * | Launched | Futures Contract V3 launched with improved performance and stability; V3 will receive ongoing maintenance while V2 is sunset. | --- ## Document: Contact Us URL: /api-doc/contract/ContactUs # Contact Us For technical issues or any feedback, feel free to reach out to us via the following methods: - Email us at support@weex.com - Join our [Telegram community](https://t.me/+Y72JdNeHcUw3NWQ1) to stay updated and engage with the community. --- ## Document: Get Account Balance Demo (USER_DATA) URL: /api-doc/contract/demo/GetAccountBalance # Get Account Balance Demo (USER_DATA) - **GET** ```/capi/v3/sim/balance``` Weight(IP): 5
**Request parameters** NONE
**Request example** ```powershell curl "https://api-contract.weex.com/capi/v3/sim/balance" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "Content-Type: application/json" ```
**Response parameters** | Parameter | Type | Description | |:-----------------|:-------|:-------------------------| | asset | String | Asset name | | balance | String | Total balance | | availableBalance | String | Available balance | | frozen | String | Frozen amount | | unrealizePnl | String | Unrealized Profit and Loss |
**Response example** ```json [ { "asset": "SUSDT", "balance": "5696.49288823", "availableBalance": "5413.06877369", "frozen": "81.28240000", "unrealizePnl": "-34.55300000" } ] ```
--- ## Document: Get All Positions Demo (USER_DATA) URL: /api-doc/contract/demo/GetAllPositions # Get All Positions Demo (USER_DATA) - **GET** ```/capi/v3/sim/position/allPosition``` Weight(IP): 10
**Request parameters** NONE
**Request example** ```powershell curl "https://api-contract.weex.com/capi/v3/sim/position/allPosition" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "Content-Type: application/json" ```
**Response parameters** | Parameter | Type | Description | |----------------------------|---------|----------------------------------------------------------------------------------------------------------------------------------------| | id | Long | Position ID | | asset | String | Associated collateral asset | | symbol | String | Trading pair | | side | String | Position direction such as LONG or SHORT | | marginType | String | Margin mode of current position
CROSSED: Cross Mode
ISOLATED: Isolated Mode | | separatedMode | String | Current position's separated mode
COMBINED: Combined mode
SEPARATED: Separated mode | | separatedOpenOrderId | Long | Opening order ID of separated position | | leverage | String | Position leverage | | size | String | Current position size | | openValue | String | Initial value at position opening | | openFee | String | Opening fee | | fundingFee | String | Funding fee | | marginSize | String | Margin amount (margin coin) | | isolatedMargin | String | Isolated margin | | isAutoAppendIsolatedMargin | Boolean | Whether the auto-adding of funds for the isolated margin is enabled (only for isolated mode) | | cumOpenSize | String | Accumulated opened positions | | cumOpenValue | String | Accumulated value of opened positions | | cumOpenFee | String | Accumulated fees paid for opened positions | | cumCloseSize | String | Accumulated closed positions | | cumCloseValue | String | Accumulated value of closed positions | | cumCloseFee | String | Accumulated fees paid for closing positions | | cumFundingFee | String | Accumulated settled funding fees | | cumLiquidateFee | String | Accumulated liquidation fees | | createdMatchSequenceId | Long | Matching engine sequence ID at creation | | updatedMatchSequenceId | Long | Matching engine sequence ID at last update | | createdTime | Long | Creation time
Unix millisecond timestamp | | updatedTime | Long | Update time
Unix millisecond timestamp | | unrealizePnl | String | Unrealized PnL | | liquidatePrice | String | Estimated liquidation price
If the value = 0, it means the position is at low risk and there is no liquidation price at this time |
**Response example** ```json [ { "id": 689987235755328154, "asset": "SUSDT", "symbol": "BTCSUSDT", "side": "LONG", "marginType": "CROSSED", "separatedMode": "COMBINED", "separatedOpenOrderId": 0, "leverage": "100", "size": "0.020000", "openValue": "1801.0670000", "openFee": "0.70731060", "fundingFee": "1.22618160", "marginSize": "17.154980", "isolatedMargin": "0", "isAutoAppendIsolatedMargin": false, "cumOpenSize": "0.020000", "cumOpenValue": "1801.0670000", "cumOpenFee": "0.70731060", "cumCloseSize": "0", "cumCloseValue": "0", "cumCloseFee": "0", "cumFundingFee": "1.22618160", "cumLiquidateFee": "0", "createdMatchSequenceId": 7027745116, "updatedMatchSequenceId": 7040274110, "createdTime": 1764505776347, "updatedTime": 1764588886461, "unrealizePnl": "-85.5690000", "liquidatePrice": "0" } ] ```
--- ## Document: Get Order History Demo (USER_DATA) URL: /api-doc/contract/demo/GetOrderHistory # Get Order History Demo (USER_DATA) - **GET** ```/capi/v3/sim/order/history``` Weight(IP): 10
**Request parameters** | Parameter | Type | Required? | Description | |-----------|---------|-----------|-------------| | symbol | String | No | Filter by trading pair. | | limit | Integer | No | Number of records per page, 1-1000. Default 500. | | startTime | Long | No | Start time (ms). Must be less than or equal to `endTime`. | | endTime | Long | No | End time (ms). Must be within 90 days of `startTime`. | | page | Integer | No | Page index starting from 0. Default 0. |
**Request example** ```powershell curl "https://api-contract.weex.com/capi/v3/sim/order/history?symbol=BTCSUSDT" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ ```
**Response parameters** Returns an array of objects identical to [Get Order Info](/api-doc/contract/Transaction_API/GetSingleOrderInfo#response-parameters).
**Response example** ```json [ { "orderId": 702345678901234567, "symbol": "BTCSUSDT", "side": "BUY", "positionSide": "LONG", "status": "FILLED", "type": "LIMIT", "time": 1764400000000, "price": "65000", "origQty": "0.01", "executedQty": "0.01", "avgPrice": "64999.5", "updateTime": 1764400001234, "clientOrderId": "hist-1", "cumQuote": "649.995", "timeInForce": "GTC" } ] ```
--- ## Document: Demo Mode URL: /api-doc/contract/demo # Demo Mode --- ## Document: Place Order Demo (TRADE) URL: /api-doc/contract/demo/PlaceOrder # Place Order Demo (TRADE) - **POST** ```/capi/v3/sim/order``` 1 on 10s order rate limit(X-ORDER-COUNT-10S); 1 on 1min order rate limit(X-ORDER-COUNT-1M); 0 on IP rate limit(X-USED-WEIGHT-1M);
**Request parameters** | Parameter | Type | Required? | Description | |------------------|---------|-------------|---------------------------------------------------------------------------------------------------------------| | symbol | String | Yes | Trading pair, for example `BTCSUSDT`. | | side | String | Yes | Order side. Supported values: `BUY`, `SELL`. | | positionSide | String | Yes | Position side. Supported values: `LONG`, `SHORT`. | | type | String | Yes | Order type. Supported values: `LIMIT`, `MARKET`. | | timeInForce | String | Conditional | Time-in-force policy. Required when `type = LIMIT`. Supported values: `GTC`, `IOC`, `FOK`. | | quantity | String | Yes | Order quantity. Must be greater than 0. | | price | String | Conditional | Limit price. Required when `type = LIMIT`. | | newClientOrderId | String | Yes | Client order identifier (1-36 characters, pattern `^[\\.A-Z\:/a-z0-9_-]{1,36}$`). | | tpTriggerPrice | String | No | Optional take-profit trigger price. | | slTriggerPrice | String | No | Optional stop-loss trigger price. | | TpWorkingType | String | No | Take-profit trigger price source. Supported values: `CONTRACT_PRICE`, `MARK_PRICE`. Default `CONTRACT_PRICE`. | | SlWorkingType | String | No | Stop-loss trigger price source. Supported values: `CONTRACT_PRICE`, `MARK_PRICE`. Default `CONTRACT_PRICE`. |
**Request example** ```powershell curl -X POST "https://api-contract.weex.com/capi/v3/sim/order" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "Content-Type: application/json" \ -d '{ "symbol": "BTCSUSDT", "side": "BUY", "positionSide": "LONG", "type": "LIMIT", "timeInForce": "GTC", "quantity": "0.01", "price": "69000", "newClientOrderId": "my-order-0001", "tpTriggerPrice": "70000", "slTriggerPrice": "68000", "TpWorkingType": "CONTRACT_PRICE", "SlWorkingType": "MARK_PRICE" }' ```
**Response parameters** | Field | Type | Description | |----------------|---------|--------------------------------------------------------| | orderId | String | Order ID assigned by the system. | | clientOrderId | String | Echo of `newClientOrderId`. | | success | Boolean | Whether the order request was accepted. | | errorCode | String | Error code when `success = false`; otherwise empty. | | errorMessage | String | Error message when `success = false`; otherwise empty. |
**Response example** ```json { "orderId": "702345678901234567", "clientOrderId": "my-order-0001", "success": true, "errorCode": "", "errorMessage": "" } ```
--- ## Document: Error Codes URL: /api-doc/contract/ExampleOfErrorCode # Error Codes Here is the error JSON payload: ```json { "code": -1121, "msg": "Invalid symbol." } ``` Errors consist of two parts: an error code and a message. Codes are universal, but messages can vary. ## 10xx - General Server or Network issues ### -1000 UNKNOWN_ERROR - An unknown error occurred. ### -1054 SYSTEM_ERROR - System error, please retry later. ## 10xx - Authentication / Access ### -1040 ACCESS_KEY_EMPTY - ACCESS_KEY header is required. ### -1041 ACCESS_SIGN_EMPTY - ACCESS_SIGN header is required. ### -1042 ACCESS_TIMESTAMP_EMPTY - ACCESS_TIMESTAMP header is required. ### -1043 INVALID_ACCESS_TIMESTAMP - Invalid ACCESS_TIMESTAMP. ### -1044 INVALID_ACCESS_KEY - Invalid ACCESS_KEY. ### -1045 INVALID_CONTENT_TYPE - Invalid Content-Type, please use application/json. ### -1046 ACCESS_TIMESTAMP_EXPIRED - Request timestamp expired. ### -1047 API_AUTH_ERROR - API authentication failed. ### -1049 API_KEY_OR_PASSPHRASE_INCORRECT - API key or passphrase incorrect. ### -1050 USER_STATUS_FORBIDDEN - User status is abnormal. ### -1051 PERMISSION_DENIED - Permission denied. ### -1052 INSUFFICIENT_PERMISSIONS - Insufficient permissions for this action. ### -1053 PERMISSION_VALIDATION_FAILED - Permission validation failed. ### -1055 USER_AUTH_NOT_SAFE - User must bind phone or Google authenticator. ### -1056 ILLEGAL_IP - Invalid IP address. ### -1057 USER_LOCKED - User account is locked. ### -1058 NO_PERMISSION_TRADE_PAIR - The trading pair is not supported via the API. Check the supported symbols here: [https://api-contract.weex.com/capi/v3/market/apiTradingSymbols](https://api-contract.weex.com/capi/v3/market/apiTradingSymbols). ### -1059 HIGH_FREQUENCY_ORDER_LIMITED - Too many high-frequency order requests in current window. ### -1060 API_KEY_SYMBOL_NOT_BOUND - This API key is not bound to the trading pair. ## 11xx - Request Content / Parameters ### -1115 INVALID_TIME_IN_FORCE - Invalid timeInForce. ### -1116 INVALID_ORDER_TYPE - Invalid order type. ### -1117 INVALID_SIDE - Invalid side. ### -1121 INVALID_SYMBOL - Invalid symbol. ### -1128 INVALID_PARAM_COMBINATION - Combination of optional parameters invalid. ### -1135 INVALID_JSON - Invalid JSON request. ### -1140 PARAM_VALIDATE_ERROR - Parameter validation failed. - limit must be between %d and %d. - startTime must be a valid millisecond timestamp. - endTime must be a valid millisecond timestamp. ### -1141 PARAM_EMPTY - Parameter '%s' cannot be empty. ### -1142 PARAM_ERROR - Parameter '%s' is invalid. ### -1150 REQUEST_METHOD_NOT_SUPPORTED - Request method not supported. ### -1160 DECIMAL_PRECISION_ERROR - Decimal precision error. ### -1170 QUERY_TIME_OUT_OF_RANGE - startTime must be within the last %d days. - Time range cannot exceed %d days. ### -1171 START_TIME_AFTER_END_TIME - startTime cannot be greater than endTime. ### -1180 CLIENT_OID_LENGTH_ERROR - client_oid length must not exceed 40 and must not contain special characters. ### -1190 FORBIDDEN_ACCESS - Access forbidden. Please contact support. ## 30xx - Contract Config ### -3006 CONTRACT_DOES_NOT_SUPPORT_CONTRACT_UNITS - Contract does not support ordering by contract units. ### -3007 CONTRACT_MAX_ORDER_QUANTITY_EXCEEDED - Maximum contract order quantity exceeded. ## 32xx - Contract Orders ### -3200 CONTRACT_ORDER_NOT_EXIST - Order does not exist. ### -3201 CONTRACT_ORDER_QUANTITY_EXCEEDS_LIMIT - Order quantity cannot exceed %d. ### -3235 CONTRACT_NO_PERMISSION_TRADE_PAIR - No permission for this trading pair. ### -3236 CONTRACT_NO_PERMISSION_API - No permission to access this API. ## 33xx - Contract Leverage / Position ### -3313 CONTRACT_LEVERAGE_ERROR - Leverage exceeds maximum limit. ## 36xx - Contract Internal / System ### -3613 CONTRACT_FATAL_TOKEN_NOT_SUPPORT - Fatal: token ID not supported for symbol. --- ## Document: Introduction URL: /api-doc/contract/intro # Introduction The WEEX contract trading API provides developers with a complete set of programmatic trading interfaces, covering core functions such as market data retrieval, account management, and order operations. Through this API, developers can: - Automate trading strategies: programmatic order placement, take-profit and stop-loss - Monitor real-time market data: access K-line, order book, and latest trade data - Manage account assets: query balances and fund flow records --- ## Document: Get API Trading Symbols URL: /api-doc/contract/Market_API/GetApiTradingSymbols # Get API Trading Symbols - **GET** ```/capi/v3/market/apiTradingSymbols``` Weight(IP): 5
**Request parameters** No parameters.
**Request example** ```powershell curl "https://api-contract.weex.com/capi/v3/market/apiTradingSymbols" ```
**Response** Returns an array containing all trading pairs that are currently eligible for API futures trading.
**Response example** ```json [ "BTCUSDT", "ETHUSDT", "BCHUSDT" ] ```
--- ## Document: Get Best Bid/Ask URL: /api-doc/contract/Market_API/GetBookTicker # Get Best Bid/Ask - **GET** ```/capi/v3/market/ticker/bookTicker``` Weight(IP): 1
**Request parameters** | Parameter | Type | Required? | Description | |-----------|--------|-----------|------------------------------------------------------------| | symbol | String | No | Trading pair. Leave empty to return all trading pairs. |
**Request example** ```powershell curl "https://api-contract.weex.com/capi/v3/market/ticker/bookTicker?symbol=BTCUSDT" ```
**Response parameters** | Parameter | Type | Description | |-----------|--------|----------------------------------------------| | symbol | String | Trading pair | | bidPrice | String | Best bid price | | bidQty | String | Quantity available at the best bid price | | askPrice | String | Best ask price | | askQty | String | Quantity available at the best ask price | | time | Long | Matching engine timestamp |
**Response example** ```json [ { "symbol": "BTCUSDT", "bidPrice": "69350.1", "bidQty": "12.5", "askPrice": "69351.0", "askQty": "8.3", "time": 1764505776000 } ] ```
--- ## Document: Get Exchange Information URL: /api-doc/contract/Market_API/GetContractInfo # Get Exchange Information - **GET** ```/capi/v3/market/exchangeInfo``` Weight(IP): 1
**Request parameters** | Parameter | Type | Required? | Description | |-------------------|--------|-----------|-----------------------------------------------------------------------------| | symbol | String | No | Trading pair. Leave empty to return all supported contracts and assets. | | contractType | String | No | Contract type. Supported values: `PERPETUAL`, `TRADIFI_PERPETUAL`. | | underlyingType | String | No | Underlying asset type. | | underlyingSubType | String | No | Underlying asset label. Matches if the symbol's `underlyingSubType` contains this value. |
**Request example** ```powershell curl "https://api-contract.weex.com/capi/v3/market/exchangeInfo?symbol=BTCUSDT" ```
**Response parameters** | Parameter | Type | Description | |-----------|-------|-----------------------------------------------------------------------------| | assets | Array | Collateral assets list. Each item matches the *Coin object (assets[])*. | | rateLimits | Array | API access rate limits. Each item matches the *Rate-limit object (rateLimits[])*. | | symbols | Array | Contract configuration list. Each item matches the *Symbol object (symbols[])*. |
**Coin object (assets[])** | Field | Type | Description | |------------------|---------|--------------------------------------------------| | asset | String | Asset symbol (collateral currency) | | marginAvailable | Boolean | Whether the asset can be used as collateral |
**Rate-limit object (rateLimits[])** | Field | Type | Description | |---------------|---------|------------------------------------------------------| | interval | String | Rate-limit interval unit, e.g. `MINUTE` | | intervalNum | Integer | Number of interval units, e.g. `1` | | limit | Integer | Maximum allowed count within the interval | | rateLimitType | String | Rate-limit type, e.g. `REQUEST_WEIGHT` or `ORDERS` |
**Symbol object (symbols[])** | Field | Type | Description | |---------------------|-----------|--------------------------------------------------------------| | symbol | String | Trading pair name (e.g. BTCUSDT) | | displaySymbol | String | Trading pair display name | | baseAsset | String | Base asset | | quoteAsset | String | Quote asset | | marginAsset | String | Margin asset | | contractType | String | Contract type. Supported values: `PERPETUAL`, `TRADIFI_PERPETUAL` | | underlyingType | String | Underlying asset type | | underlyingSubType | Array | Underlying asset labels | | pricePrecision | Integer | Price precision | | quantityPrecision | Integer | Quantity precision | | baseAssetPrecision | Integer | Precision for base asset quantity | | quotePrecision | Integer | Precision for quote asset quantity | | contractVal | Decimal | Contract size | | delivery | Array | Settlement times | | forwardContractFlag | Boolean | Whether the contract is USDT-margined | | minLeverage | Integer | Minimum leverage | | maxLeverage | Integer | Maximum leverage | | buyLimitPriceRatio | Decimal | Buy-side price limit ratio | | sellLimitPriceRatio | Decimal | Sell-side price limit ratio | | makerFeeRate | Decimal | Contract maker fee rate | | takerFeeRate | Decimal | Contract taker fee rate | | apiMakerFeeRate | Decimal | Maker fee rate for orders placed through the API. This field may not be returned. | | apiTakerFeeRate | Decimal | Taker fee rate for orders placed through the API. This field may not be returned. | | minOrderSize | Decimal | Minimum order size (base asset) | | maxOrderSize | Decimal | Maximum order size (base asset) | | maxPositionSize | Decimal | Maximum position size (base asset) | | marketOpenLimitSize | Decimal | Maximum market order size for opening positions (base asset) |
**Response example** ```json { "assets": [ { "asset": "BTC", "marginAvailable": false }, { "asset": "USDT", "marginAvailable": true } ], "rateLimits": [ { "rateLimitType": "REQUEST_WEIGHT", "interval": "SECOND", "intervalNum": 10, "limit": 2000 }, { "rateLimitType": "ORDERS", "interval": "SECOND", "intervalNum": 10, "limit": 5 } ], "symbols": [ { "symbol": "BTCUSDT", "displaySymbol": "BTCUSDT", "baseAsset": "BTC", "quoteAsset": "USDT", "marginAsset": "USDT", "contractType": "PERPETUAL", "underlyingType": "COIN", "underlyingSubType": [ "PoW" ], "pricePrecision": 1, "quantityPrecision": 6, "baseAssetPrecision": 3, "quotePrecision": 8, "contractVal": 0.000001, "delivery": [ "00:00:00", "06:00:00", "12:00:00", "18:00:00" ], "forwardContractFlag": true, "minLeverage": 1, "maxLeverage": 408, "buyLimitPriceRatio": 0.016, "sellLimitPriceRatio": 0.015, "makerFeeRate": 0, "takerFeeRate": 0.001, "apiMakerFeeRate": 0.0002, "apiTakerFeeRate": 0.0008, "minOrderSize": 0.0001, "maxOrderSize": 10000, "maxPositionSize": 20000000, "marketOpenLimitSize": 12000 } ] } ```
--- ## Document: Get Current Funding Rate URL: /api-doc/contract/Market_API/GetCurrentFundingRate # Get Current Funding Rate - **GET** ```/capi/v3/market/premiumIndex``` Weight(IP): 1
**Request parameters** | Parameter | Type | Required? | Description | |-----------|--------|-----------|------------------------------------------------------------| | symbol | String | No | Trading pair. Leave empty to return all trading pairs. |
**Request example** ```powershell curl "https://api-contract.weex.com/capi/v3/market/premiumIndex?symbol=BTCUSDT" ```
**Response parameters** | Parameter | Type | Description | |---------------------|--------|--------------------------------------------------| | symbol | String | Trading pair | | markPrice | String | Latest mark price | | indexPrice | String | Latest index price | | lastFundingRate | String | Most recent funding rate | | forecastFundingRate | String | Forecasted funding rate | | interestRate | String | Underlying benchmark interest rate | | nextFundingTime | Long | Next funding time
Unix millisecond timestamp | | time | Long | Data timestamp
Unix millisecond timestamp | | collectCycle | Long | Funding interval in minutes |
**Response example** ```json [ { "symbol": "BTCUSDT", "markPrice": "69348.6", "indexPrice": "69347.9", "lastFundingRate": "0.00025", "forecastFundingRate": "0.00025", "interestRate": "0.0001", "nextFundingTime": 1764510000000, "time": 1764505777345, "collectCycle": 480 } ] ```
--- ## Document: Get Order Book Depth URL: /api-doc/contract/Market_API/GetDepthData # Get Order Book Depth - **GET** ```/capi/v3/market/depth``` Weight(IP): 1
**Request parameters** | Parameter | Type | Required? | Description | |-----------|---------|-----------|-----------------------------------------------------------------------------| | symbol | String | Yes | Trading pair | | limit | Integer | No | Depth size. Supported values: `15`, `200`. Default: `15`. |
**Request example** ```powershell curl "https://api-contract.weex.com/capi/v3/market/depth?symbol=BTCUSDT&limit=200" ```
**Response parameters** | Parameter | Type | Description | |--------------|-------|-----------------------------------------------------------------------------------------------------------| | bids | Array | Bid side depth.
Each item is `[price, size]`. | | asks | Array | Ask side depth.
Each item is `[price, size]`. | | lastUpdateId | Long | Last processed order book update ID |
**Response example** ```json { "bids": [ ["69350.1", "12.5"], ["69349.8", "1.2"] ], "asks": [ ["69351.0", "3.6"], ["69351.2", "0.8"] ], "lastUpdateId": 1234567890123 } ```
--- ## Document: Get Funding Rate History URL: /api-doc/contract/Market_API/GetFundingRateHistory # Get Funding Rate History - **GET** ```/capi/v3/market/fundingRate``` Weight(IP): 5
**Request parameters** | Parameter | Type | Required? | Description | |-----------|---------|-----------|-----------------------------------------------------------------------------------------------------| | symbol | String | Yes | Trading pair | | startTime | Long | No | Start time (inclusive). Unix millisecond timestamp. | | endTime | Long | No | End time (inclusive). Unix millisecond timestamp. Must be ≥ startTime. | | limit | Integer | No | Number of records. Range: 1-1000. Default: 100. |
The time span between `startTime` and `endTime` must not exceed 7 days.
**Request example** ```powershell curl "https://api-contract.weex.com/capi/v3/market/fundingRate?symbol=BTCUSDT&startTime=1763894400000&endTime=1764499200000&limit=50" ```
**Response parameters** | Parameter | Type | Description | |-------------|--------|------------------------------------------| | symbol | String | Trading pair | | fundingRate | String | Historical funding rate | | fundingTime | Long | Funding time
Unix millisecond timestamp | | markPrice | String | Mark price at the funding time |
**Response example** ```json [ { "symbol": "BTCUSDT", "fundingRate": "0.00025", "fundingTime": 1764499200000, "markPrice": "69250.0" } ] ```
--- ## Document: Get Historical Klines URL: /api-doc/contract/Market_API/GetHistoryKlines # Get Historical Klines - **GET** ```/capi/v3/market/historyKlines``` Weight(IP): 5
**Request parameters** | Parameter | Type | Required? | Description | |-----------|---------|-----------|-------------------------------------------------------------------------------------------------------------------------------------| | symbol | String | Yes | Trading pair | | interval | String | Yes | Kline interval.
Allowed values: 1m, 5m, 15m, 30m, 1h, 4h, 12h, 1d, 1w. | | startTime | Long | No | Start time (inclusive). Unix millisecond timestamp. Must not be in the future. | | endTime | Long | No | End time (inclusive). Unix millisecond timestamp. Must not be in the future and must be ≥ startTime. | | limit | Integer | No | Number of klines to return. Range: 1-100. Default: 100. | | priceType | String | No | Price type. Supported values: LAST (last trade), INDEX (index price), MARK (mark price). Default: LAST. |
**Request example** ```powershell curl "https://api-contract.weex.com/capi/v3/market/historyKlines?symbol=BTCUSDT&interval=4h&startTime=1763894400000&endTime=1764499200000&priceType=MARK" ```
**Response parameters** Same structure as [Get Kline Data](/api-doc/contract/Market_API/GetKlines).
**Response example** ```json [ [ 1763894400000, "68000.0", "68550.0", "67810.0", "68220.0", "320.456", 1763908800000, "21874563.70", 982, "180.120", "12345678.90" ] ] ```
--- ## Document: Get Index Price Klines URL: /api-doc/contract/Market_API/GetIndexPriceKlines # Get Index Price Klines - **GET** ```/capi/v3/market/indexPriceKlines``` Weight(IP): 1
**Request parameters** | Parameter | Type | Required? | Description | |-----------|---------|-----------|-------------------------------------------------------------------------------------------------| | symbol | String | Yes | Trading pair | | interval | String | Yes | Kline interval.
Allowed values: 1m, 5m, 15m, 30m, 1h, 4h, 12h, 1d, 1w. | | limit | Integer | No | Number of klines to return. Range: 1-1000. Default: 100. |
**Request example** ```powershell curl "https://api-contract.weex.com/capi/v3/market/indexPriceKlines?symbol=BTCUSDT&interval=1h&limit=48" ```
**Response parameters** Same structure as [Get Kline Data](/api-doc/contract/Market_API/GetKlines), with prices derived from the index price feed.
**Response example** ```json [ [ 1764492000000, "69210.5", "69400.0", "69180.4", "69320.0", "0", 1764495600000, "0", 0, "0", "0" ] ] ```
--- ## Document: Get Kline Data URL: /api-doc/contract/Market_API/GetKlines # Get Kline Data - **GET** ```/capi/v3/market/klines``` Weight(IP): 1
**Request parameters** | Parameter | Type | Required? | Description | |-----------|---------|-----------|-------------------------------------------------------------------------------------------------| | symbol | String | Yes | Trading pair | | interval | String | Yes | Kline interval.
Allowed values: 1m, 5m, 15m, 30m, 1h, 4h, 12h, 1d, 1w. | | limit | Integer | No | Number of klines to return. Range: 1-1000. Default: 100. |
**Request example** ```powershell curl "https://api-contract.weex.com/capi/v3/market/klines?symbol=BTCUSDT&interval=1m&limit=100" ```
**Response parameters** | Index | Type | Description | |------------|--------|-------------------------------------------------------| | index[0] | Long | Open time
Unix millisecond timestamp | | index[1] | String | Open price | | index[2] | String | High price | | index[3] | String | Low price | | index[4] | String | Close price | | index[5] | String | Volume (base asset) | | index[6] | Long | Close time
Unix millisecond timestamp | | index[7] | String | Quote volume (quote asset) | | index[8] | Long | Number of trades | | index[9] | String | Taker buy volume (base asset) | | index[10] | String | Taker buy volume (quote asset) |
**Response example** ```json [ [ 1764505740000, "69340.1", "69380.0", "69320.5", "69355.2", "25.678", 1764505800000, "1782223.45", 125, "12.345", "856789.12" ] ] ```
--- ## Document: Get Mark Price Klines URL: /api-doc/contract/Market_API/GetMarkPriceKlines # Get Mark Price Klines - **GET** ```/capi/v3/market/markPriceKlines``` Weight(IP): 1
**Request parameters** | Parameter | Type | Required? | Description | |-----------|---------|-----------|-------------------------------------------------------------------------------------------------| | symbol | String | Yes | Trading pair | | interval | String | Yes | Kline interval.
Allowed values: 1m, 5m, 15m, 30m, 1h, 4h, 12h, 1d, 1w. | | limit | Integer | No | Number of klines to return. Range: 1-1000. Default: 100. |
**Request example** ```powershell curl "https://api-contract.weex.com/capi/v3/market/markPriceKlines?symbol=BTCUSDT&interval=15m&limit=96" ```
**Response parameters** Identical to [Get Kline Data](/api-doc/contract/Market_API/GetKlines), with prices taken from the mark price feed.
**Response example** ```json [ [ 1764504000000, "69310.0", "69360.0", "69280.5", "69340.2", "15.234", 1764504900000, "1056702.43", 64, "7.100", "493021.56" ] ] ```
--- ## Document: Get Open Interest URL: /api-doc/contract/Market_API/GetOpenInterest # Get Open Interest - **GET** ```/capi/v3/market/openInterest``` Weight(IP): 2
**Request parameters** | Parameter | Type | Required? | Description | |-----------|--------|-----------|--------------| | symbol | String | Yes | Trading pair |
**Request example** ```powershell curl "https://api-contract.weex.com/capi/v3/market/openInterest?symbol=BTCUSDT" ```
**Response parameters** | Parameter | Type | Description | |--------------|--------|-----------------------------------------------------| | symbol | String | Trading pair | | openInterest | String | Current open interest (contracts) | | time | Long | Matching engine timestamp
Unix millisecond timestamp |
**Response example** ```json { "symbol": "BTCUSDT", "openInterest": "128345.67", "time": 1764505777345 } ```
--- ## Document: Get Recent Trades URL: /api-doc/contract/Market_API/GetRecentTrades # Get Recent Trades - **GET** ```/capi/v3/market/trades``` Weight(IP): 5
**Request parameters** | Parameter | Type | Required? | Description | |-----------|---------|-----------|-----------------------------------------------------------------| | symbol | String | Yes | Trading pair | | limit | Integer | No | Number of trades to return. Range: 1-1000. Default: 100. |
**Request example** ```powershell curl "https://api-contract.weex.com/capi/v3/market/trades?symbol=BTCUSDT&limit=50" ```
**Response parameters** | Parameter | Type | Description | |---------------|---------|----------------------------------------------------------| | id | String | Trade ID | | time | Long | Trade time
Unix millisecond timestamp | | price | String | Trade price | | qty | String | Filled quantity (base asset) | | quoteQty | String | Trade value (quote asset) | | isBestMatch | Boolean | Whether the trade was the best match | | isBuyerMaker | Boolean | Whether the buyer was the maker |
**Response example** ```json [ { "id": "1234567890", "time": 1764505776123, "price": "69350.8", "qty": "0.005", "quoteQty": "346.754", "isBestMatch": true, "isBuyerMaker": false } ] ```
--- ## Document: Get Server Time URL: /api-doc/contract/Market_API/GetServerTime # Get Server Time - **GET** ```/capi/v3/market/time``` Weight(IP): 1
**Request parameters** NONE
**Request example** ```powershell curl "https://api-contract.weex.com/capi/v3/market/time" ```
**Response parameters** | Parameter | Type | Description | |------------|------|------------------------------------------| | serverTime | Long | Server time
Unix millisecond timestamp |
**Response example** ```json { "serverTime": 1764505776347 } ```
--- ## Document: Get Symbol Price URL: /api-doc/contract/Market_API/GetSymbolPrice # Get Symbol Price - **GET** ```/capi/v3/market/symbolPrice``` Weight(IP): 1
**Request parameters** | Parameter | Type | Required? | Description | |-----------|--------|-----------|-----------------------------------------------------------------------------| | symbol | String | Yes | Trading pair | | priceType | String | No | Price type. Supported values: INDEX, MARK. Default: INDEX. |
**Request example** ```powershell curl "https://api-contract.weex.com/capi/v3/market/symbolPrice?symbol=BTCUSDT&priceType=MARK" ```
**Response parameters** | Parameter | Type | Description | |-----------|--------|------------------------------------------| | symbol | String | Trading pair | | price | String | Requested price | | time | Long | System timestamp
Unix millisecond timestamp |
**Response example** ```json { "symbol": "BTCUSDT", "price": "69348.5", "time": 1764505776890 } ```
--- ## Document: Get 24hr Ticker Statistics URL: /api-doc/contract/Market_API/GetTicker24h # Get 24hr Ticker Statistics - **GET** ```/capi/v3/market/ticker/24hr``` Weight(IP): 40
**Request parameters** | Parameter | Type | Required? | Description | |-----------|--------|-----------|------------------------------------------------------------| | symbol | String | No | Trading pair. Leave empty to return all trading pairs. |
**Request example** ```powershell curl "https://api-contract.weex.com/capi/v3/market/ticker/24hr?symbol=BTCUSDT" ```
**Response parameters** | Parameter | Type | Description | |---------------------|--------|---------------------------------------------------| | symbol | String | Trading pair | | priceChange | String | Absolute price change over the last 24 hours | | priceChangePercent | String | Percentage price change over the last 24 hours | | lastPrice | String | Last traded price | | openPrice | String | Open price 24 hours ago | | highPrice | String | Highest price in the last 24 hours | | lowPrice | String | Lowest price in the last 24 hours | | volume | String | 24-hour trading volume (base asset) | | quoteVolume | String | 24-hour trading volume (quote asset) | | markPrice | String | Last mark price | | indexPrice | String | Last index price | | openTime | Long | Timestamp of the first trade in the 24-hour window | | closeTime | Long | Timestamp of the last trade in the 24-hour window |
**Response example** ```json [ { "symbol": "BTCUSDT", "priceChange": "150.5", "priceChangePercent": "0.22", "lastPrice": "69350.5", "openPrice": "69200.0", "highPrice": "69980.0", "lowPrice": "68888.0", "volume": "1234.567", "quoteVolume": "85679012.45", "markPrice": "69348.7", "indexPrice": "69347.9", "openTime": 1764419370000, "closeTime": 1764505770000 } ] ```
--- ## Document: Market URL: /api-doc/contract/Market_API # Market --- ## Document: Access Restrictions URL: /api-doc/contract/QuickStart/AccessRestrictions # Access Restrictions REST API access is rate limited. Except for order placement endpoints, all endpoints are rate limited by IP. Order placement endpoints are rate limited by the `ORDERS` type. When you exceed a request rate limit, the request fails with HTTP status code `429`. When you receive `429`, you are responsible for stopping requests and must not abuse the API. Violating the limits results in a `10s` ban. ## Basic Information The following `intervalLetter` values are used in response headers: | interval | intervalLetter | |----------|----------------| | SECOND | S | | MINUTE | M | | HOUR | H | | DAY | D | The `rateLimits` array in `/capi/v3/market/exchangeInfo` contains REST API rate limits, including but not limited to the REST endpoints in this document. These limits include weighted request limits and order rate limits. For more information about limit types, see the enum definitions. ## IP Rate Limits Except for order placement endpoints, all endpoints use IP rate limits. These limits are based on IP, not API Key or UID. Each endpoint has a corresponding `weight`. Some endpoints may have different weights depending on request parameters. Endpoints that consume more resources have higher weights. Each request includes the following response headers: | Header | Description | |--------|-------------| | `X-USED-WEIGHT-(intervalNum)(intervalLetter)` | Used weight for the current IP within the interval. | | `X-REMAINING-WEIGHT-(intervalNum)(intervalLetter)` | Remaining weight for the current IP within the interval. | For example, `X-USED-WEIGHT-1M` indicates the used weight for the current IP within a 1-minute interval. ## ORDERS Rate Limits Order placement endpoints are rate limited by the `ORDERS` type. This limit is based on the account, that is, `userId`. Order placement endpoints do not consume IP weight. The IP rate limit count in response headers is `0`. Each order placement request includes the following response headers: | Header | Description | |--------|-------------| | `X-ORDER-COUNT-(intervalNum)(intervalLetter)` | Used order count for the current account within the interval. | | `X-ORDER-REMAINING-(intervalNum)(intervalLetter)` | Remaining order count for the current account within the interval. | --- ## Document: API Domain URL: /api-doc/contract/QuickStart/APIDomain # API Domain You can use different domain as below Rest API. | Domain Name | API | Description | |----------------------|-------------------------------|-------| | Contract REST Domain | https://api-contract.weex.com | Main Domain | --- ## Document: Preparation URL: /api-doc/contract/QuickStart/IntegrationPreparation # Preparation To use the API, please log in to the web platform, create and configure API keys with proper permissions, then proceed with development and trading as detailed in this documentation. Click [here](https://www.weex.com/account/newapi) to create an API Key. Each user can create up to 10 API Key groups. Each key can be configured for "Read" and/or "Trade" permissions. Permission details: - The default permission for newly created APIs is `Read Only` - If you need to trade via API, select the corresponding trading permission `Futures/Contract` After creating an API Key, securely store the following: - `APIKey` — The unique identifier for API authentication which is algorithmically generated. - `SecretKey` — The system-generated private key for signature encryption. - `Passphrase` —A user-defined access phrase. Note: If lost, the Passphrase cannot be recovered. You must create a new API key. :::tip You can bind IP addresses to API keys when creating API keys. Unrestricted API keys (with no IP address binding) pose security risks. ::: :::warning ::: --- ## Document: API Types URL: /api-doc/contract/QuickStart/InterfaceType # API Types This section categorizes APIs into two types: - Public APIs - Private APIs **Public APIs** Public APIs allow users to retrieve configuration and market data.These requests do not require authentication. **Private APIs** Private APIs enable order management and account management.Each private request must be authenticated using a standardized signature method. Private APIs require validation with your API key. --- ## Document: Request Processing URL: /api-doc/contract/QuickStart/RequestInteraction # Request Processing ```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 = "https://api-spot.weex.com"; // 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"); 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"); 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/v3/openOrders"; String queryString = "?symbol=BTCUSDT"; String response = sendRequestGet(API_KEY, SECRET_KEY, ACCESS_PASSPHRASE, "GET", requestPath, queryString); System.out.println("GET Response: " + response); // POST request example String postPath = "/api/v3/order"; String body = "{\"symbol\":\"BTCUSDT\",\"side\":\"BUY\",\"type\":\"LIMIT\",\"timeInForce\":\"GTC\",\"quantity\":\"0.01\",\"price\":\"68900\"}"; response = sendRequestPost(API_KEY, SECRET_KEY, ACCESS_PASSPHRASE, "POST", postPath, "", body); System.out.println("POST Response: " + response); } catch (Exception e) { e.printStackTrace(); } } } ``` ```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() # print(base64.b64encode(signature).decode()) return base64.b64encode(signature).decode() 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() # print(base64.b64encode(signature).decode()) 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)) # print(timestamp) 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" } url = "https://api-spot.weex.com" # Please replace with the actual API address if method == "GET": response = requests.get(url + request_path, headers=headers) elif method == "POST": response = requests.post(url + request_path, headers=headers, data=body) return response def send_request_get(api_key, secret_key, access_passphrase, method, request_path, query_string): timestamp = str(int(time.time() * 1000)) # print(timestamp) 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" } url = "https://api-spot.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(): # Example of calling a GET request request_path = "/api/v3/openOrders" query_string = '?symbol=BTCUSDT' response = send_request_get(api_key, secret_key, access_passphrase, "GET", request_path, query_string) print(response.status_code) print(response.text) def post(): # Example of calling a POST request request_path = "/api/v3/order" body = { "symbol": "BTCUSDT", "side": "BUY", "type": "LIMIT", "timeInForce": "GTC", "quantity": "0.01", "price": "68900" } 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__': get() post() ``` All requests are based on the HTTPS protocol. The Content-Type in the request headers must be set to 'application/json'. **Request Processing** - Request parameters: Parameter encapsulation according to endpoint request parameter specification. - Submit request: Submit the encapsulated parameters to the server via GET/POST. - Server response: The server first performs security checks on the request data, and after passing the check, returns the response data to the user in the JSON format based on the operation logic. - Data processing: Process the server response data. **Success** HTTP 200 status codes indicates success and may contain content.Response content (if any) will be included in the returned data. **Common error codes** - 400 Bad Request – Invalid request format - 401 Unauthorized – Invalid API Key - 403 Forbidden – You do not have access to the requested resource - 404 Not Found — No requests found - 429 Too Many Requests – Rate limit exceeded - 500 Internal Server Error – We had a problem with our server - Failed responses include error descriptions in the body. --- ## Document: Signature URL: /api-doc/contract/QuickStart/Signature # Signature The ACCESS-SIGN request header is generated by using the **HMAC SHA256** method encryption on the **timestamp + method.toUpperCase() + requestPath + "?" + queryString + body** string (+ denotes string concatenation), and putting the result through **BASE64** encoding. **Timestamp** The `ACCESS-TIMESTAMP` in request signatures is in milliseconds. Requests are rejected if the timestamp deviates by more than 30 seconds from the API server time. If the local server time deviates significantly from the API server time, we recommend querying the API server time and using it to update the HTTP Header. **Request Formats** The following request methods are currently supported: - GET: Parameters are sent to the server in the path through queryString. - POST: Parameters are sent to the server in the body as JSON. - DELETE: Parameters are sent to the server through queryString or a JSON body, according to the endpoint documentation. When generating the signature, concatenate `requestPath`, `queryString`, and `body` according to the actual request content. **Signature Field Description** - timestamp: This matches the ACCESS-TIMESTAMP header. - method: The request method (GET/POST/DELETE), with all letters in uppercase. - requestPath: API endpoint path. - queryString: The query parameters after the "?" in the URL. - body: The string that corresponds to the request body. It can be omitted if the request has no body. **Signature format rules if queryString is empty** - timestamp + method.toUpperCase() + requestPath + body **Signature format rules if queryString is not empty** - timestamp + method.toUpperCase() + requestPath + "?" + queryString + body **Examples** Fetching market depth, using BTCUSDT as an example: - Timestamp = 1591089508404 - Method = "GET" - requestPath = "/api/v3/market/depth" - queryString= "symbol=BTCUSDT&limit=20" **Generate the string to be signed:** - '1591089508404GET/api/v3/market/depth?symbol=BTCUSDT&limit=20' Placing an order, using BTCUSDT_SPBL as an example: - Timestamp = 1561022985382 - Method = "POST" - requestPath = "/api/v3/order" - body = ```json {"symbol":"BTCUSDT","side":"BUY","type":"LIMIT","timeInForce":"GTC","quantity":"1","price":"68900","newClientOrderId":"my-order-001"} ``` **Generate the string to be signed:** - ``` '1561022985382POST/api/v3/order{"symbol":"BTCUSDT","side":"BUY","type":"LIMIT","timeInForce":"GTC","quantity":"1","price":"68900","newClientOrderId":"my-order-001"}' ``` **Steps to generate the final signature** 1. Encrypt the unsigned string with HMAC SHA256 using your secretKey - Signature = hmac_sha256(secretkey, Message) 2. Encode the signature using Base64 - Signature = base64.encode(Signature) --- ## Document: Cancel All Open Orders (TRADE) URL: /api-doc/contract/Transaction_API/CancelAllOrders # Cancel All Open Orders (TRADE) - **DELETE** ```/capi/v3/allOpenOrders``` Weight(IP): 5
**Request parameters** | Parameter | Type | Required? | Description | |-----------|--------|-----------|-------------| | symbol | String | No | Trading pair to filter. Omit to cancel all open orders across symbols. |
**Request example** ```powershell curl -X DELETE "https://api-contract.weex.com/capi/v3/allOpenOrders?symbol=BTCUSDT" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ ```
**Response parameters** Returns an array of entries with the following fields: | Field | Type | Description | |--------------|---------|-------------| | orderId | Long | ID of the cancelled order. | | success | Boolean | Whether this order was successfully cancelled. | | errorCode | String | Error code when `success = false`. | | errorMessage | String | Error message when `success = false`. |
**Response example** ```json [ { "orderId": 702345678901234567, "success": true, "errorCode": "", "errorMessage": "" } ] ```
--- ## Document: Cancel All Conditional Orders (TRADE) URL: /api-doc/contract/Transaction_API/CancelAllPendingOrders # Cancel All Conditional Orders (TRADE) - **DELETE** ```/capi/v3/algoOpenOrders``` Weight(IP): 5
**Request parameters** | Parameter | Type | Required? | Description | |-----------|--------|-----------|-------------| | symbol | String | No | Trading pair filter. Omit to cancel all conditional orders. |
**Request example** ```powershell curl -X DELETE "https://api-contract.weex.com/capi/v3/algoOpenOrders?symbol=BTCUSDT" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ ```
**Response parameters** Returns an array of objects with the fields below: | Field | Type | Description | |--------------|---------|-------------| | orderId | Long | Conditional order ID. | | success | Boolean | Whether the cancel succeeded. | | errorCode | String | Error code when `success = false`. | | errorMessage | String | Error description when `success = false`. |
**Response example** ```json [ { "orderId": 712345678901234567, "success": true, "errorCode": "", "errorMessage": "" } ] ```
--- ## Document: Cancel Order (TRADE) URL: /api-doc/contract/Transaction_API/CancelOrder # Cancel Order (TRADE) - **DELETE** ```/capi/v3/order``` Weight(IP): 1
**Request parameters** | Parameter | Type | Required? | Description | |-------------------|--------|-----------|-------------| | orderId | Long | Conditional | Target order ID. Required when `origClientOrderId` is not provided. | | origClientOrderId | String | Conditional | Client order ID, 1-36 characters. Required when `orderId` is not provided. |
**Request example** ```powershell curl -X DELETE "https://api-contract.weex.com/capi/v3/order?orderId=702345678901234567" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ ```
**Response parameters** | Field | Type | Description | |-------------------|---------|-------------| | orderId | String | Cancelled order ID. | | origClientOrderId | String | Client order ID (if provided). | | success | Boolean | Whether the cancel request succeeded. | | errorCode | String | Error code when `success = false`. | | errorMessage | String | Error description when `success = false`. |
**Response example** ```json { "orderId": "702345678901234567", "origClientOrderId": "my-order-0001", "success": true, "errorCode": "", "errorMessage": "" } ```
--- ## Document: Cancel Orders Batch (TRADE) URL: /api-doc/contract/Transaction_API/CancelOrdersBatch # Cancel Orders Batch (TRADE) - **DELETE** ```/capi/v3/batchOrders``` Weight(IP): 5
**Request parameters** | Parameter | Type | Required? | Description | |-----------------------|-----------------|-------------|-----------------------------------------------------------------------------------------------------------------| | orderIdList | `Array` | Conditional | Up to 10 order IDs to cancel. Required when `origClientOrderIdList` is empty. | | origClientOrderIdList | `Array` | Conditional | Up to 10 client order IDs. Each must match `^[\\.A-Z\:/a-z0-9_-]{1,36}$`. Required when `orderIdList` is empty. |
**Request example** ```powershell curl -X DELETE "https://api-contract.weex.com/capi/v3/batchOrders" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "Content-Type: application/json" \ -d '{ "orderIdList": [702345678901234567, 702345678901234568] }' ```
**Response parameters** Returns an array of objects that follow the schema described in [Cancel Order (TRADE)](/api-doc/contract/Transaction_API/CancelOrder).
**Response example** ```json [ { "orderId": "702345678901234567", "origClientOrderId": "", "success": true, "errorCode": "", "errorMessage": "" }, { "orderId": "702345678901234568", "origClientOrderId": "", "success": false, "errorCode": "ORDER_NOT_FOUND", "errorMessage": "orderId not exist" } ] ```
--- ## Document: Cancel Conditional Order (TRADE) URL: /api-doc/contract/Transaction_API/CancelPendingOrder # Cancel Conditional Order (TRADE) - **DELETE** ```/capi/v3/algoOrder``` Weight(IP): 1
**Request parameters** | Parameter | Type | Required? | Description | |-----------|------|-----------|-------------| | orderId | Long | Yes | Conditional order ID to cancel. |
**Request example** ```powershell curl -X DELETE "https://api-contract.weex.com/capi/v3/algoOrder?orderId=712345678901234567" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ ```
**Response parameters** Identical to the schema described in [Cancel Order (TRADE)](/api-doc/contract/Transaction_API/CancelOrder#response-parameters).
**Response example** ```json { "orderId": "712345678901234567", "origClientOrderId": "", "success": true, "errorCode": "", "errorMessage": "" } ```
--- ## Document: Close Positions (TRADE) URL: /api-doc/contract/Transaction_API/ClosePositions # Close Positions (TRADE) - **POST** ```/capi/v3/closePositions``` Weight(IP): 40
**Request parameters** | Parameter | Type | Required? | Description | |--------------|--------|-------------|------------------------| | symbol | String | No | Trading pair to close. | | positionId | Long | No | Position ID. | - When both `symbol` and `positionId` are provided, the system closes the position specified by `positionId`, and verifies that the position belongs to the trading pair specified by `symbol`. If the verification fails, the request is rejected. - When both `symbol` and `positionId` are empty, the system closes all open positions in the account. - When only `symbol` is provided, the system closes all positions under the specified trading pair (`symbol`), including both long and short positions. - When only `positionId` is provided, the system closes the position corresponding to the specified position ID (`positionId`).
**Request example** ```powershell curl -X POST "https://api-contract.weex.com/capi/v3/closePositions" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "Content-Type: application/json" \ -d '{ "symbol": "BTCUSDT" }' ```
**Response parameters** Returns an array of objects with the fields below: | Field | Type | Description | |----------------|---------|-------------| | positionId | Long | Position identifier. | | success | Boolean | Whether the close action succeeded. | | successOrderId | Long | Order ID created to close the position (when successful). | | errorMessage | String | Failure reason when `success = false`. |
**Response example** ```json [ { "positionId": 689987235755328154, "success": true, "successOrderId": 702345678901234580, "errorMessage": "" } ] ```
--- ## Document: Get Current Orders (USER_DATA) URL: /api-doc/contract/Transaction_API/GetCurrentOrderStatus # Get Current Orders (USER_DATA) - **GET** ```/capi/v3/openOrders``` Weight(IP): 2
**Request parameters** | Parameter | Type | Required? | Description | |-----------|--------|-----------|-------------| | symbol | String | No | Filter by trading pair. | | orderId | String | No | Only return orders with ID greater than the specified value. | | startTime | Long | No | Filter orders created after this timestamp (ms). | | endTime | Long | No | Filter orders created before this timestamp (ms). | | limit | Integer| No | Page size, 1-100. Default 100. | | page | Integer| No | Page index starting from 0. Default 0. |
**Request example** ```powershell curl "https://api-contract.weex.com/capi/v3/openOrders?symbol=BTCUSDT&limit=50&page=0" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ ```
**Response parameters** Returns an array of objects identical to [Get Order Info](/api-doc/contract/Transaction_API/GetSingleOrderInfo#response-parameters).
**Response example** ```json [ { "avgPrice": "0", "clientOrderId": "open-1", "cumQuote": "0", "executedQty": "0", "orderId": 702345678901234600, "origQty": "0.02", "price": "69500", "reduceOnly": false, "side": "SELL", "positionSide": "SHORT", "status": "NEW", "stopPrice": "0", "symbol": "BTCUSDT", "time": 1764505800000, "timeInForce": "GTC", "type": "LIMIT", "updateTime": 1764505800000, "workingType": "CONTRACT_PRICE", "priceProtect": false, "priceMatch": "NONE", "selfTradePreventionMode": "NONE", "goodTillDate": 0 } ] ```
--- ## Document: Get Current Conditional Orders (USER_DATA) URL: /api-doc/contract/Transaction_API/GetCurrentPendingOrders # Get Current Conditional Orders (USER_DATA) - **GET** ```/capi/v3/openAlgoOrders``` Weight(IP): 3
**Request parameters** | Parameter | Type | Required? | Description | |-----------|---------|-----------|-------------| | symbol | String | No | Trading pair filter. | | startTime | Long | No | Start time (ms). | | endTime | Long | No | End time (ms). Must be ≥ `startTime`. | | page | Integer | No | Page number starting from 1. Default 1. | | limit | Integer | No | Page size, 1-100. Default 100. |
**Request example** ```powershell curl "https://api-contract.weex.com/capi/v3/openAlgoOrders?symbol=BTCUSDT&page=1&limit=50" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ ```
**Response parameters** Returns an array of conditional orders with the fields below: | Field | Type | Description | |---------------------|---------|-------------| | algoId | Long | Conditional order ID. | | clientAlgoId | String | Client-defined ID. | | algoType | String | Conditional order category. Currently only `CONDITIONAL` is returned. | | orderType | String | Triggered order type. Values: `STOP`, `TAKE_PROFIT`, `STOP_MARKET`, `TAKE_PROFIT_MARKET`, `TRAILING_STOP_MARKET`. | | symbol | String | Trading pair. | | side | String | Order side. Values: `BUY`, `SELL`. | | positionSide | String | Position side. Values: `LONG`, `SHORT`. | | timeInForce | String | Time-in-force for the triggered order. Values: `GTC`, `IOC`, `FOK`, `POST_ONLY`. | | quantity | String | Requested quantity. | | algoStatus | String | Conditional order status. Values: `NEW`, `PENDING`, `UNTRIGGERED`, `FILLED`, `CANCELED`, `CANCELING`. | | actualOrderId | Long | ID of the triggered active order (if any). | | actualPrice | String | Execution price (if triggered). | | triggerPrice | String | Trigger price. | | price | String | Execution price configured for the triggered order. | | tpTriggerPrice | String | Linked take-profit trigger price (if configured). | | tpPrice | String | Linked take-profit execution price (if configured). | | slTriggerPrice | String | Linked stop-loss trigger price (if configured). | | slPrice | String | Linked stop-loss execution price (if configured). | | tpOrderType | String | Take-profit trigger price source. Values: `CONTRACT_PRICE`, `MARK_PRICE`. | | workingType | String | Trigger price source. Values: `CONTRACT_PRICE`, `MARK_PRICE`. | | closePosition | Boolean | Whether the triggered order will close the entire position. | | reduceOnly | Boolean | Whether the triggered order is reduce-only. | | createTime | Long | Creation time (ms). | | updateTime | Long | Last update time (ms). | | triggerTime | Long | Trigger time (ms). Returns `0` if the order has not been triggered. |
**Response example** ```json [ { "algoId": 812345678901234500, "clientAlgoId": "algo-20240201-1", "algoType": "CONDITIONAL", "orderType": "STOP", "symbol": "BTCUSDT", "side": "BUY", "positionSide": "LONG", "timeInForce": "GTC", "quantity": "0.01", "algoStatus": "UNTRIGGERED", "actualOrderId": null, "actualPrice": "0", "triggerPrice": "68900", "price": "68800", "tpTriggerPrice": "70500", "tpPrice": "70500", "slTriggerPrice": "68000", "slPrice": "0", "tpOrderType": "MARK_PRICE", "workingType": "MARK_PRICE", "closePosition": false, "reduceOnly": false, "createTime": 1764505800123, "updateTime": 1764505800123, "triggerTime": 0 } ] ```
--- ## Document: Get Current Trailing Orders (USER_DATA) URL: /api-doc/contract/Transaction_API/GetCurrentTrailingOrders # Get Current Trailing Orders (USER_DATA) - **GET** ```/capi/v3/trailing/openOrders``` Weight(IP): 2
**Request parameters** | Parameter | Type | Required? | Description | |-----------|--------|-----------|-------------| | symbol | String | No | Filter by trading pair. | | orderId | String | No | Only return orders with ID greater than the specified value. | | startTime | Long | No | Filter orders created after this timestamp (ms). | | endTime | Long | No | Filter orders created before this timestamp (ms). | | limit | Integer| No | Page size, 1-100. Default 100. | | page | Integer| No | Page index starting from 0. Default 0. |
**Request example** ```powershell curl "https://api-contract.weex.com/capi/v3/trailing/openOrders?symbol=BTCUSDT&limit=50&page=0" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ ```
**Response parameters** Returns an array of objects identical to [Get Order Info](/api-doc/contract/Transaction_API/GetSingleOrderInfo#response-parameters), with the following trailing order fields. | Field | Type | Description | |---------------|--------|-------------| | activatePrice | String | Activation price. This field is returned when available. | | callbackRate | String | Callback rate percentage. This field is returned when available. |
**Response example** ```json [ { "avgPrice": "0.00000", "clientOrderId": "trail-open-1", "cumQuote": "0", "executedQty": "0", "orderId": 775106388773831578, "origQty": "0.6", "price": "0.00", "reduceOnly": false, "side": "BUY", "positionSide": "LONG", "status": "UNACTIVATED", "stopPrice": "0", "symbol": "SOLUSDT", "time": 1784799763863, "timeInForce": "IOC", "type": "TRAILING_MARKET", "updateTime": 1784799763863, "workingType": "CONTRACT_PRICE", "activatePrice": "70.00", "callbackRate": "0.0500" } ] ```
--- ## Document: Get Conditional Order History (USER_DATA) URL: /api-doc/contract/Transaction_API/GetHistoricalPendingOrders # Get Conditional Order History (USER_DATA) - **GET** ```/capi/v3/allAlgoOrders``` Weight(IP): 5
**Request parameters** | Parameter | Type | Required? | Description | |-------------|---------|------------|-------------------------------------------------------| | symbol | String | No | Trading pair filter. | | startTime | Long | No | Start time (ms). | | endTime | Long | No | End time (ms). Must be within 90 days of `startTime`. | | limit | Integer | No | Page size, 1-1000. Default 500. |
**Request example** ```powershell curl "https://api-contract.weex.com/capi/v3/allAlgoOrders?symbol=BTCUSDT&limit=200" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ ```
**Response parameters** | Field | Type | Description | |----------|--------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------| | orders | `Array` | Current page of conditional orders. Each element follows the schema described in [Get Current Conditional Orders](/api-doc/contract/Transaction_API/GetCurrentPendingOrders). | | hasMore | Boolean | `true` if more data is available. |
**Response example** ```json { "orders": [ { "algoId": 812345678901234500, "clientAlgoId": "algo-20240201-1", "algoType": "PLAN", "orderType": "STOP", "symbol": "BTCUSDT", "side": "BUY", "positionSide": "LONG", "timeInForce": "GTC", "quantity": "0.01", "algoStatus": "TRIGGERED", "actualOrderId": 702345678901234700, "actualPrice": "68850", "triggerPrice": "68900", "price": "68800", "workingType": "MARK_PRICE", "createTime": 1764505800123, "updateTime": 1764506000456, "triggerTime": 1764506000123 } ], "hasMore": false } ```
--- ## Document: Get Order History (USER_DATA) URL: /api-doc/contract/Transaction_API/GetOrderHistory # Get Order History (USER_DATA) - **GET** ```/capi/v3/order/history``` Weight(IP): 10
**Request parameters** | Parameter | Type | Required? | Description | |-----------|---------|-----------|-------------| | symbol | String | No | Filter by trading pair. | | limit | Integer | No | Number of records per page, 1-1000. Default 500. | | startTime | Long | No | Start time (ms). Must be less than or equal to `endTime`. | | endTime | Long | No | End time (ms). Must be within 90 days of `startTime`. | | page | Integer | No | Page index starting from 0. Default 0. |
**Request example** ```powershell curl "https://api-contract.weex.com/capi/v3/order/history?symbol=BTCUSDT&limit=200&page=0" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ ```
**Response parameters** Returns an array of objects identical to [Get Order Info](/api-doc/contract/Transaction_API/GetSingleOrderInfo#response-parameters).
**Response example** ```json [ { "orderId": 702345678901234567, "symbol": "BTCUSDT", "side": "BUY", "positionSide": "LONG", "status": "FILLED", "type": "LIMIT", "time": 1764400000000, "price": "65000", "origQty": "0.01", "executedQty": "0.01", "avgPrice": "64999.5", "updateTime": 1764400001234, "clientOrderId": "hist-1", "cumQuote": "649.995", "timeInForce": "GTC" } ] ```
--- ## Document: Get Order Info (USER_DATA) URL: /api-doc/contract/Transaction_API/GetSingleOrderInfo # Get Order Info (USER_DATA) - **GET** ```/capi/v3/order``` Weight(IP): 2
**Request parameters** | Parameter | Type | Required? | Description | |-----------|------|-----------|-------------| | orderId | Long | Yes | Order ID to query. |
**Request example** ```powershell curl "https://api-contract.weex.com/capi/v3/order?orderId=702345678901234567" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ ```
**Response parameters** | Field | Type | Description | |---------------------------|-----------|----------------------------------------------------------------------------| | avgPrice | String | Average fill price. | | clientOrderId | String | Client-defined order ID. | | cumQuote | String | Cumulative filled amount in the quote asset. | | executedQty | String | Filled quantity in the base asset. | | orderId | Long | System order ID. | | origQty | String | Original order quantity. | | price | String | Order price. | | reduceOnly | Boolean | Whether the order can only reduce positions. | | side | String | Order side. See [Order Side](../APIPublicParameters.md#enum-definitions) for possible values. | | positionSide | String | Position side. See [Position Mode](../APIPublicParameters.md#enum-definitions). | | status | String | Order status. See [Order Status](../APIPublicParameters.md#enum-definitions). | | stopPrice | String | Stop price / trigger price (if applicable). | | symbol | String | Trading pair. | | time | Long | Order creation time (ms). | | timeInForce | String | Time-in-force policy. See [Time in Force](../APIPublicParameters.md#enum-definitions). | | type | String | Order type. See [Order Type](../APIPublicParameters.md#enum-definitions). | | updateTime | Long | Last update time (ms). | | workingType | String | Trigger price type. See [Trigger Price Type](../APIPublicParameters.md#enum-definitions). |
**Response example** ```json { "avgPrice": "68990.5", "clientOrderId": "my-order-0001", "cumQuote": "689.905", "executedQty": "0.01", "orderId": 702345678901234567, "origQty": "0.01", "price": "69000", "reduceOnly": false, "side": "BUY", "positionSide": "LONG", "status": "FILLED", "stopPrice": "0", "symbol": "BTCUSDT", "time": 1764505700123, "timeInForce": "GTC", "type": "LIMIT", "updateTime": 1764505701456, "workingType": "CONTRACT_PRICE" } ```
--- ## Document: Get Trade Details (USER_DATA) URL: /api-doc/contract/Transaction_API/GetTradeDetails # Get Trade Details (USER_DATA) - **GET** ```/capi/v3/userTrades``` Weight(IP): 5
**Request parameters** | Parameter | Type | Required? | Description | |-----------|---------|-----------|-------------| | symbol | String | No | Trading pair filter. | | orderId | Long | No | Only return trades associated with this order. | | startTime | Long | No | Start time (ms). | | endTime | Long | No | End time (ms). Must be ≥ `startTime`. | | limit | Integer | No | Number of records (1-100). Default 100. | **Notes** - If `startTime` and `endTime` are both not sent, then the last 7 days' data will be returned. - The time between `startTime` and `endTime` cannot be longer than 7 days. - Only support querying trade in the past 365 days.
**Request example** ```powershell curl "https://api-contract.weex.com/capi/v3/userTrades?symbol=BTCUSDT&limit=50" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ ```
**Response parameters** | Field | Type | Description | |------------------|---------|-------------| | id | Long | Trade ID. | | orderId | Long | Associated order ID. | | symbol | String | Trading pair. | | buyer | Boolean | Whether the user was the buyer. | | commission | String | Commission amount. | | commissionAsset | String | Asset used to pay commission. | | maker | Boolean | `true` if maker, `false` if taker. | | price | String | Trade price. | | qty | String | Filled quantity (base asset). | | quoteQty | String | Filled amount (quote asset). | | realizedPnl | String | Realised PnL for this fill. | | side | String | Order side, `BUY` or `SELL`. | | positionSide | String | Position side, `LONG` or `SHORT`. | | time | Long | Trade time (ms). |
**Response example** ```json [ { "id": 801234567890123456, "orderId": 702345678901234567, "symbol": "BTCUSDT", "buyer": true, "commission": "0.138", "commissionAsset": "USDT", "maker": false, "price": "69000", "qty": "0.01", "quoteQty": "690", "realizedPnl": "0", "side": "BUY", "positionSide": "LONG", "time": 1764505701456 } ] ```
--- ## Document: Get Trailing Order History (USER_DATA) URL: /api-doc/contract/Transaction_API/GetTrailingOrderHistory # Get Trailing Order History (USER_DATA) - **GET** ```/capi/v3/trailing/historyOrders``` Weight(IP): 10
**Request parameters** | Parameter | Type | Required? | Description | |-----------|---------|-----------|-------------| | symbol | String | No | Filter by trading pair. | | limit | Integer | No | Number of records per page, 1-1000. Default 500. | | startTime | Long | No | Start time (ms). Must be less than or equal to `endTime`. | | endTime | Long | No | End time (ms). Must be within 90 days of `startTime`. | | page | Integer | No | Page index starting from 0. Default 0. |
**Request example** ```powershell curl "https://api-contract.weex.com/capi/v3/trailing/historyOrders?symbol=BTCUSDT&limit=200&page=0" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ ```
**Response parameters** Returns an array of objects identical to [Get Order Info](/api-doc/contract/Transaction_API/GetSingleOrderInfo#response-parameters), with the following trailing order fields. | Field | Type | Description | |---------------|--------|-------------| | activatePrice | String | Activation price. This field is returned when available. | | callbackRate | String | Callback rate percentage. This field is returned when available. |
**Response example** ```json [ { "avgPrice": "0.00000", "clientOrderId": "trail-hist-1", "cumQuote": "0", "executedQty": "0", "orderId": 775106388773831578, "origQty": "0.6", "price": "0.00", "reduceOnly": false, "side": "BUY", "positionSide": "LONG", "status": "UNACTIVATED", "stopPrice": "0", "symbol": "SOLUSDT", "time": 1784799763863, "timeInForce": "IOC", "type": "TRAILING_MARKET", "updateTime": 1784799763863, "workingType": "CONTRACT_PRICE", "activatePrice": "70.00", "callbackRate": "0.0500" } ] ```
--- ## Document: Trade URL: /api-doc/contract/Transaction_API # Trade --- ## Document: Modify TP/SL Conditional Order (TRADE) URL: /api-doc/contract/Transaction_API/ModifyTpSlOrder # Modify TP/SL Conditional Order (TRADE) - **POST** ```/capi/v3/modifyTpSlOrder``` **Request Weight** 1 on 10s order rate limit(X-ORDER-COUNT-10S); 1 on 1min order rate limit(X-ORDER-COUNT-1M); 0 on IP rate limit(X-USED-WEIGHT-1M);
**Request parameters** | Parameter | Type | Required? | Description | |------------------|--------|-----------|-------------| | orderId | Long | Yes | Conditional order ID to modify. | | triggerPrice | String | Yes | New trigger price (> 0). | | executePrice | String | Conditional | New execution price. Set to `0` or omit to switch to market execution. Copy-trading API keys only support market close, so this field must be `0` or omitted. | | triggerPriceType | String | No | Trigger price source. `CONTRACT_PRICE` or `MARK_PRICE`. Default `CONTRACT_PRICE`. |
**Request example** ```powershell curl -X POST "https://api-contract.weex.com/capi/v3/modifyTpSlOrder" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "Content-Type: application/json" \ -d '{ "orderId": 812345678901234900, "triggerPrice": "71000", "executePrice": "71000", "triggerPriceType": "MARK_PRICE" }' ```
**Response parameters** | Field | Type | Description | |---------|---------|-------------| | success | Boolean | Whether the modification was accepted. |
**Response example** ```json { "success": true } ```
--- ## Document: Place Order (TRADE) URL: /api-doc/contract/Transaction_API/PlaceOrder # Place Order (TRADE) - **POST** ```/capi/v3/order``` **Request Weight** 1 on 10s order rate limit(X-ORDER-COUNT-10S); 1 on 1min order rate limit(X-ORDER-COUNT-1M); 0 on IP rate limit(X-USED-WEIGHT-1M);
**Request parameters** | Parameter | Type | Required? | Description | |------------------|---------|-------------|---------------------------------------------------------------------------------------------------------------| | symbol | String | Yes | Trading pair, for example `BTCUSDT`. | | side | String | Yes | Order side. Supported values: `BUY`, `SELL`. | | positionSide | String | Yes | Position side. Supported values: `LONG`, `SHORT`. | | type | String | Yes | Order type. Supported values: `LIMIT`, `MARKET`. | | timeInForce | String | Conditional | Time-in-force policy. Required when `type = LIMIT`. Supported values: `GTC`, `IOC`, `FOK`, `POST_ONLY`. | | quantity | String | Yes | Order quantity. Must be greater than 0. | | price | String | Conditional | Limit price. Required when `type = LIMIT`. | | newClientOrderId | String | Yes | Client order identifier (1-36 characters, pattern `^[\\.A-Z\:/a-z0-9_-]{1,36}$`). | | tpTriggerPrice | String | No | Optional take-profit trigger price. | | slTriggerPrice | String | No | Optional stop-loss trigger price. | | TpWorkingType | String | No | Take-profit trigger price source. Supported values: `CONTRACT_PRICE`, `MARK_PRICE`. Default `CONTRACT_PRICE`. | | SlWorkingType | String | No | Stop-loss trigger price source. Supported values: `CONTRACT_PRICE`, `MARK_PRICE`. Default `CONTRACT_PRICE`. | | reduceOnly | Boolean | No | Whether the order is reduce-only. |
**Request example** ```powershell curl -X POST "https://api-contract.weex.com/capi/v3/order" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "Content-Type: application/json" \ -d '{ "symbol": "BTCUSDT", "side": "BUY", "positionSide": "LONG", "type": "LIMIT", "timeInForce": "GTC", "quantity": "0.01", "price": "69000", "newClientOrderId": "my-order-0001", "tpTriggerPrice": "70000", "slTriggerPrice": "68000", "TpWorkingType": "CONTRACT_PRICE", "SlWorkingType": "MARK_PRICE", "reduceOnly": false }' ```
**Response parameters** | Field | Type | Description | |----------------|---------|-------------| | orderId | String | Order ID assigned by the system. | | clientOrderId | String | Echo of `newClientOrderId`. | | success | Boolean | Whether the order request was accepted. | | errorCode | String | Error code when `success = false`; otherwise empty. | | errorMessage | String | Error message when `success = false`; otherwise empty. |
**Response example** ```json { "orderId": "702345678901234567", "clientOrderId": "my-order-0001", "success": true, "errorCode": "", "errorMessage": "" } ```
--- ## Document: Place Orders Batch (TRADE) URL: /api-doc/contract/Transaction_API/PlaceOrdersBatch # Place Orders Batch (TRADE) - **POST** ```/capi/v3/batchOrders``` **Request Weight** 5 on 10s order rate limit(X-ORDER-COUNT-10S); 5 on 1min order rate limit(X-ORDER-COUNT-1M); 0 on IP rate limit(X-USED-WEIGHT-1M);
**Request parameters** | Parameter | Type | Required? | Description | |---------------|---------------------|-------------|-------------------------------------------------------------------------------------------------------------------------------| | batchOrders | `Array` | Yes | Up to 5 orders per request. Each element uses the same fields as [Place Order (TRADE)](/api-doc/contract/Transaction_API/PlaceOrder). |










**Request example** ```powershell curl -X POST "https://api-contract.weex.com/capi/v3/batchOrders" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "Content-Type: application/json" \ -d '{ "batchOrders": [ { "symbol": "BTCUSDT", "side": "BUY", "positionSide": "LONG", "type": "LIMIT", "timeInForce": "GTC", "quantity": "0.01", "price": "69000", "newClientOrderId": "batch-1", "reduceOnly": false } ] }' ```
**Response parameters** A JSON array where each element matches the response schema of [Place Order (TRADE)](/api-doc/contract/Transaction_API/PlaceOrder).
**Response example** ```json [ { "orderId": "702345678901234567", "clientOrderId": "batch-1", "success": true, "errorCode": "", "errorMessage": "" } ] ```
--- ## Document: Place Conditional Order (TRADE) URL: /api-doc/contract/Transaction_API/PlacePendingOrder # Place Conditional Order (TRADE) - **POST** ```/capi/v3/algoOrder``` **Request Weight** 1 on 10s order rate limit(X-ORDER-COUNT-10S); 1 on 1min order rate limit(X-ORDER-COUNT-1M); 0 on IP rate limit(X-USED-WEIGHT-1M);
**Request parameters** | Parameter | Type | Required? | Description | |-------------------------|--------|-----------|-------------| | symbol | String | Yes | Trading pair, e.g. `BTCUSDT`. | | side | String | Yes | Order side. Values: `BUY`, `SELL`. | | positionSide | String | Yes | Position side. Values: `LONG`, `SHORT`. | | type | String | Yes | Conditional order type. Values: `STOP`, `TAKE_PROFIT`, `STOP_MARKET`, `TAKE_PROFIT_MARKET`, `TRAILING_MARKET`. | | quantity | String | Yes | Order quantity. Must be > 0. | | price | String | Conditional | Execution price. Required when `type` is `STOP` or `TAKE_PROFIT`. | | triggerPrice | String | Conditional | Trigger price. Required when `type` is `STOP`, `TAKE_PROFIT`, `STOP_MARKET`, or `TAKE_PROFIT_MARKET`. | | clientAlgoId | String | Yes | Client-defined identifier (1-36 characters, pattern `^[\\.A-Z\:/a-z0-9_-]{1,36}$`). | | presetTakeProfitPrice | String | No | Optional take-profit trigger price. | | presetStopLossPrice | String | No | Optional stop-loss trigger price. | | TpWorkingType | String | No | Take-profit trigger type: `CONTRACT_PRICE` or `MARK_PRICE`. Default `CONTRACT_PRICE`. | | SlWorkingType | String | No | Stop-loss trigger type: `CONTRACT_PRICE` or `MARK_PRICE`. Default `CONTRACT_PRICE`. | | activatePrice | String | No | Trailing stop activation price. Only valid when `type = TRAILING_MARKET`. If omitted, the current market price is used based on `workingType`. | | callbackRate | String | Conditional | Trailing stop callback rate. Required when `type = TRAILING_MARKET`. Range: `[0.001, 0.9999]`. | | workingType | String | No | Price type used for trailing activation and callback. Values: `CONTRACT_PRICE`, `MARK_PRICE`. Default `CONTRACT_PRICE`. | | reduceOnly | Boolean | No | Whether the order is reduce-only. |
**Request example** ```powershell curl -X POST "https://api-contract.weex.com/capi/v3/algoOrder" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "Content-Type: application/json" \ -d '{ "symbol": "BTCUSDT", "side": "BUY", "positionSide": "LONG", "type": "STOP", "quantity": "0.01", "price": "68800", "triggerPrice": "68900", "clientAlgoId": "algo-20240201-1", "presetTakeProfitPrice": "70500", "presetStopLossPrice": "68000", "TpWorkingType": "MARK_PRICE", "reduceOnly": false }' ```
**Response parameters** Identical to the schema described in [Place Order (TRADE)](/api-doc/contract/Transaction_API/PlaceOrder).
**Response example** ```json { "orderId": "702345678901234700", "clientOrderId": "algo-20240201-1", "success": true, "errorCode": "", "errorMessage": "" } ```
--- ## Document: Place TP/SL Conditional Orders (TRADE) URL: /api-doc/contract/Transaction_API/PlaceTpSlOrder # Place TP/SL Conditional Orders (TRADE) - **POST** ```/capi/v3/placeTpSlOrder``` **Request Weight** 1 on 10s order rate limit(X-ORDER-COUNT-10S); 1 on 1min order rate limit(X-ORDER-COUNT-1M); 0 on IP rate limit(X-USED-WEIGHT-1M);
**Request parameters** | Parameter | Type | Required? | Description | |---------------------|--------|-------------|-------------------------------------------------------------------------------------| | symbol | String | Yes | Trading pair. | | clientAlgoId | String | Yes | Client-defined identifier (1-36 characters, pattern `^[\\.A-Z\:/a-z0-9_-]{1,36}$`). | | planType | String | Yes | Plan type. Values: `TAKE_PROFIT`, `STOP_LOSS`. | | triggerPrice | String | Yes | Trigger price (> 0). | | executePrice | String | Conditional | Execution price. Set to `0` or omit for market execution. Copy-trading API keys only support market close, so this field must be `0` or omitted. | | quantity | String | No | Quantity to execute. Set to `0` or omit to set TP/SL for the full position. Copy-trading API keys must close the full position, so this field must be `0` or omitted. | | positionSide | String | Yes | Position side (`LONG`, `SHORT`). | | triggerPriceType | String | No | Trigger source. `CONTRACT_PRICE` or `MARK_PRICE`. Default `CONTRACT_PRICE`. | | reduceOnly | Boolean | No | Whether the order is reduce-only. |
**Request example** ```powershell curl -X POST "https://api-contract.weex.com/capi/v3/placeTpSlOrder" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "Content-Type: application/json" \ -d '{ "symbol": "BTCUSDT", "clientAlgoId": "tp-20240201-1", "planType": "TAKE_PROFIT", "triggerPrice": "70500", "executePrice": "70500", "quantity": "0.01", "positionSide": "LONG", "triggerPriceType": "MARK_PRICE", "reduceOnly": false }' ```
**Response parameters** Returns an array of objects with the following fields: | Field | Type | Description | |--------------|----------|-------------------------------------------| | success | Boolean | Whether the plan order was accepted. | | orderId | Long | Plan order ID when successful. | | errorCode | String | Error code when `success = false`. | | errorMessage | String | Error description when `success = false`. |
**Response example** ```json [ { "success": true, "orderId": 812345678901234900, "errorCode": "", "errorMessage": "" } ] ```
--- ## Document: Account Channel URL: /api-doc/contract/Websocket/private/Account-Channel # Account Channel **Description** Streams collateral balance changes for the authenticated account.
**Subscription Request Parameters** | Field | Type | Required | Description | |:-------|:---------------|:---------|:------------| | method | String | Yes | `SUBSCRIBE` or `UNSUBSCRIBE`. | | params | Array\ | Yes | Channel list. Use `account`. | | id | Number | Optional | Client-defined identifier echoed in the acknowledgement. |
**Subscription Request Example** ```json { "method": "SUBSCRIBE", "params": [ "account" ], "id": 11 } ```
**Acknowledgement** | Field | Type | Description | |:-------|:--------|:------------| | result | Boolean | `true` when the command succeeds. | | id | Number | Echo of the request id (if provided). | | msg | String | Error details when `result` is `false`. |
**Acknowledgement Example** ```json { "result": true, "id": 11 } ```
**Push Payload** | Field | Type | Description | |:------|:-----|:------------| | e | String | Event type, always `account`. | | E | Number | Event time in milliseconds. | | v | Number | Account version associated with the update. | | msgEvent | String | Upstream event label (for example `PositionFundingSettle`). | | d | Array\ | Collateral entries. | | > coin | String | Collateral asset (uppercase). | | > marginMode | String | Margin mode (`CROSSED`, `ISOLATED`). | | > crossSymbol | String | Associated symbol when in crossed mode; empty otherwise. | | > isolatedPositionId | String | Related position ID when in isolated mode. | | > amount | String | Available collateral amount. | | > pendingDepositAmount | String | Pending deposits. | | > pendingWithdrawAmount | String | Pending withdrawals. | | > pendingTransferInAmount | String | Pending transfer-in amount. | | > pendingTransferOutAmount | String | Pending transfer-out amount. | | > liquidating | Boolean | Whether the asset is under liquidation. | | > legacyAmount | String | Legacy balance (display only). | | > cumDepositAmount | String | Cumulative deposits. | | > cumWithdrawAmount | String | Cumulative withdrawals. | | > cumTransferInAmount | String | Cumulative transfer-ins. | | > cumTransferOutAmount | String | Cumulative transfer-outs. | | > cumMarginMoveInAmount | String | Cumulative margin move-ins. | | > cumMarginMoveOutAmount | String | Cumulative margin move-outs. | | > cumPositionOpenLongAmount | String | Cumulative collateral used to open long positions. | | > cumPositionOpenShortAmount | String | Cumulative collateral used to open short positions. | | > cumPositionCloseLongAmount | String | Cumulative collateral returned when closing longs. | | > cumPositionCloseShortAmount | String | Cumulative collateral returned when closing shorts. | | > cumPositionFillFeeAmount | String | Cumulative trading fees. | | > cumPositionLiquidateFeeAmount | String | Cumulative liquidation fees. | | > cumPositionFundingAmount | String | Cumulative funding payments (may be negative). | | > cumOrderFillFeeIncomeAmount | String | Cumulative fee income. | | > cumOrderLiquidateFeeIncomeAmount | String | Cumulative liquidation fee income. | | > createdTime | String | Record creation timestamp. | | > updatedTime | String | Last update timestamp. |
**Push Example** ```json { "e": "account", "E": 1773298961302, "v": 46571, "msgEvent": "PositionFundingSettle", "d": [ { "coin": "USDT", "marginMode": "CROSSED", "crossSymbol": "", "isolatedPositionId": "0", "amount": "6625267.708162", "pendingDepositAmount": "0.000000", "pendingWithdrawAmount": "0.000000", "pendingTransferInAmount": "0", "pendingTransferOutAmount": "0", "liquidating": false, "legacyAmount": "6628108.535375", "cumDepositAmount": "6850179.708361", "cumWithdrawAmount": "118.284985", "cumTransferInAmount": "151.912400", "cumTransferOutAmount": "0", "cumMarginMoveInAmount": "0", "cumMarginMoveOutAmount": "114.587618", "cumPositionOpenLongAmount": "3551408.796139", "cumPositionOpenShortAmount": "287685.101200", "cumPositionCloseLongAmount": "3406364.752975", "cumPositionCloseShortAmount": "287789.808420", "cumPositionFillFeeAmount": "32.199683", "cumPositionLiquidateFeeAmount": "76.930498", "cumPositionFundingAmount": "-5778.744009", "cumOrderFillFeeIncomeAmount": "0", "cumOrderLiquidateFeeIncomeAmount": "0", "createdTime": "1728493664997", "updatedTime": "1747188961302" } ] } ```
--- ## Document: Fill Channel URL: /api-doc/contract/Websocket/private/Fill-Channel # Fill Channel **Description** Streams real-time fill details for orders owned by the authenticated account.
**Subscription Request Parameters** | Field | Type | Required | Description | |:-------|:---------------|:---------|:------------| | method | String | Yes | `SUBSCRIBE` or `UNSUBSCRIBE`. | | params | Array\ | Yes | Channel list. Use `fill`. | | id | Number | Optional | Client-defined identifier echoed in the acknowledgement. |
**Subscription Request Example** ```json { "method": "SUBSCRIBE", "params": [ "fill" ], "id": 9 } ```
**Acknowledgement** | Field | Type | Description | |:-------|:--------|:------------| | result | Boolean | `true` when the subscription command succeeds. | | id | Number | Echo of the request id (if provided). | | msg | String | Error message when `result` is `false`. |
**Acknowledgement Example** ```json { "result": true, "id": 9 } ```
**Push Payload** | Field | Type | Description | |:------|:-----|:------------| | e | String | Event type, always `fill`. | | E | Number | Event time in milliseconds. | | v | Number | Account data version related to the update. | | msgEvent | String | Upstream event label (e.g. `OrderUpdate`). | | d | Array\ | Fill entries. | | > id | String | Fill ID. | | > coin | String | Collateral asset (uppercase). | | > symbol | String | Trading pair symbol (uppercase). | | > orderId | String | Parent order ID. | | > marginMode | String | Margin mode (`CROSSED`, `ISOLATED`). | | > separatedMode | String | Position mode (`COMBINED`, `SEPARATED`). | | > separatedOpenOrderId | String | Related separated opening order ID. | | > positionSide | String | Position side (`LONG`, `SHORT`, `UNKNOWN`). | | > orderSide | String | Order side for the fill (`BUY`, `SELL`). | | > fillSize | String | Filled quantity. | | > fillValue | String | Filled value. | | > fillFee | String | Trading fee for the fill. | | > liquidateFee | String | Liquidation fee, when applicable. | | > realizePnl | String | Realised PnL produced by the fill. | | > direction | String | Liquidity direction (`MAKER`, `TAKER`). | | > createdTime | String | Fill creation timestamp. | | > updatedTime | String | Last update timestamp. |
**Push Example** ```json { "e": "fill", "E": 1773295739154, "v": 46655, "msgEvent": "OrderUpdate", "d": [ { "id": "617414920887075482", "coin": "USDT", "symbol": "BTCUSDT", "orderId": "617414920861909658", "marginMode": "CROSSED", "separatedMode": "COMBINED", "separatedOpenOrderId": "0", "positionSide": "LONG", "orderSide": "BUY", "fillSize": "0.10000", "fillValue": "10381.270000", "fillFee": "6.228762", "liquidateFee": "0", "realizePnl": "0", "direction": "TAKER", "createdTime": "1747203188154", "updatedTime": "1747203188154" } ] } ```
--- ## Document: Order Channel URL: /api-doc/contract/Websocket/private/Order-Channel # Order Channel **Description** Streams real-time order lifecycle updates for the authenticated account.
**Subscription Request Parameters** | Field | Type | Required | Description | |:-------|:---------------|:---------|:------------| | method | String | Yes | `SUBSCRIBE` or `UNSUBSCRIBE`. | | params | Array\ | Yes | Channel list. Use `orders`. | | id | Number | Optional | Client-provided identifier echoed in the acknowledgement. |
**Subscription Request Example** ```json { "method": "SUBSCRIBE", "params": [ "orders" ], "id": 1 } ```
**Acknowledgement** | Field | Type | Description | |:-------|:--------|:------------| | result | Boolean | `true` when the command succeeds. | | id | Number | Echo of the request id, when provided. | | msg | String | Error information when `result` is `false`. |
**Acknowledgement Example** ```json { "result": true, "id": 1 } ```
**Push Payload** | Field | Type | Description | |:------|:-----|:------------| | e | String | Event type, always `orders`. | | E | Number | Event time in milliseconds. | | v | Number | Account version associated with the update. | | msgEvent | String | Upstream event name (for example `OrderUpdate`). | | d | Array\ | Updated order entries. | | > id | String | Order ID. | | > coin | String | Collateral asset (uppercase). | | > symbol | String | Trading pair symbol (uppercase, e.g. `BTCUSDT`). | | > marginMode | String | Margin mode (`CROSSED`, `ISOLATED`). | | > separatedMode | String | Position mode (`COMBINED`, `SEPARATED`). | | > separatedOpenOrderId | String | Related separated position creation order ID. | | > positionSide | String | Position side (`LONG`, `SHORT`, `UNKNOWN`). | | > orderSide | String | Order side (`BUY`, `SELL`). | | > price | String | Order price. | | > size | String | Order quantity. | | > clientOrderId | String | Client-specified identifier. | | > type | String | Order type (`LIMIT`, `MARKET`, `STOP`, `TAKE_PROFIT`, `STOP_MARKET`, `TAKE_PROFIT_MARKET`). | | > timeInForce | String | Time-in-force (`GTC`, `IOC`, `FOK`, `POST_ONLY`). | | > reduceOnly | Boolean | Whether the order is reduce-only. | | > triggerPrice | String | Trigger price when applicable. | | > triggerPriceType | String | Trigger price type (`CONTRACT_PRICE`, `MARK_PRICE`). | | > orderSource | String | Order source (for example `WEB`, `API`). | | > openTpslParentOrderId | String | Opening order ID for TP/SL orders. | | > positionTpsl | Boolean | Whether the order is a position TP/SL order. | | > setOpenTp | Boolean | Whether take-profit parameters were set. | | > setOpenSl | Boolean | Whether stop-loss parameters were set. | | > leverage | String | Leverage set when placing the order. | | > takerFeeRate | String | Taker fee rate. | | > makerFeeRate | String | Maker fee rate. | | > feeDiscount | String | Fee discount ratio. | | > liquidateFeeRate | String | Liquidation fee rate. | | > status | String | Order status (`NEW`, `PENDING`, `UNTRIGGERED`, `FILLED`, `CANCELED`, `CANCELING`, etc.). | | > triggerTime | String | Trigger time for conditional orders. | | > triggerPriceTime | String | Trigger price event time. | | > triggerPriceValue | String | Recorded trigger price. | | > cancelReason | String | Cancellation reason (enum label). | | > latestFillPrice | String | Latest fill price. | | > maxFillPrice | String | Maximum fill price. | | > minFillPrice | String | Minimum fill price. | | > cumFillSize | String | Cumulative filled quantity. | | > cumFillValue | String | Cumulative filled value. | | > cumFillFee | String | Cumulative trading fee. | | > cumLiquidateFee | String | Cumulative liquidation fee. | | > cumRealizePnl | String | Cumulative realised PnL. | | > createdTime | String | Order creation timestamp. | | > updatedTime | String | Last update timestamp. |
**Push Example** ```json { "e": "orders", "E": 1773295738939, "v": 46654, "msgEvent": "OrderUpdate", "d": [ { "id": "617414920861909658", "coin": "USDT", "symbol": "BTCUSDT", "marginMode": "CROSSED", "separatedMode": "COMBINED", "separatedOpenOrderId": "0", "positionSide": "LONG", "orderSide": "BUY", "price": "0.0", "size": "0.10000", "clientOrderId": "1747203186927FPIZRP", "type": "MARKET", "timeInForce": "IOC", "reduceOnly": false, "triggerPrice": "0", "triggerPriceType": "CONTRACT_PRICE", "orderSource": "WEB", "openTpslParentOrderId": "0", "positionTpsl": false, "setOpenTp": false, "setOpenSl": false, "leverage": "20", "takerFeeRate": "0.0006", "makerFeeRate": "0.0002", "feeDiscount": "1", "liquidateFeeRate": "0.01", "status": "PENDING", "triggerTime": "0", "triggerPriceTime": "0", "triggerPriceValue": "0", "cancelReason": "UNKNOWN_ORDER_CANCEL_REASON", "latestFillPrice": "0", "maxFillPrice": "0", "minFillPrice": "0", "cumFillSize": "0", "cumFillValue": "0", "cumFillFee": "0", "cumLiquidateFee": "0", "cumRealizePnl": "0", "createdTime": "1747203188148", "updatedTime": "1747203188148" } ] } ```
--- ## Document: Position Channel URL: /api-doc/contract/Websocket/private/Positions-Channel # Position Channel **Description** Streams position changes (quantity, funding, margin mode) for the authenticated account.
**Subscription Request Parameters** | Field | Type | Required | Description | |:-------|:---------------|:---------|:------------| | method | String | Yes | `SUBSCRIBE` or `UNSUBSCRIBE`. | | params | Array\ | Yes | Channel list. Use `positions`. | | id | Number | Optional | Client-specified identifier echoed in the acknowledgement. |
**Subscription Request Example** ```json { "method": "SUBSCRIBE", "params": [ "positions" ], "id": 7 } ```
**Acknowledgement** | Field | Type | Description | |:-------|:--------|:------------| | result | Boolean | `true` when the command succeeds. | | id | Number | Echo of the request id (if provided). | | msg | String | Error message when `result` is `false`. |
**Acknowledgement Example** ```json { "result": true, "id": 7 } ```
**Push Payload** | Field | Type | Description | |:------|:-----|:------------| | e | String | Event type, always `positions`. | | E | Number | Event time in milliseconds. | | v | Number | Account data version associated with the update. | | msgEvent | String | Upstream event label (e.g. `PositionFundingSettle`). | | d | Array\ | Updated position entries. | | > id | String | Position ID. | | > coin | String | Collateral asset (uppercase). | | > symbol | String | Trading pair symbol (uppercase). | | > side | String | Position side (`LONG`, `SHORT`, `UNKNOWN`). | | > marginMode | String | Margin mode (`CROSSED`, `ISOLATED`). | | > separatedMode | String | Position mode (`COMBINED`, `SEPARATED`). | | > separatedOpenOrderId | String | Related separated opening order ID. | | > leverage | String | Effective leverage. | | > size | String | Current position size. | | > openValue | String | Accumulated open value. | | > openFee | String | Accumulated opening fees. | | > fundingFee | String | Current funding accrual. | | > isolatedMargin | String | Isolated margin (zero in crossed mode). | | > autoAppendIsolatedMargin | Boolean | Auto add isolated margin flag. | | > cumOpenSize | String | Cumulative opened size. | | > cumOpenValue | String | Cumulative opened value. | | > cumOpenFee | String | Cumulative opened fees. | | > cumCloseSize | String | Cumulative closed size. | | > cumCloseValue | String | Cumulative closed value. | | > cumCloseFee | String | Cumulative closing fees. | | > cumFundingFee | String | Cumulative settled funding. | | > cumLiquidateFee | String | Cumulative liquidation fees. | | > createdMatchSequenceId | String | Matching engine sequence at creation. | | > updatedMatchSequenceId | String | Matching engine sequence at last update. | | > createdTime | String | Creation timestamp. | | > updatedTime | String | Last update timestamp. |
**Push Example** ```json { "e": "positions", "E": 1773298805123, "v": 55218, "msgEvent": "PositionFundingSettle", "d": [ { "id": "615193369903104410", "coin": "USDT", "symbol": "BTCUSDT", "side": "LONG", "marginMode": "CROSSED", "separatedMode": "COMBINED", "separatedOpenOrderId": "0", "leverage": "20", "size": "0.01000", "openValue": "992.405443", "openFee": "0.595443", "fundingFee": "157.475456", "isolatedMargin": "0", "autoAppendIsolatedMargin": false, "cumOpenSize": "0.55061", "cumOpenValue": "54642.836110", "cumOpenFee": "32.785700", "cumCloseSize": "0.54061", "cumCloseValue": "53666.138456", "cumCloseFee": "32.199683", "cumFundingFee": "163.232384", "cumLiquidateFee": "0", "createdMatchSequenceId": "3647905144", "updatedMatchSequenceId": "3656434385", "createdTime": "1746673529125", "updatedTime": "1747188961302" } ] } ```
--- ## Document: Candlestick Channel URL: /api-doc/contract/Websocket/public/Candlesticks-Channel # Candlestick Channel **Description** Streams candlestick (K-line) data for a contract. After a successful subscription the server pushes `kline` updates whenever the requested bar is created or refreshed.
**Subscription Request Parameters** | Field | Type | Required | Description | |:-------|:---------------|:---------|:------------| | method | String | Yes | `SUBSCRIBE` or `UNSUBSCRIBE`. | | params | Array\ | Yes | `@kline__`.
Examples: `BTCUSDT@kline_1m_LAST_PRICE`, `ETHUSDT@kline_1h_MARK_PRICE`. | | id | Number | Optional | Client identifier echoed in the acknowledgement. | **Interval Tokens** | Token | Description | |:------|:------------| | 1m | 1 minute | | 5m | 5 minutes | | 15m | 15 minutes | | 30m | 30 minutes | | 1h | 1 hour | | 2h | 2 hours | | 4h | 4 hours | | 6h | 6 hours | | 8h | 8 hours | | 12h | 12 hours | | 1d | 1 day | | 1w | 1 week | | 1M | 1 calendar month (note the uppercase `M`). | **Price Types** | Token | Description | |:------|:------------| | LAST_PRICE | Last trade price candles. | | MARK_PRICE | Mark price candles. |
**Subscription Request Example** ```json { "method": "SUBSCRIBE", "params": [ "ETHUSDT@kline_1m_LAST_PRICE" ], "id": 4 } ```
**Acknowledgement** | Field | Type | Description | |:-------|:--------|:------------| | result | Boolean | `true` when the operation succeeds. | | id | Number | Echo of the request id. | | msg | String | Error details when `result` is `false`. |
**Acknowledgement Example** ```json { "result": true, "id": 4 } ```
**Update Payload (`kline`)** | Field | Type | Description | |:------|:-----|:------------| | e | String | Event type, `kline`. | | E | Number | Event time (milliseconds). | | s | String | Trading pair in uppercase. | | p | String | Price type (e.g. `LAST_PRICE`). | | d | Array\ | Candle entries, usually containing the currently forming bar. | | > t | Number | Candle start time (milliseconds). | | > T | Number | Candle close time (milliseconds). | | > s | String | Trading pair. | | > i | String | Interval token exactly as subscribed (e.g. `1m`). | | > o | String | Open price. | | > c | String | Close price. | | > h | String | High price. | | > l | String | Low price. | | > v | String | Volume (base asset). | | > n | Number | Number of trades. | | > q | String | Quote asset volume. | | > V | String | Taker buy volume. | | > Q | String | Taker buy quote volume. |
**Update Example** ```json { "e": "kline", "E": 1773295738000, "s": "ETHUSDT", "p": "LAST_PRICE", "d": [ { "t": 1773295680000, "T": 1773295739999, "s": "ETHUSDT", "i": "1m", "o": "3572.10", "c": "3573.40", "h": "3574.00", "l": "3571.80", "v": "18.2", "n": 9, "q": "65035.88", "V": "9.4", "Q": "33590.96" } ] } ```
> **Interval tokens are case-sensitive.** `1m` (minutes) and `1M` (months) represent different bars. Use uppercase price types (e.g. `LAST_PRICE`) to avoid validation errors. --- ## Document: Depth Channel URL: /api-doc/contract/Websocket/public/Depth-Channel # Depth Channel **Description** Streams merged order book depth change events (`depth`) for the subscribed trading pair and level.
**Request Parameters** | Parameter | Type | Required | Description | |:----------|:---------------|:---------|:------------| | method | String | Yes | `SUBSCRIBE` to add, `UNSUBSCRIBE` to remove. | | params | Array\ | Yes | `@depth{level}`. Supported levels: `15`, `200`. Example: `BTCUSDT@depth15`. | | id | Number | Optional | Client-defined identifier echoed in the acknowledgement. |
**Request Example** ```json { "method": "SUBSCRIBE", "params": [ "BTCUSDT@depth15" ], "id": 2 } ```
**Response Parameters (Ack)** | Field | Type | Description | |:-------|:--------|:------------| | result | Boolean | `true` for success, `false` for failure. | | id | Number | Echo of the request `id`. | | msg | String | Error details when `result` is `false`. |
**Acknowledgement Example** ```json { "result": true, "id": 2 } ```
**Update Payload (`depth`)** | Field | Type | Description | |:------|:-----|:------------| | e | String | Event type, `depth`. | | E | Number | Event time (ms). | | s | String | Trading pair. | | U | Number | First update ID for this message. | | u | Number | Last update ID for this message. | | l | Number | Book depth level. | | d | String | Depth type, `CHANGED`. | | b | Array\> | Changed bid levels `[price, size]`. | | a | Array\> | Changed ask levels `[price, size]`. | | f | String | Merge factor (present on merged-depth updates only). |
**Update Example** ```json { "e": "depth", "E": 1773295701456, "s": "BTCUSDT", "U": 161, "u": 161, "l": 15, "d": "CHANGED", "b": [ ["103435.90", "2.10000"] ], "a": [ ["103436.10", "1.21500"] ] } ```
> **Processing tip:** Consume update IDs sequentially (`U` through `u`). If any update is missed, resubscribe to obtain fresh order book data. --- ## Document: Market Channel URL: /api-doc/contract/Websocket/public/Tickers-Channel # Market Channel **Description** Streams 24h ticker statistics for a contract, including price change, weighted average price, and the latest trade. Ticker data is pushed whenever upstream metrics change (typically within 100-300 ms).
**Subscription Request Parameters** | Field | Type | Required | Description | |:-------|:---------------|:---------|:------------| | method | String | Yes | Use `SUBSCRIBE` to add, `UNSUBSCRIBE` to remove subscriptions. | | params | Array\ | Yes | Each entry uses the format `@ticker`. Symbols are quoted in base/quote (e.g. `BTCUSDT`). | | id | Number | Optional | Client-defined identifier echoed in the acknowledgement. |
**Subscription Request Example** ```json { "method": "SUBSCRIBE", "params": [ "BTCUSDT@ticker" ], "id": 1 } ```
**Acknowledgement** | Field | Type | Description | |:-------|:--------|:------------| | result | Boolean | `true` for success, `false` for failure. | | id | Number | Echo of the request id (if provided). | | msg | String | Error message when `result` is `false`. |
**Acknowledgement Example** ```json { "result": true, "id": 1 } ```
**Push Payload** | Field | Type | Description | |:------|:-----|:------------| | e | String | Event type (`ticker`). | | E | Number | Event time in milliseconds. | | s | String | Trading pair in uppercase (e.g. `BTCUSDT`). | | d | Array\ | Ticker statistic objects. | | > p | String | 24h absolute price change. | | > P | String | 24h percentage price change. | | > w | String | 24h weighted average price. | | > c | String | Latest traded price. | | > o | String | Opening price at the start of the 24h window. | | > h | String | 24h high price. | | > l | String | 24h low price. | | > v | String | 24h trading volume (base asset). | | > q | String | 24h trading value (quote asset). | | > O | Number | Window start time (ms). | | > C | Number | Window end time (ms). | | > n | Number | Number of trades in the window. | | > m | String | Latest mark price. | | > i | String | Latest index price. |
**Push Example** ```json { "e": "ticker", "E": 1773295738939, "s": "BTCUSDT", "d": [ { "p": "-2055.6", "P": "-1.96", "w": "102345.12", "c": "102623.90", "o": "104679.50", "h": "104692.20", "l": "100709.60", "v": "176145.66489", "q": "18115688543.1", "O": 1773210000000, "C": 1773296400000, "n": 28941, "m": "102620.00", "i": "102615.50" } ] } ```
--- ## Document: Public Trade Channel URL: /api-doc/contract/Websocket/public/Trades-Channel # Public Trade Channel **Description** Streams recent taker trades for a contract. After subscribing the server delivers real-time trade updates (`trade`).
**Subscription Request Parameters** | Field | Type | Required | Description | |:-------|:---------------|:---------|:------------| | method | String | Yes | `SUBSCRIBE` or `UNSUBSCRIBE`. | | params | Array\ | Yes | `@trade`, e.g. `BTCUSDT@trade`. | | id | Number | Optional | Client identifier echoed in the acknowledgement. |
**Subscription Request Example** ```json { "method": "SUBSCRIBE", "params": [ "BTCUSDT@trade" ], "id": 3 } ```
**Acknowledgement** | Field | Type | Description | |:-------|:--------|:------------| | result | Boolean | `true` when the subscription succeeds. | | id | Number | Echo of the request id. | | msg | String | Error message when `result` is `false`. |
**Acknowledgement Example** ```json { "result": true, "id": 3 } ```
**Update Payload (`trade`)** | Field | Type | Description | |:------|:-----|:------------| | e | String | Event type, `trade`. | | E | Number | Event time in milliseconds. | | s | String | Trading pair in uppercase (e.g. `BTCUSDT`). | | d | Array\ | Trade entries, typically containing the latest fills. | | > T | Number | Trade execution time (milliseconds). | | > t | Number or String | Trade ID. | | > p | String | Trade price. | | > q | String | Trade quantity. | | > v | String | Trade value (price × quantity). | | > m | Boolean | Whether the maker side was the seller (`true` = aggressive sell). |
**Update Example** ```json { "e": "trade", "E": 1773295739001, "s": "BTCUSDT", "d": [ { "T": 1773295739001, "t": 7423916138, "p": "69382.20", "q": "0.014", "v": "971.3508", "m": false } ] } ```
> **Note:** Reconnect and resubscribe if incremental trade IDs (`t`) are detected out of order or duplicated beyond the exchange’s tolerance window. --- ## Document: Overview URL: /api-doc/contract/Websocket/websocket-intro # Overview WebSocket is a new protocol in HTML5 that enables full-duplex communication between clients and servers, allowing rapid bidirectional data transmission. Through a simple handshake, a connection can be established between client and server, enabling the server to actively push information to the client based on business rules. Its advantages include: - Small header size (~2 bytes) during data transmission between client and server - Both client and server can actively send data - Eliminates the need for repeated TCP connection setup/teardown, conserving bandwidth and server resources - Strongly recommended for developers to obtain market data, order book depth, and other information | Domain | WebSocket API | Recommended Use | |-----------------|------------------------------------------|----------------------------------| | Public Channel | wss://ws-contract.weex.com/v3/ws/public | Primary domain, public channels | | Private Channel | wss://ws-contract.weex.com/v3/ws/private | Primary domain, private channels | ## Connection Connection Specifications: - Connection limit: 300 connection requests/IP/5 minutes, maximum 20 concurrent connections per IP - Subscription limit: 240 operations/hour/connection, maximum 100 channels per connection - Public channel requirement: Public channel connections require header authentication(User-Agent) - Private channel requirement: Private channel connections require header authentication - To maintain stable and effective connections, we recommend: - After successful WebSocket connection establishment, the server will periodically send Ping messages to the client. Public channels use the format: `{"event":"ping","time":"1693208170000"}`, while private channels use the format: `{"type":"ping","time":"1693208170000"}`. In both formats, "time" represents the server's timestamp. Upon receiving either message, the client should respond with the same Pong message: `{"method":"PONG","id":1}`. The server will actively terminate connections that fail to respond more than 10 times. ## Header Authentication for Private Channels **User-Agent**:Client identification **ACCESS-KEY**: Unique identifier for API user authentication (requires application) **ACCESS-PASSPHRASE**: Password for the API Key **ACCESS-TIMESTAMP**: Unix Epoch timestamp in milliseconds (expires after 30 seconds, must match signature timestamp) **ACCESS-SIGN**: Signature string generated as follows: The message (string to be signed) consists of: timestamp + requestPath Example timestamp (in milliseconds): `const timestamp = '' + Date.now()` Where requestPath is `/v3/ws/private` **Signature Generation Process** 1. Encrypt the message string using HMAC SHA256 with the secret key: - Signature = hmac_sha256(secretkey, Message) 2. Encode the Signature using Base64: - Signature = base64.encode(Signature) ## Subscription Subscription Specification: ```json { "method": "SUBSCRIBE", "params": ["BTCUSDT@ticker", "BTCUSDT@depth15"], "id": 1 } ``` ## Unsubscription Unsubscription Specification: ```json { "result": true, "id": 1 } ``` --- ## Document: llms.txt URL: /api-doc/partner/AIResources/llms-txt # llms.txt --- ## Document: Update log URL: /api-doc/partner/changelog # Update log | Effective Time (UTC+8) | API | Update Type | Description | |--------------------------|--------------------------------------------------------------------------------------|----------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------| | 2026-07-27 | [News Source APIs](/api-doc/partner/content-endpoints/GetArticleList) | Launched | Added Web3 content APIs for paginated article queries, coin-based filtering, article details, and latest banners. | | 2026-06-22 | [Access Restrictions](/api-doc/partner/QuickStart/AccessRestrictions) | Modify | Updated access restriction rules. | | 2026-04-07 | [Get Affiliate Referral Data](/api-doc/partner/rebate-endpoints/GetChannelUserTradeAndAsset) | Modify | Documented time-range validation rules for the Get Affiliate Referral Data endpoint (v3). | | 2026-04-06 | [Get Affiliate UIDs ](/api-doc/partner/rebate-endpoints/GetAffiliateUIDs) | Modify | Documented time-range validation rules for the Get Affiliate UIDs endpoint (v3). | --- ## Document: Error Codes URL: /api-doc/partner/CommonErrorCodes # Error Codes Here is the error JSON payload: ```json { "code": -1121, "msg": "Invalid symbol." } ``` Errors consist of two parts: an error code and a message. Codes are universal, but messages can vary. ## 10xx - General Server or Network issues ### -1000 UNKNOWN_ERROR - An unknown error occurred. ### -1054 SYSTEM_ERROR - System error, please retry later. ## 10xx - Authentication / Access ### -1040 ACCESS_KEY_EMPTY - ACCESS_KEY header is required. ### -1041 ACCESS_SIGN_EMPTY - ACCESS_SIGN header is required. ### -1042 ACCESS_TIMESTAMP_EMPTY - ACCESS_TIMESTAMP header is required. ### -1043 INVALID_ACCESS_TIMESTAMP - Invalid ACCESS_TIMESTAMP. ### -1044 INVALID_ACCESS_KEY - Invalid ACCESS_KEY. ### -1045 INVALID_CONTENT_TYPE - Invalid Content-Type, please use application/json. ### -1046 ACCESS_TIMESTAMP_EXPIRED - Request timestamp expired. ### -1047 API_AUTH_ERROR - API authentication failed. ### -1049 API_KEY_OR_PASSPHRASE_INCORRECT - API key or passphrase incorrect. ### -1050 USER_STATUS_FORBIDDEN - User status is abnormal. ### -1051 PERMISSION_DENIED - Permission denied. ### -1052 INSUFFICIENT_PERMISSIONS - Insufficient permissions for this action. ### -1053 PERMISSION_VALIDATION_FAILED - Permission validation failed. ### -1055 USER_AUTH_NOT_SAFE - User must bind phone or Google authenticator. ### -1056 ILLEGAL_IP - Invalid IP address. ### -1057 USER_LOCKED - User account is locked. ### -1058 NO_PERMISSION_TRADE_PAIR - The trading pair is not supported via the API. Check the supported symbols here: [https://api-spot.weex.com/api/v3/apiTradingSymbols](https://api-spot.weex.com/api/v3/apiTradingSymbols). ### -1059 HIGH_FREQUENCY_ORDER_LIMITED - Too many high-frequency order requests in current window. ### -1060 API_KEY_SYMBOL_NOT_BOUND - This API key is not bound to the trading pair. ## 11xx - Request Content / Parameters ### -1115 INVALID_TIME_IN_FORCE - Invalid timeInForce. ### -1116 INVALID_ORDER_TYPE - Invalid order type. ### -1117 INVALID_SIDE - Invalid side. ### -1121 INVALID_SYMBOL - Invalid symbol. ### -1128 INVALID_PARAM_COMBINATION - Combination of optional parameters invalid. ### -1135 INVALID_JSON - Invalid JSON request. ### -1140 PARAM_VALIDATE_ERROR - Parameter validation failed. - limit must be between %d and %d. - startTime must be a valid millisecond timestamp. - endTime must be a valid millisecond timestamp. ### -1141 PARAM_EMPTY - Parameter '%s' cannot be empty. ### -1142 PARAM_ERROR - Parameter '%s' is invalid. ### -1150 REQUEST_METHOD_NOT_SUPPORTED - Request method not supported. ### -1160 DECIMAL_PRECISION_ERROR - Decimal precision error. ### -1170 QUERY_TIME_OUT_OF_RANGE - startTime must be within the last %d days. - Time range cannot exceed %d days. ### -1171 START_TIME_AFTER_END_TIME - startTime cannot be greater than endTime. ### -1180 CLIENT_OID_LENGTH_ERROR - client_oid length must not exceed 40 and must not contain special characters. ### -1190 FORBIDDEN_ACCESS - Access forbidden. Please contact support. ## 20xx - Spot Config / Validation ### -2007 SPOT_SYMBOL_NOT_EXIST - Symbol does not exist. ## 22xx - Spot Trading ### -2200 SPOT_ORDER_NOT_EXIST - Order does not exist. ## 23xx - Content Endpoints ### -2300 NEWS_CONTENT_NOT_FOUND - Content does not exist. ### -2301 INVALID_SECTION - Invalid section. ### -2302 ARTICLE_ID_REQUIRED - `documentId` or `v4Id` is required. ### -2303 COIN_REQUIRED - `symbol` or `slug` is required. ### -2304 INVALID_BANNER_TYPE - Invalid Banner type. ### -2305 ARTICLE_DETAIL_PERMISSION_DENIED - No permission to access article detail. The API Key owner's UID is not in the `newsSourceUids` whitelist. --- ## Document: Contact Us URL: /api-doc/partner/ContactUs # Contact Us For technical issues or any feedback, feel free to reach out to us via the following methods: - Email us at support@weex.com - Join our [Telegram community](https://t.me/+Y72JdNeHcUw3NWQ1) to stay updated and engage with the community. --- ## Document: Get Article Detail URL: /api-doc/partner/content-endpoints/GetArticleDetail # Get Article Detail **HTTP request** Returns the localized body and complete metadata of a Web3 article. This endpoint is available only to allowlisted UIDs. To request access, please contact WEEX BD. - **GET** ```/api/v3/content/articles/detail``` Weight(IP): 1
**Request headers** | Header | Required | Description | |:---|:---|:---| | `locale` | No | Content locale used for localized content and `articleUrl`. Default: `en_US`. Supported values: `ar_AR`, `az_AZ`, `de_DE`, `en_US`, `es_419`, `es_AR`, `es_ES`, `fa_IR`, `fr_FR`, `in_ID`, `it_IT`, `ja_JP`, `pl_PL`, `pt_BR`, `pt_PT`, `ru_RU`, `uk_UK`, `vi_VN`, `zh_CN`, `zh_TW`. | **Request parameters** | Parameter | Type | Required | Applies to | Description | |:---|:---|:---|:---|:---| | `section` | String | Yes | All | One value: `wiki`, `news`, `learn`, or `questions`. | | `documentId` | String | Conditional | All | Document ID. Takes precedence when both IDs are supplied. | | `v4Id` | String | Conditional | All | Legacy-compatible ID. At least one of `documentId` and `v4Id` is required. | | `populateThumbnail` | Boolean | No | `wiki`, `news`, `learn` | Whether to return `thumbnail`. Default: `false`. Ignored for `questions`. | | `populateTagLists` | Boolean | No | `wiki`, `learn`, `questions` | Whether to return `tagLists`. Default: `false`. Ignored for `news`. | | `populateCoins` | Boolean | No | All | Whether to return `coinsMaps`. Default: `false`. |
**Request example** ```powershell curl "https://api-spot.weex.com/api/v3/content/articles/detail?section=wiki&documentId=p9k2hraavuh05kfwq4ctsz84&populateThumbnail=true&populateTagLists=true&populateCoins=true" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "locale: en_US" \ -H "Content-Type: application/json" ```
**Response parameters** The detail response includes every field documented in [Get Article List](./GetArticleList.md), plus: | Field | Type | Applies to | Description | |:---|:---|:---|:---| | `body` | String | All | HTML body. The `content` field from `learn` is mapped to `body`. | | `articleUrl` | String | All | WEEX article URL generated by the server. |
**Response example** ```json { "id": 4960955, "documentId": "p9k2hraavuh05kfwq4ctsz84", "v4Id": null, "section": "wiki", "title": "iShares Core MSCI EAFE Tokenized ETF (Ondo) Price Prediction", "summary": "This article provides a market outlook and price prediction for IEFAON.", "contentKey": null, "enabled": true, "enabledDate": 1780993402765, "category": "price-prediction", "imgCategory": "Price Prediction", "link": null, "sourceSite": null, "outerPic": null, "originalSourceUrl": null, "priority": null, "date": null, "level": null, "outerId": "wordPress_wiki_130881263710491", "outerLocaleId": 130881263710491, "sourceLang": null, "titleEn": "iShares Core MSCI EAFE Tokenized ETF (Ondo) Price Prediction", "translation": true, "translationStatus": "Translated", "thumbnail": null, "tagLists": [], "coinsMaps": [], "publishedAt": 1780993501641, "createdAt": 1780993356022, "updatedAt": 1780993519507, "body": "

This article provides a full analysis of the market outlook.

", "articleUrl": "https://www.weex.com/wiki/article/ishares-core-msci-eafe-tokenized-etf-ondo-price-prediction-p9k2hraavuh05kfwq4ctsz84" } ```
--- ## Document: Get Article List URL: /api-doc/partner/content-endpoints/GetArticleList # Get Article List **HTTP request** Returns a paginated list of Web3 content. Article bodies are not included in list responses. - **GET** ```/api/v3/content/articles/list``` Weight(IP): 1
**Request headers** | Header | Required | Description | |:---|:---|:---| | `locale` | No | Content locale. Default: `en_US`. Supported values: `ar_AR`, `az_AZ`, `de_DE`, `en_US`, `es_419`, `es_AR`, `es_ES`, `fa_IR`, `fr_FR`, `in_ID`, `it_IT`, `ja_JP`, `pl_PL`, `pt_BR`, `pt_PT`, `ru_RU`, `uk_UK`, `vi_VN`, `zh_CN`, `zh_TW`. | **Request parameters** | Parameter | Type | Required | Applies to | Description | |:---|:---|:---|:---|:---| | `section` | String | Yes | All | One value: `wiki`, `news`, `learn`, or `questions`. | | `category` | String | No | `wiki`, `news` | Category filter, maximum 64 characters. For `news`, it is mutually exclusive with `categoryFilter`. | | `categoryFilter` | String | No | `news` | Excludes the specified categories, maximum 64 characters. Mutually exclusive with `category`. | | `tagName` | String | No | All | Filters by associated tag name. | | `title` | String | No | `wiki`, `news`, `questions` | Fuzzy title search, maximum 200 characters. | | `prioritySort` | Boolean | No | `news` | Sorts by priority. Default: `false`. | | `level` | String | No | `learn` | `Beginner`, `Intermediate`, or `Advanced`. Mutually exclusive with `excludeLevel`. | | `excludeLevel` | String | No | `learn` | Excludes one learning level. Mutually exclusive with `level`. | | `excludeDocumentId` | String | No | `questions` | Excludes one document ID, typically for related-content queries. | | `excludeContentKey` | String | No | `questions` | Excludes contentKey. | | `withCount` | Boolean | No | All | Whether to return `total` and `pages`. Default: `false`. | | `page` | Integer | No | All | Page number, starting from 1. Default: `1`. | | `pageSize` | Integer | No | All | Items per page. Default: `25`; maximum: `200`. | | `populateThumbnail` | Boolean | No | `wiki`, `news`, `learn` | Whether to return `thumbnail`. Default: `false`. Ignored for `questions`. | | `populateTagLists` | Boolean | No | All | Whether to return `tagLists`. Default: `false`. | | `populateCoins` | Boolean | No | All | Whether to return `coinsMaps`. Default: `false`. |
**Request example** ```powershell curl "https://api-spot.weex.com/api/v3/content/articles/list?section=news&categoryFilter=events&prioritySort=true&page=1&pageSize=10&withCount=true&populateThumbnail=true&populateTagLists=true&populateCoins=true" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "locale: en_US" \ -H "Content-Type: application/json" ```
**Response parameters** | Field | Type | Description | |:---|:---|:---| | `total` | Long | Total records. `null` when `withCount=false`. | | `page` | Integer | Current page number. | | `pageSize` | Integer | Page size. | | `pages` | Integer | Total pages. `null` when `withCount=false`. | | `hasNextPage` | Boolean | Whether another page is available. | | `items` | ArticleListItem[] | Article items. | **ArticleListItem** | Field | Type | Applies to | Description | |:---|:---|:---|:---| | `id` | Long | All | Content ID. | | `documentId` | String | All | Document ID. | | `v4Id` | String | All | Legacy-compatible content ID. | | `section` | String | All | `wiki`, `news`, `learn`, or `questions`. | | `title` | String | All | Localized title. | | `summary` | String | `wiki`, `news`, `questions` | Localized summary. `null` for `learn`. | | `contentKey` | String | All | Content key. | | `enabled` | Boolean | `wiki`, `news`, `questions` | Whether the content is enabled. `null` for `learn`. | | `enabledDate` | Long | `wiki`, `news`, `questions` | Enable time in UTC milliseconds. `null` for `learn`. | | `category` | String | `wiki`, `news` | Content category. | | `imgCategory` | String | `wiki` | Wiki image category. | | `link` | String | `news` | External source link. | | `sourceSite` | String | `news` | Source site. | | `outerPic` | String | `news` | External source image. | | `originalSourceUrl` | String | `news` | Original source URL. | | `priority` | Integer | `news` | News priority. | | `date` | Long | `learn` | Learning content date in UTC milliseconds. | | `level` | String | `learn` | `Beginner`, `Intermediate`, or `Advanced`. | | `outerId` | String | All | External content ID. | | `outerLocaleId` | Long | `wiki`, `learn`, `questions` | External locale ID. `null` for `news`. | | `sourceLang` | String | `wiki`, `learn`, `questions` | Source language. `null` for `news`. | | `titleEn` | String | All | English title. | | `translation` | Boolean | `wiki`, `learn`, `questions` | Translation flag. `null` for `news`. | | `translationStatus` | String | `wiki`, `learn`, `questions` | Translation status. `null` for `news`. | | `thumbnail` | Object | `wiki`, `news`, `learn` | `null` when unsupported, not requested, or absent. | | `tagLists` | Array | All | `null` when not requested; an empty array when requested but no tags exist. | | `coinsMaps` | Array | All | `null` when not requested; an empty array when requested but no coins exist. | | `publishedAt` | Long | All | Publication time in UTC milliseconds. | | `createdAt` | Long | All | Creation time in UTC milliseconds. | | `updatedAt` | Long | All | Update time in UTC milliseconds. |
**Response example** ```json { "total": 8102, "page": 1, "pageSize": 10, "pages": 811, "hasNextPage": true, "items": [ { "id": 1811667, "documentId": "nixq62735vbptclw9y0xti6f", "v4Id": null, "section": "news", "title": "Data: 12,000 ETH withdrawn from Poloniex", "summary": "A market news summary.", "contentKey": null, "enabled": true, "enabledDate": 1781062934160, "category": "news-flash", "imgCategory": null, "link": "https://example.com/article", "sourceSite": "rootData", "outerPic": null, "originalSourceUrl": "https://example.com/article", "priority": null, "date": null, "level": null, "outerId": "rootData_2270427", "outerLocaleId": null, "sourceLang": null, "titleEn": "Data: 12,000 ETH withdrawn from Poloniex", "translation": null, "translationStatus": null, "thumbnail": null, "tagLists": [], "coinsMaps": [], "publishedAt": 1781062922400, "createdAt": 1781062922391, "updatedAt": 1781062935084 } ] } ```
--- ## Document: Get Article List by Coin URL: /api-doc/partner/content-endpoints/GetArticleListByCoin # Get Article List by Coin **HTTP request** Returns a paginated Web3 content list associated with a coin. - **GET** ```/api/v3/content/articles/listByCoin``` Weight(IP): 1
**Request headers** | Header | Required | Description | |:---------|:---------|:------------| | `locale` | No | Content locale. Default: `en_US`. Supported values: `ar_AR`, `az_AZ`, `de_DE`, `en_US`, `es_419`, `es_AR`, `es_ES`, `fa_IR`, `fr_FR`, `in_ID`, `it_IT`, `ja_JP`, `pl_PL`, `pt_BR`, `pt_PT`, `ru_RU`, `uk_UK`, `vi_VN`, `zh_CN`, `zh_TW`. | **Request parameters** | Parameter | Type | Required | Applies to | Description | |:----------|:-----|:---------|:-----------|:------------| | `section` | String | Yes | All | One content section: `wiki`, `news`, `learn`, or `questions`. | | `symbol` | String | Conditional | All | Coin symbol, for example `BTC`. At least one of `symbol` and `slug` is required. | | `slug` | String | Conditional | All | Coin slug, for example `btc`. At least one of `symbol` and `slug` is required. | | `startEnableDate` | String | No | `news` | Inclusive lower bound of `enabledDate`, as a Unix timestamp in seconds or milliseconds. Ignored for other sections. | | `endEnableDate` | String | No | `news` | Inclusive upper bound of `enabledDate`, as a Unix timestamp in seconds or milliseconds. When omitted, results do not go beyond the current time. Ignored for other sections. | | `withCount` | Boolean | No | All | Whether to return `total` and `pages`. Default: `false`. | | `page` | Integer | No | All | Page number, starting from 1. Default: `1`. | | `pageSize` | Integer | No | All | Number of items per page. Default: `25`; maximum: `200`. | | `populateThumbnail` | Boolean | No | `wiki`, `news`, `learn` | Whether to return `thumbnail`. Default: `false`. Ignored for `questions`. | | `populateTagLists` | Boolean | No | All | Whether to return `tagLists`. Default: `false`. | | `populateCoins` | Boolean | No | All | Whether to return `coinsMaps`. Default: `false`. |
**Request example** ```powershell curl "https://api-spot.weex.com/api/v3/content/articles/listByCoin?section=learn&symbol=BTC&page=1&pageSize=10&withCount=true&populateThumbnail=true&populateTagLists=true&populateCoins=true" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "locale: en_US" \ -H "Content-Type: application/json" ```
**Response parameters** | Field | Type | Description | |:------|:-----|:------------| | `total` | Long | Total records. May be `null` when `withCount=false`. | | `page` | Integer | Current page number. | | `pageSize` | Integer | Page size. | | `pages` | Integer | Total pages. May be `null` when `withCount=false`. | | `hasNextPage` | Boolean | Whether another page is available. | | `items` | ArticleListItem[] | Article items. Fields are documented in [Get Article List](./GetArticleList.md). | Article bodies are not returned. Every item contains the complete 30-field `ArticleListItem` union documented in [Get Article List](./GetArticleList.md). Fields that do not apply to the selected `section` are returned as `null`; they are not omitted.
**Response example** ```json { "total": 154, "page": 1, "pageSize": 10, "pages": 16, "hasNextPage": true, "items": [ { "id": 1714, "documentId": "vvcry6rt2d8bt5e4kgaaxkv7", "v4Id": null, "section": "learn", "title": "What Is Bitcoin?", "summary": null, "level": "Beginner", "contentKey": "learn-bitcoin", "titleEn": "What Is Bitcoin?", "thumbnail": null, "tagLists": [], "coinsMaps": [ { "id": 1, "documentId": "btc-coin-map", "slug": "btc", "symbol": "BTC", "name": "Bitcoin", "icon": "https://example.com/btc.png", "type": "Tokens", "locale": "en_US" } ], "publishedAt": 1780993501641, "createdAt": 1780993356022, "updatedAt": 1780993519507 } ] } ```
--- ## Document: Get Latest Banner URL: /api-doc/partner/content-endpoints/GetLatestBanner # Get Latest Banner **HTTP request** Returns the latest published Banner for the specified type. - **GET** ```/api/v3/content/banners/latest``` Weight(IP): 1
**Request headers** | Header | Required | Description | |:---------|:---------|:------------| | `locale` | No | Banner locale. Default: `en_US`. Supported values: `ar_AR`, `az_AZ`, `de_DE`, `en_US`, `es_419`, `es_AR`, `es_ES`, `fa_IR`, `fr_FR`, `in_ID`, `it_IT`, `ja_JP`, `pl_PL`, `pt_BR`, `pt_PT`, `ru_RU`, `uk_UK`, `vi_VN`, `zh_CN`, `zh_TW`. | **Request parameters** | Parameter | Type | Required | Description | |:----------|:-----|:---------|:------------| | `type` | String | Yes | Banner type: `News`, `Wiki`, `Learn main`, `Learn details`, `News details bottom`, `learn pop up`, `learn pop up detail`, or `News details text`. |
**Request example** ```powershell curl "https://api-spot.weex.com/api/v3/content/banners/latest?type=News" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "locale: en_US" \ -H "Content-Type: application/json" ```
**Response parameters** | Field | Type | Description | |:------|:-----|:------------| | `id` | Long | Banner ID. | | `documentId` | String | Document ID. | | `title` | String | Banner title. | | `description` | String | Banner description. | | `cta` | String | Call-to-action text. | | `link` | String | Target URL. | | `type` | String | Banner type. | | `thumbnail` | Object | Banner image metadata. Omitted when no image exists. | | `publishedAt` | Long | Publication time in UTC milliseconds. | | `createdAt` | Long | Creation time in UTC milliseconds. | | `updatedAt` | Long | Update time in UTC milliseconds. |
**Response example** ```json { "id": 1001, "documentId": "banner-news-latest", "title": "Latest Crypto News", "description": "Stay updated with the latest Web3 market news.", "cta": "Read more", "link": "https://www.weex.com/news", "type": "News", "thumbnail": { "id": 9001, "documentId": "banner-image-doc", "name": "news-banner.png", "url": "https://example.com/news-banner.png", "width": 1200, "height": 480, "mime": "image/png", "size": 245.5 }, "publishedAt": 1780993501641, "createdAt": 1780993356022, "updatedAt": 1780993519507 } ```
--- ## Document: Content Endpoints URL: /api-doc/partner/content-endpoints # Content Endpoints --- ## Document: FAQs URL: /api-doc/partner/FAQ # FAQs ## Q1: Does WEEX provide a Partner / Rebate API? Yes. WEEX provides the Partner API, which can be used to query partner-related data such as invited users, trading volume, rebates, and assets. Documentation entry: [Partner API](https://www.weex.com/api-doc/partner/intro) ## Q2: Why does the rebate API return 403 or 40022? This is usually caused by using an old API version or by an account permission mismatch. Please use the V3 Partner API first, and confirm that the current account has the required partner/rebate permissions. Rebate API example: [GetAffiliateCommission](https://www.weex.com/api-doc/partner/rebate-endpoints/GetAffiliateCommission) ## Q3: Can I query the list of users I invited? Yes. You can use `GetAffiliateUIDs` to query the invited user list. Documentation: [GetAffiliateUIDs](https://www.weex.com/api-doc/partner/rebate-endpoints/GetAffiliateUIDs) ## Q4: Can I query trading data for a specific UID? Yes. You can use `GetChannelUserTradeAndAsset` to query the trading volume, deposits, withdrawals, rebates, and other data of a specified invited user. Documentation: [GetChannelUserTradeAndAsset](https://www.weex.com/api-doc/partner/rebate-endpoints/GetChannelUserTradeAndAsset) ## Q5: Can I query a user's spot and futures trading volume? Yes. `GetChannelUserTradeAndAsset` supports querying the spot and futures trading volume of invited users, and supports custom time ranges. ## Q6: Can I query my rebates and user transaction fees? Yes. You can use `GetAffiliateCommission` to query rebate records, transaction fees, rebate ratios, trading pairs, maker/taker information, and more. Documentation: [GetAffiliateCommission](https://www.weex.com/api-doc/partner/rebate-endpoints/GetAffiliateCommission) ## Q7: Can I query invited users' assets, balances, and deposit information? Yes. You can use `GetAffiliateAssets` to query invited users' spot assets, futures assets, available balances, and deposit-related information. Documentation: [GetAffiliateAssets](https://www.weex.com/api-doc/partner/rebate-endpoints/GetAffiliateAssets) ## Q8: Does the API return user KYC status or registration time? Currently, this type of interface does not directly return user KYC status or registration time. ## Q9: Can the API query a user's current positions or copy trading information? Currently, API queries for invited users' current futures positions, copy trading, or copy transaction information are not supported. ## Q10: How can I confirm whether a user registered through my invitation code? You can use the `VerifyReferrals` interface to verify whether the user matches the invitation code or invitation relationship. Documentation: [VerifyReferrals](https://www.weex.com/api-doc/partner/rebate-endpoints/VerifyReferrals) ## Q11: Can I query sub-agent or sub-channel data? Yes. You can use `QuerySubChannelTransactions` to query sub-agent-related information. Documentation: [QuerySubChannelTransactions](https://www.weex.com/api-doc/partner/rebate-endpoints/QuerySubChannelTransactions) ## Q12: Does the Partner API provide a test environment? Currently, the Partner API does not provide a dedicated sandbox/test environment. The demo trading API is only applicable to testing some trading interfaces and cannot be used as a Partner API test environment. ## Q13: Why is the rebate data query empty? Possible reasons include: rebates have not been settled yet, the query time range is incorrect, required parameters are missing, or there is no matching data within the selected time range. We recommend confirming the time range and parameters before querying again. ## Q14: What are the units for trading volume, rebates, deposits, and withdrawals? Related amount fields are usually returned in USDT terms. ## Q15: After each sub-partner creates their own API Key, what data can they view? When sub-partners use API Keys created under their own accounts, they can only view invited users and rebate data within the permission scope of their accounts. ## Q16: How should API requests be signed? Please generate `ACCESS-SIGN` according to the Partner API signature documentation, and include `ACCESS-KEY`, `ACCESS-SIGN`, `ACCESS-TIMESTAMP`, `ACCESS-PASSPHRASE`, and other required information in the request headers. Documentation: [Signature](https://www.weex.com/api-doc/partner/QuickStart/Signature) --- ## Document: Introduction URL: /api-doc/partner/intro # Introduction The Partner API provides WEEX partners with a comprehensive set of programmatic management interfaces for querying commission data, managing invited users, monitoring sub-partner performance, and more. Through this API, partners can: - Commission Inquiry: Retrieve real-time commission income details and summaries - User Management: View directly and indirectly invited users, as well as sub-partner lists - Performance Monitoring: Track contract/spot trading data of invited users --- ## Document: Access Restrictions URL: /api-doc/partner/QuickStart/AccessRestrictions # Access Restrictions REST API access is rate limited. Except for order placement endpoints, all endpoints are rate limited by IP. Order placement endpoints are rate limited by the `ORDERS` type. When you exceed a request rate limit, the request fails with HTTP status code `429`. When you receive `429`, you are responsible for stopping requests and must not abuse the API. Violating the limits results in a `10s` ban. ## Basic Information The following `intervalLetter` values are used in response headers: | interval | intervalLetter | |----------|----------------| | SECOND | S | | MINUTE | M | | HOUR | H | | DAY | D | The `rateLimits` array in `/api/v3/exchangeInfo` contains REST API rate limits, including but not limited to the REST endpoints in this document. These limits include weighted request limits and order rate limits. For more information about limit types, see the enum definitions. ## IP Rate Limits Except for order placement endpoints, all endpoints use IP rate limits. These limits are based on IP, not API Key or UID. Each endpoint has a corresponding `weight`. Some endpoints may have different weights depending on request parameters. Endpoints that consume more resources have higher weights. Each request includes the following response headers: | Header | Description | |--------|-------------| | `X-USED-WEIGHT-(intervalNum)(intervalLetter)` | Used weight for the current IP within the interval. | | `X-REMAINING-WEIGHT-(intervalNum)(intervalLetter)` | Remaining weight for the current IP within the interval. | For example, `X-USED-WEIGHT-1M` indicates the used weight for the current IP within a 1-minute interval. ## ORDERS Rate Limits Order placement endpoints are rate limited by the `ORDERS` type. This limit is based on the account, that is, `userId`. Order placement endpoints do not consume IP weight. The IP rate limit count in response headers is `0`. Each order placement request includes the following response headers: | Header | Description | |--------|-------------| | `X-ORDER-COUNT-(intervalNum)(intervalLetter)` | Used order count for the current account within the interval. | | `X-ORDER-REMAINING-(intervalNum)(intervalLetter)` | Remaining order count for the current account within the interval. | --- ## Document: API Domain URL: /api-doc/partner/QuickStart/APIDomain # API Domain You can use different domain as below Rest API. | Domain Name | API | Description | |----------------------|-------------------------------|-------| | Spot REST Domain | https://api-spot.weex.com | Main Domain | --- ## Document: Preparation URL: /api-doc/partner/QuickStart/IntegrationPreparation # Preparation To use the API, please log in to the web platform, create and configure API keys with proper permissions, then proceed with development and trading as detailed in this documentation. Click [here](https://www.weex.com/account/newapi) to create an API Key. Each user can create up to 10 API Key groups. Each key can be configured for "Read" and/or "Trade" permissions. Permission details: - The default permission for newly created APIs is `Read Only` After creating an API Key, securely store the following: - `APIKey` — The unique identifier for API authentication which is algorithmically generated. - `SecretKey` — The system-generated private key for signature encryption. - `Passphrase` —A user-defined access phrase. Note: If lost, the Passphrase cannot be recovered. You must create a new API key. :::tip You can bind IP addresses to API keys when creating API keys. Unrestricted API keys (with no IP address binding) pose security risks. ::: :::warning ::: --- ## Document: Request Processing URL: /api-doc/partner/QuickStart/RequestInteraction # Request Processing ```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 = "https://api-spot.weex.com"; // 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"); 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"); 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/v3/openOrders"; String queryString = "?symbol=BTCUSDT"; String response = sendRequestGet(API_KEY, SECRET_KEY, ACCESS_PASSPHRASE, "GET", requestPath, queryString); System.out.println("GET Response: " + response); // POST request example String postPath = "/api/v3/order"; String body = "{\"symbol\":\"BTCUSDT\",\"side\":\"BUY\",\"type\":\"LIMIT\",\"timeInForce\":\"GTC\",\"quantity\":\"0.01\",\"price\":\"68900\"}"; response = sendRequestPost(API_KEY, SECRET_KEY, ACCESS_PASSPHRASE, "POST", postPath, "", body); System.out.println("POST Response: " + response); } catch (Exception e) { e.printStackTrace(); } } } ``` ```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() # print(base64.b64encode(signature).decode()) return base64.b64encode(signature).decode() 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() # print(base64.b64encode(signature).decode()) 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)) # print(timestamp) 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" } url = "https://api-spot.weex.com" # Please replace with the actual API address if method == "GET": response = requests.get(url + request_path, headers=headers) elif method == "POST": response = requests.post(url + request_path, headers=headers, data=body) return response def send_request_get(api_key, secret_key, access_passphrase, method, request_path, query_string): timestamp = str(int(time.time() * 1000)) # print(timestamp) 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" } url = "https://api-spot.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(): # Example of calling a GET request request_path = "/api/v3/openOrders" query_string = '?symbol=BTCUSDT' response = send_request_get(api_key, secret_key, access_passphrase, "GET", request_path, query_string) print(response.status_code) print(response.text) def post(): # Example of calling a POST request request_path = "/api/v3/order" body = { "symbol": "BTCUSDT", "side": "BUY", "type": "LIMIT", "timeInForce": "GTC", "quantity": "0.01", "price": "68900" } 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__': get() post() ``` All requests are based on the HTTPS protocol. The Content-Type in the request headers must be set to 'application/json'. **Request Processing** - Request parameters: Parameter encapsulation according to endpoint request parameter specification. - Submit request: Submit the encapsulated parameters to the server via GET/POST. - Server response: The server first performs security checks on the request data, and after passing the check, returns the response data to the user in the JSON format based on the operation logic. - Data processing: Process the server response data. **Success** HTTP 200 status codes indicates success and may contain content.Response content (if any) will be included in the returned data. **Common error codes** - 400 Bad Request – Invalid request format - 401 Unauthorized – Invalid API Key - 403 Forbidden – You do not have access to the requested resource - 404 Not Found — No requests found - 429 Too Many Requests – Rate limit exceeded - 500 Internal Server Error – We had a problem with our server - Failed responses include error descriptions in the body. --- ## Document: Signature URL: /api-doc/partner/QuickStart/Signature # Signature The ACCESS-SIGN request header is generated by using the **HMAC SHA256** method encryption on the **timestamp + method.toUpperCase() + requestPath + "?" + queryString + body** string (+ denotes string concatenation), and putting the result through **BASE64** encoding. **Timestamp** The `ACCESS-TIMESTAMP` in request signatures is in milliseconds. Requests are rejected if the timestamp deviates by more than 30 seconds from the API server time. If the local server time deviates significantly from the API server time, we recommend querying the API server time and using it to update the HTTP Header. **Request Formats** The following request methods are currently supported: - GET: Parameters are sent to the server in the path through queryString. - POST: Parameters are sent to the server in the body as JSON. - DELETE: Parameters are sent to the server through queryString or a JSON body, according to the endpoint documentation. When generating the signature, concatenate `requestPath`, `queryString`, and `body` according to the actual request content. **Signature Field Description** - timestamp: This matches the ACCESS-TIMESTAMP header. - method: The request method (GET/POST/DELETE), with all letters in uppercase. - requestPath: API endpoint path. - queryString: The query parameters after the "?" in the URL. - body: The string that corresponds to the request body. It can be omitted if the request has no body. **Signature format rules if queryString is empty** - timestamp + method.toUpperCase() + requestPath + body **Signature format rules if queryString is not empty** - timestamp + method.toUpperCase() + requestPath + "?" + queryString + body **Examples** Fetching market depth, using BTCUSDT as an example: - Timestamp = 1591089508404 - Method = "GET" - requestPath = "/api/v3/market/depth" - queryString= "symbol=BTCUSDT&limit=20" **Generate the string to be signed:** - '1591089508404GET/api/v3/market/depth?symbol=BTCUSDT&limit=20' Placing an order, using BTCUSDT_SPBL as an example: - Timestamp = 1561022985382 - Method = "POST" - requestPath = "/api/v3/order" - body = ```json {"symbol":"BTCUSDT","side":"BUY","type":"LIMIT","timeInForce":"GTC","quantity":"1","price":"68900","newClientOrderId":"my-order-001"} ``` **Generate the string to be signed:** - ``` '1561022985382POST/api/v3/order{"symbol":"BTCUSDT","side":"BUY","type":"LIMIT","timeInForce":"GTC","quantity":"1","price":"68900","newClientOrderId":"my-order-001"}' ``` **Steps to generate the final signature** 1. Encrypt the unsigned string with HMAC SHA256 using your secretKey - Signature = hmac_sha256(secretkey, Message) 2. Encode the signature using Base64 - Signature = base64.encode(Signature) --- ## Document: Get Affiliate Member Assets URL: /api-doc/partner/rebate-endpoints/GetAffiliateAssets # Get Affiliate Member Assets **HTTP request** Query the asset snapshot of a direct customer under the current affiliate. - **GET** ```/api/v3/agency/getAssert``` Weight(IP): 10
**Request parameters** | Parameter | Type | Required? | Description | |:-----------|:-------|:----------|:----------------------------------------------------------------------------| | userId | Long | Yes | Direct customer UID | | startTime | String | No | Optional start time (UTC, format `yyyy-MM-dd`) | | endTime | String | No | Optional end time (UTC, format `yyyy-MM-dd`, defaults to current if absent) |
**Request example** ```powershell curl "https://api-spot.weex.com/api/v3/agency/getAssert?userId=4667776811&startTime=2025-02-01&endTime=2025-03-01" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1732972800000" \ -H "Content-Type: application/json" ```
**Response parameters** | Field Name | Type | Description | |:--------------------|:-------|:-------------------------------------------------| | availableBalance | String | Available balance in USDT | | fundingTotalUsdt | String | Total funding account equity in USDT | | spotProTotalUsdt | String | Total spot account equity in USDT | | unimarginTotalUsdt | String | Total contract account equity in USDT | | depositTotalAmount | String | Cumulative deposit amount within the time window | | depositList | Array | Deposit records |
**Response example** ```json { "availableBalance": "3415185672.29521058", "contractTotalUsdt": "--", "depositList": [], "depositTotalAmount": "0.00000000", "fundingTotalUsdt": "100.19000000", "spotProTotalUsdt": "3415184095.36345915", "unimarginTotalUsdt": "1476.74175143" } ```
--- ## Document: Get Affiliate Commission URL: /api-doc/partner/rebate-endpoints/GetAffiliateCommission # Get Affiliate Commission **HTTP request** Get Affiliate Commission - **GET** ```/api/v3/rebate/affiliate/getAffiliateCommission``` Weight(IP): 20
**Request parameters** | Parameter | Parameter Type | Required | Description | |:---------------|:----------------|:---------|:-------------------------------------------------------------------------------| | uid | Long | No | Invited User UID | | startTime | Long | No | Start timestamp in UTC (milliseconds). Default: 7 days ago,Max range: 3 months | | endTime | Long | No | End timestamp in UTC (milliseconds). Default: current time,Max range: 3 months | | coin | String | No | USDT or BTC | | productType | String | No | SPOT or FUTURES (default SPOT) | | page | Integer | No | Page number (starting from 1, default 1) | | pageSize | Integer | No | Page size (default 100) |
**Request example** ```powershell curl "https://api-spot.weex.com/api/v3/rebate/affiliate/getAffiliateCommission" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "Content-Type: application/json" ```
**Response parameters** | Field Name | Type | Description | |:----------------------------|:--------|:-----------------------------------------| | channelCommissionInfoItems | Array | Commission records | | uid | Long | Invited User UID | | date | Long | Commission timestamp, unit: milliseconds | | coin | String | USDT, BTC ... | | productType | String | Product Type | | fee | String | Net Trading Fee | | commission | String | Paid Commission | | rate | String | Rebate Rate | | symbol | String | Trading Pair | | sourceType | Integer | 1: Direct Client, 2: Sub-agent | | takerAmount | String | Taker Amount (Trading Volume) | | makerAmount | String | Maker Amount (Trading Volume) | | pages | Integer | Total pages | | pageSize | Integer | Page size | | total | Long | Total records |
**Response example** ```json { "pages": 3, "pageSize": 100, "total": 1014, "channelCommissionInfoItems": [ { "uid": "4667776811", "date": 1755687731913, "coin": "USDT", "fee": "0.682571", "commission": "0.0682571", "rate": "0.1", "productType": "SPOT", "symbol": "cmt_btcusdt", "sourceType": 1, "takerAmount": "1137.619", "makerAmount": "0" } ] } ```
--- ## Document: Get Affiliate Deal Data URL: /api-doc/partner/rebate-endpoints/GetAffiliateDealData # Get Affiliate Deal Data **HTTP request** Retrieve trading volume and rebate statistics for one or more direct customers. - **GET** ```/api/v3/agency/getDealData``` Weight(IP): 10
**Request parameters** | Parameter | Type | Required? | Description | |:----------|:-----------------|:----------|:-------------------------------------------------------------------------------------------------| | userIds | List\ | No | Optional repeated query parameter (e.g. `userIds=123&userIds=456`). Defaults to all direct users | | startTime | String | No | Filter start date (UTC, format `yyyy-MM-dd`) | | endTime | String | No | Filter end date (UTC, format `yyyy-MM-dd`) |
**Request example** ```powershell curl "https://api-spot.weex.com/api/v3/agency/getDealData?userIds=4667776811&startTime=2025-02-01&endTime=2025-03-01" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1732972800000" \ -H "Content-Type: application/json" ```
**Response parameters** | Field Name | Type | Description | |:--------------------------|:-------|:-----------------------------------------------------------| | data | Array | Trading statistics returned by the upstream service | | userId | Long | UID of the queried customer | | spotDealAmountUsdt | String | Spot trading volume (USDT) | | futuresProDealAmountUsdt | String | Futures trading volume (USDT) | | spotProDealAmountUsdtTemp | String | Spot trading volume (raw value returned by partner system) | | startTime | String | Start date applied by the upstream service (`yyyy-MM-dd`) | | endTime | String | End date applied by the upstream service (`yyyy-MM-dd`) |
**Response example** ```json { "data": [ { "futuresProDealAmountUsdt": "619659.79380470", "spotDealAmountUsdt": "75156.60000000", "spotProDealAmountUsdtTemp": "75156.6", "userId": 4667776811 } ], "endTime": "2026-03-04", "startTime": "2025-12-03" } ```
--- ## Document: Get Affiliate UIDs URL: /api-doc/partner/rebate-endpoints/GetAffiliateUIDs # Get Affiliate UIDs **HTTP request** Get Affiliate UIDs - **GET** ```/api/v3/rebate/affiliate/getAffiliateUIDs``` Weight(IP): 20
**Request parameters** | Parameter | Parameter type | Required? | Description | |:---------------|:----------------|:-----------|:-----------------------------------------| | uid | Long | No | Invited User UID | | startTime | Long | No | Start timestamp in UTC (milliseconds). Must fall within the past 1 year; defaults to 90 days prior to `endTime` when omitted. | | endTime | Long | No | End timestamp in UTC (milliseconds). Must be greater than `startTime`; total range cannot exceed 90 days. | | page | Integer | No | Page number (starting from 1, default 1) | | pageSize | Integer | No | Page size (default 100) | - End time must be later than the start time. - The query window cannot exceed 90 consecutive days. - The start time must be within the most recent 365 days; by default the system queries the last 90 days.
**Request example** ```powershell curl "https://api-spot.weex.com/api/v3/rebate/affiliate/getAffiliateUIDs" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "Content-Type: application/json" ```
**Response parameters** | Field Name | Type | Description | |:--------------|:--------|:-------------------------------------------| | uid | String | Invited User UID | | registerTime | Long | Registration timestamp, unit: milliseconds | | kycResult | Boolean | KYC status | | inviteCode | String | Invitation Code | | firstDeposit | Long | First deposit time (milliseconds) | | firstTrade | Long | First trade time (milliseconds) | | lastDeposit | Long | Latest deposit time (milliseconds) | | lastTrade | Long | Latest trade time (milliseconds) | | channelUserInfoItemList | Array | Affiliate user items | | pages | Integer | Total pages | | pageSize | Integer | Page size | | total | Long | Total records |
**Response example** ```json { "pages": 1, "pageSize": 100, "total": 98, "channelUserInfoItemList": [ { "uid": "3066862172", "registerTime": 1749797913000, "kycResult": false, "inviteCode": "3lft", "firstTrade": 1738767425000, "lastTrade": 1744115178000, "firstDeposit": 1736425200000, "lastDeposit": 1745038712000 } ] } ```
--- ## Document: Get Affiliate Referral Data URL: /api-doc/partner/rebate-endpoints/GetChannelUserTradeAndAsset # Get Affiliate Referral Data **HTTP request** Direct Customer Trading Volume and Capital Analytics - **GET** ```/api/v3/rebate/affiliate/getChannelUserTradeAndAsset``` Weight(IP): 20
**Request parameters** | Parameter | Parameter type | Required? | Description | |:---------------|:----------------|:-----------|:-----------------------------------------| | uid | Long | No | Invited User UID | | startTime | Long | No | Start timestamp in UTC (milliseconds) | | endTime | Long | No | End timestamp in UTC (milliseconds) | | page | Integer | No | Page number (starting from 1, default 1) | | pageSize | Integer | No | Page size (default 100) | - End time must be later than the start time. - The query window cannot exceed 90 consecutive days. - The start time must be within the most recent 365 days; by default the system queries the last 90 days.
**Request example** ```powershell curl "https://api-spot.weex.com/api/v3/rebate/affiliate/getChannelUserTradeAndAsset" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "Content-Type: application/json" ```
**Response parameters** | Field Name | Type | Description | |:---------------------|:--------|:-----------------------| | uid | String | Invited User UID | | depositAmount | String | Deposit Amount | | withdrawalAmount | String | Withdrawal Amount | | spotTradingAmount | String | Spot Trading Volume | | futuresTradingAmount | String | Futures Trading Volume | | commission | String | Commission | | records | Array | Aggregated records | | pages | Integer | Total pages | | pageSize | Integer | Page size | | total | Long | Total records |
**Response example** ```json { "pages": 1, "pageSize": 100, "total": 98, "records": [ { "uid": "3066862172", "depositAmount": "0", "withdrawalAmount": "0", "spotTradingAmount": "0", "futuresTradingAmount": "0", "commission": "0" } ] } ```
--- ## Document: Get Internal Withdrawal Status URL: /api-doc/partner/rebate-endpoints/GetInternalWithdrawalStatus # Get Internal Withdrawal Status **HTTP request** Get Internal Withdrawal Status - **GET** ```/api/v3/rebate/affiliate/getInternalWithdrawalStatus``` Weight(IP): 100
**Request parameters** | Parameter | Parameter Type | Required | Description | |:------------------|:----------------|:-----------|:---------------------------------------------------------------------------------------------| | withdrawID | String | No | Withdraw ID | | coin | String | No | Currency type (USDT, BTC) | | startTime | Long | No | Start timestamp in UTC (milliseconds)
(Only data from the past month can be queried) | | endTime | Long | No | End timestamp in UTC (milliseconds)
(Only data from the past month can be queried) | | fromAccountType | String | No | Type of the originating account
(SPOT: spot wallet, FUND: funding wallet, Default: SPOT) | | toAccountType | String | No | Type of the target account
(SPOT: spot wallet, FUND: funding wallet, Default: SPOT) | | page | Integer | No | Page number (starting from 1, default 1) | | pageSize | Integer | No | Page size (default 100, max 200) |
**Request example** ```powershell curl "https://api-spot.weex.com/api/v3/rebate/affiliate/getInternalWithdrawalStatus" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "Content-Type: application/json" ```
**Response parameters** | Field Name | Type | Description | |:---------------|:-------|:-----------------------------------------------------------------------| | items | Array | Withdrawal records | | fromUserId | Long | Transfer out User ID | | toUserId | Long | Transfer in User ID | | withdrawId | String | Withdraw ID | | coin | String | USDT, BTC ... | | status | String | Possible values:
SUCCESS
FAILED
PROGRESSING | | amount | String | Transfer amount | | createTime | Long | Withdraw created timestamp (ms) | | updateTime | Long | Withdraw updated timestamp (ms) | | total | Long | Total records | | pageSize | Integer| Page size | | page | Integer| Current page number | | pages | Integer| Total pages | | hasNextPage | Boolean| Whether more pages exist |
**Response example** ```json { "total": 2, "page": 1, "pageSize": 100, "pages": 1, "hasNextPage": false, "items": [ { "fromUserId": 4382293191, "toUserId": 1626721110, "withdrawId": "1295851890224222208", "coin": "USDT", "status": "SUCCESS", "amount": "0.1000000000000000", "createTime": 1744681087070, "updateTime": 1744681087118 } ] } ```
--- ## Document: Partner Endpoints URL: /api-doc/partner/rebate-endpoints # Partner Endpoints --- ## Document: Internal Withdrawal URL: /api-doc/partner/rebate-endpoints/InternalWithdrawal # Internal Withdrawal **HTTP request** Internal Withdrawal - **POST** ```/api/v3/rebate/affiliate/internalWithdrawal``` Weight(IP): 100
**Request parameters** | Parameter | Parameter Type | Required | Description | |:----------------|:-----------------|:----------|:---------------------------------------------------------------------------------------------| | toUserId | Long | Yes | Transfer-in user ID | | coin | String | Yes | Currency type (USDT, BTC) | | amount | String | Yes | Transfer amount (Up to 6 decimal places) | | fromAccountType | String | No | Type of the originating account
(SPOT: spot wallet, FUND: funding wallet, Default: SPOT) | | toAccountType | String | No | Type of the target account
(SPOT: spot wallet, FUND: funding wallet, Default: SPOT) |
**Request example** ```powershell curl -X POST "https://api-spot.weex.com/api/v3/rebate/affiliate/internalWithdrawal" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "Content-Type: application/json" \ -d '{ "toUserId": "3066862172", "coin": "USDT", "amount": "1", "fromAccountType": "SPOT", "toAccountType": "SPOT" }' ```
**Response** Returns the transfer ID as a string when the request succeeds.
**Response example** ``` "1295851890224222208" ```
--- ## Document: Get Subaffiliates Data (affiliate only) URL: /api-doc/partner/rebate-endpoints/QuerySubChannelTransactions # Get Subaffiliates Data (affiliate only) **HTTP Request** Query Sub-Affiliate Trading Volume, Fees, and Commission Data (Affiliate Account) - **POST** ```/api/v3/rebate/affiliate/querySubChannelTransactions``` Weight(IP): 10
**Request Parameters** | Parameter | Parameter Type | Required | Description | |:----------------|:----------------|:-----------|:---------------------------------------| | subUid | Long | No | Sub-affiliate's UID | | startTime | Long | No | Start timestamp (UTC milliseconds) | | endTime | Long | No | End timestamp (UTC milliseconds) | | productType | String | Yes | Product type (SPOT or FUTURES) | | pageNum | Integer | No | Page number (starts from 1, default 1) | | pageSize | Integer | No | Items per page (default 100) |
**Request Example** ```powershell curl -X POST "https://api-spot.weex.com/api/v3/rebate/affiliate/querySubChannelTransactions" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "Content-Type: application/json" \ -d '{ "startTime": null, "endTime": null, "productType": "FUTURES" }' ```
**Response Parameters** | Field Name | Type | Description | |:----------------|:---------|:--------------------------------------| | records | Array | Sub-affiliate records | | subAffiliateUid | String | Sub-affiliate ID | | productType | String | Product Type | | date | String | Date | | tradingVolume | String | Total Trading Volume | | netTradingFee | String | Net Trading Fee Collected by Platform | | paidCommission | String | Actual Rebate Amount | | total | Long | Total records | | size | Integer | Page size | | current | Integer | Current page | | pages | Integer | Total pages |
**Response Example** ```json { "records": [ { "subAffiliateUid": "6424873609", "productType": "FUTURES", "date": "2025-08-20", "tradingVolume": "2698.099", "netTradingFee": "1.70343", "paidCommission": "1.362744" } ], "total": 1, "size": 10, "current": 1, "pages": 1 } ```
--- ## Document: Verify Referrals URL: /api-doc/partner/rebate-endpoints/VerifyReferrals # Verify Referrals **HTTP request** Verify whether the specified UIDs belong to the current affiliate. - **GET** ```/api/v3/agency/verifyReferrals``` Weight(IP): 10
**Request parameters** | Parameter | Type | Required? | Description | |:----------|:-------|:----------|:-----------------------------------------------------------------------------------------| | userIds | String | Yes | Comma-separated UID list (for example `12345,67890`). Supports up to 100 UIDs per call. |
**Request example** ```powershell curl "https://api-spot.weex.com/api/v3/agency/verifyReferrals?userIds=12345,67890" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1732972800000" \ -H "Content-Type: application/json" ```
**Response parameters** | Field Name | Type | Description | |:------------|:--------|:--------------------------------------------------------| | uid | Long | UID that was checked | | isRefferal | Boolean | `true` if the UID belongs to the current affiliate |
**Response example** ```json [ { "isRefferal": true, "uid": 4667776811 } ] ```
--- ## Document: llms.txt URL: /api-doc/broker/AIResources/llms-txt # llms.txt --- ## Document: Error codes URL: /api-doc/broker/api/BrokerErrorCodes # Error codes JSON payload error: ```json { "code": -4000, "msg": "Please contact the administrator." } ``` Errors consist of two parts: an error code and a message. The code is standardized, while the message may vary. ## 40xx—Broker-related errors ### -4000 SYSTEM_ERROR - Try again later, or contact customer support. ### -4001 UNKNOWN_ERROR - System error, retry later. ### -4002 BROKER_NOT_BROKER_ACCOUNT - Not a broker account, no permission. --- ## Document: Get user commission eligibility (broker access only) URL: /api-doc/broker/api/CheckUserEligibility # Get user commission eligibility (broker access only) - **GET** ```/api/v3/apiReferral/checkUserEligibility``` Weight(IP): 5
**Request parameters** | Parameter | Type | Required? | Description | |:-------------|:---------|:-------------|:--------------------| | userId | Long | YES | WEEX UID |
**Request example** ```powershell curl "https://api-spot.weex.com/api/v3/apiReferral/checkUserEligibility" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1735632000000" ```
**Response parameters** | Field name | Type | Description | |:---------------|:--------|:--------------------------------------------------------------------------------| | eligible | Boolean | true=Eligible for referral commission, false=Ineligible | | Reason | String | Reason for ineligibility (for example, user is linked to another referral code) | | noReferralCode | Boolean | true=No referral code linked, false=Already linked to another referral code |
**Response example** ```json { "eligible": true, "reason": "", "noReferralCode": false } ```
--- ## Document: Retrieve broker commission data (broker access only) URL: /api-doc/broker/api/GetBrokerCommissionRecords # Retrieve broker commission data (broker access only) - **GET** ```/api/v3/apiReferral/rebate/recentRecord``` Weight(IP): 5
**Request parameters** | Parameter name | Parameter type | Required | Description | |:-----------------|:-----------------|:----------|:-------------------------------------------------------------------------------------------------------------------------| | symbol | String | Yes | Trading pair. Spot example: `BTCUSDT`, Futures example: `BTCUSDT` | | productType | String | No | Trading type. Supports `SPOT` (default) or `FUTURES` | | coin | String | Yes | Commission asset (e.g. `USDT`, `BTC`) | | page | Integer | No | Page number (starts from 1, default 1) | | pageSize | Integer | No | Items per page (default 100, max 100) | | startTime | String | No | Settlement start date, format `yyyy-MM-dd`. Defaults to 1 month before endTime (include the current day) if not provided | | endTime | String | No | Settlement end date, format `yyyy-MM-dd`. Defaults to the current UTC date if not provided | > Note: `startTime` must be earlier than or equal to `endTime`, and the maximum query range is 90 days.
**Request example** ```powershell curl "https://api-spot.weex.com/api/v3/apiReferral/rebate/recentRecord?symbol=BTCUSDT&coin=USDT&page=1&pageSize=50&startTime=2024-12-01&endTime=2024-12-31" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1735632000000" ```
**Response parameters** | Field name | Type | Description | |:------------|:--------|:------------------------------------------| | current | Integer | Current page number | | pages | Integer | Total pages | | size | Integer | Items per page | | total | Long | Total number of records | | records | Array | Commission record list. See details below | **Commission record fields** | Field name | Type | Description | |:----------------------|:-------|:----------------------| | symbol | String | Trading pair | | dealAmount | String | Total trade volume | | fee | String | Actual fee paid | | feeDeduction | String | Fee deduction | | rebateRate | String | Commission rate | | commissionAsset | String | Commission asset | | commission | String | Commission amount | | totalRebateUsdtAmount | String | Commission in USDT | | settleStartTime | String | Settlement start time | | settleEndTime | String | Settlement end time | | updateTime | String | Last update time |
**Response example** ```json { "current": 1, "size": 10, "total": 1, "records": [ { "symbol": "BTCUSDT", "dealAmount": "74700", "fee": "0.002", "feeDeduction": "0", "rebateRate": "0.55", "commissionAsset": "BTC", "commission": "0.0011", "totalRebateUsdtAmount": "81.55202", "settleStartTime": "2026-04-15 00:00:00", "settleEndTime": "2026-04-15 23:59:59", "updateTime": "2026-04-16 21:51:54" } ] } ```
--- ## Document: Get broker commission rate (broker access only) URL: /api-doc/broker/api/GetBrokerRebateRatio # Get broker commission rate (broker access only) - **GET** ```/api/v3/apiReferral/rebateRatio``` Weight(IP): 5
**Request parameters** None
**Request example** ```powershell curl "https://api-spot.weex.com/api/v3/apiReferral/rebateRatio" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1735632000000" ```
**Response parameters** | Field name | Type | Description | |:------------------------------|:-------|:---------------------------------------------------------------------| | level | String | Broker's current level (BRONZE,SILVER,GOLD) | | directSpotRebateRatio | String | Spot commission rate for broker's direct invitees | | directFuturesRebateRatio | String | Futures commission rate for broker's direct invitees | | noRefferralSpotRebateRatio | String | Spot commission rate for users registered without a referral code | | noRefferralFuturesRebateRatio | String | Futures commission rate for users registered without a referral code | | refferralSpotRebateRatio | String | Spot commission rate for "Invite Friends" referrals | | refferralFuturesRebateRatio | String | Futures commission rate for "Invite Friends" referrals |
**Response example** ```json { "level": "GOLD", "directSpotRebateRatio": "0.55", "directFuturesRebateRatio": "0.50", "noRefferralSpotRebateRatio": "0.45", "noRefferralFuturesRebateRatio": "0.40", "refferralSpotRebateRatio": "0.65", "refferralFuturesRebateRatio": "0.60" } ```
--- ## Document: Broker Rebate API URL: /api-doc/broker/api # Broker Rebate API --- ## Document: FAQs URL: /api-doc/broker/brokerFaq # FAQs > **Last updated:** Apr 23, 2026
> **Summary:** This guide helps brokers quickly integrate with the WEEX OAuth service. --- ## Should the authorization flow be handled by the frontend or the backend? We recommend a "frontend-initiated, backend-driven" approach. The full flow is as follows: 1. **Initiate authorization**: The frontend calls your backend to start the flow. The backend generates the `state`, `code_verifier`, and `code_challenge`, constructs the full authorization URL (including all parameters), and creates an authorization task with an `INIT` status. The backend then returns this URL to the frontend. 2. **Redirect to authorization page**: The frontend redirects the user to the provided URL, where the user completes login and grants permission on the authorization page. 3. **Handle callback**: Upon success, the OAuth server redirects back to your backend with `code` and `state`. The backend validates the `state`, exchanges the code for an access token via the `/token` endpoint, and calls `create-api`. Finally, it saves the binding results and updates the task status to `SUCCESS` or `FAILED`. 4. **Redirect to result page**: Once the backend processing is complete, it redirects the user to your frontend API Key page. 5. **Display result**: The frontend calls your backend to query the binding status and displays the result. --- ## What are the requirements for state? The `state` must be generated by your backend and should be random, unique, and single-use. It must also have a short TTL. When the backend receives the OAuth callback, it must verify that the `state` matches the one stored, hasn't expired, and belongs to a task in a valid state. This is critical for preventing CSRF and replay attacks. --- ## What should I know about PKCE (code_verifier / code_challenge)? The `code_verifier` must be generated and securely stored by your backend. It is required later when exchanging the authorization code for an `access_token`. The `code_challenge` is derived from the `code_verifier`. The `code_challenge_method` is fixed to `S256`. The frontend should never handle or transmit the `code_verifier`. --- ## In what order should the backend process the OAuth callback? Once the backend receives the request containing the `code` and `state`, it should execute the following steps: 1. Retrieve the corresponding task using the `state` and validate its integrity. 2. Update the task status to `PROCESSING`. 3. Exchange the `code and code_verifier` for an `access_token` via the `/token` endpoint. 4. Call the `create-api` interface using the `access_token`. 5. Store the binding result (or failure reason) and update the task status to `SUCCESS` or `FAILED`. 6. Redirect the user to the frontend API Key page. --- ## Can sensitive information like apikey or secret be returned to the frontend via URL? No, this is not recommended. After processing the callback, your backend should redirect the user to a frontend page (such as `/platform/apikey`) and let the frontend retrieve the binding result via an API call. `apikey`, `secret`, `passphrase`, and plaintext error details should never appear in URL parameters, nor should they be recorded in standard application logs. --- ## Document: Update log URL: /api-doc/broker/changelog # Update log | Effective time (UTC+8) | API | Update type | Description | |-------------------------|--------|---------------|-------------------| | 2026-06-22 | [Access Restrictions](/api-doc/spot/QuickStart/AccessRestrictions) | Modified | Updated access restriction rules. | | 2026-04-23 | * | New | Broker API launch | --- ## Document: Contact Us URL: /api-doc/broker/ContactUs # Contact Us For technical issues or any feedback, feel free to reach out to us via the following methods: - Email us at support@weex.com - Join our [Telegram community](https://t.me/+Y72JdNeHcUw3NWQ1) to stay updated and engage with the community. --- ## Document: API introduction URL: /api-doc/broker/intro # API introduction Welcome to the WEEX broker API. This documentation is tailored for brokers, helping you quickly integrate with the WEEX trading platform to enable automated trading, user management, and commission settlement. New features and updates will be released regularly, stay tuned! With this guide, you will learn how to: - Obtain and configure your broker ID - Verify user commission eligibility - Link your broker ID when placing orders - Query commission data and user lists ## Integration setup ### Prerequisites Have a WEEX account and be enrolled in the WEEX affiliate program. ### API key - Log in to the WEEX website and go to the "API Management" page. - Create an API key and configure the following permissions: - Read-only - Spot - Futures - Keep your secret key secure and never share it. ### Application process #### Submit your application: Visit the WEEX website and complete the [broker onboarding form](https://dsg39hlwl5ui.sg.larksuite.com/share/base/form/shrlgfmt5NkSRF2dmjaxXANTfLk). #### Review process: The WEEX BD team will review your application within three working days. #### Get your credentials: - Once approved, you will receive an email with the following details: - Unique broker ID (format: WEEX + 6 digits, such as WEEX123456) - Initial commission rate configuration - API integration documentation link - Technical support group invitation ## Verify commission eligibility Refer to [Get commission eligibility (broker access only)](/api-doc/broker/api/CheckUserEligibility) for more details. ## Linking broker ID when placing orders ### Spot orders The request structure is the same as the [Spot order (TRADE)](/api-doc/spot/orderApi/PlaceOrder) endpoint. You can include the broker ID when placing an order. **Format requirements:**
The newClientOrderId must start with `b-{brokerId}`
Example: `b-WEEX123456-20260319001`
Total length must be ≤ 64 characters
### Futures orders The request structure is the same as the [order (TRADE)](/api-doc/contract/Transaction_API/PlaceOrder) endpoint. You can link the broker ID using a custom field when placing an order. **Format requirements:**
The newClientOrderId must start with `b-{brokerId}`
Example: `b-WEEX123456-20260319001`
Total length must be ≤ 64 characters
## Commission query endpoints - [Get broker commission data (broker access only)](/api-doc/broker/api/GetBrokerCommissionRecords) - [Get broker commission rates (broker access only)](/api-doc/broker/api/GetBrokerRebateRatio) ## Rate limits REST API requests are subject to rate limits. If the limit is exceeded, "429: Too many requests" will be returned. - Rate limit basis: Endpoints that require an API key are rate-limited by UID. Endpoints without an API key are rate-limited by IP. Each endpoint specifies whether limits are based on IP or UID, along with its request weight. Endpoints have different weights. More resource-intensive endpoints carry higher weights. IP-based and UID-based limits are tracked separately. For IP-based limits, all endpoints share 500 weight/10s. For UID-based limits, all endpoints share 500 weight/10s. - Rate limit reached: If a 429 response is returned, stop sending requests immediately. Do not abuse the API. --- ## Document: OAuth integration guide URL: /api-doc/broker/oAuth # OAuth integration guide Welcome to the WEEX OAuth service. This guide is designed to help third-party platforms ("Platform") securely and efficiently integrate with the WEEX user authorization system. With user authorization, your platform can obtain user-specific API keys to perform actions on their behalf, including market data queries, spot trading, and futures trading. ## Process overview The integration process consists of three main steps: 1. Platform registration: Contact WEEX BD to register your platform. You will receive a unique **clientId** and **secret key**, and configure your callback URL. 2. User authorization: Guide WEEX users to log in and authorize access to obtain a temporary authorization code. 3. Obtain credentials: Use the code on your backend to obtain an `access_token`. Then use the `access_token` to retrieve the API key, secret key, and passphrase for API calls. ## Integration setup Provide the following information to WEEX to complete platform registration: | Configuration | Description | Example | |-------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------| | Platform name | Your name, displayed on the user authorization page. English only | MyTrading | | WEEX UID | The WEEX user ID associated with your platform, used for identity linking | 123456 | | Privacy policy | Your platform's privacy policy URL | https://www.mytrading.com/en/privacy-policy | | Terms of service | Your platform's terms of service URL | https://www.mytrading.com/en/terms-of-use | | Platform logo | Logo image displayed on the user authorization page | | | Contact person | Technical or business contact | | | Email | Contact email address | tech@mytrading.com | | Phone | Contact phone number | | | Callback URL | **Key configuration**
After user authorization, the WEEX OAuth server will redirect to this URL with an authorization code. Multiple callback URLs are supported, but the request must exactly match one of them | https://api.mytrading.com/oauth/callback
https://sandbox.mytrading.com/oauth/callback | | Outgoing IP | For security purposes, please provide the **public outgoing IP addresses** of your platform's servers. WEEX Operations will whitelist these IPs; otherwise, any requests from unauthorized IPs will be blocked. | 47.100.1.1, 47.100.1.2 | ## Integration steps ### 1. Construct the authorization URL ```bash # OAuth authorization page example https://www.weex.com/oauth? clientId={clientId}& responseType=code& scope=create:apikey& redirectUri={redirectUri}& state={state}& codeChallenge={codeChallenge}& codeChallengeMethod={codeChallengeMethod} ``` **Request parameters:** | Parameter | Description | Notes | |:--------------------|:--------------------|:-------------------------------------------------------------------------------------------------------| | clientId | Merchant identifier | Obtained after merchant initialization | | responseType | Response type | Fixed value: code | | scope | Permission | Pass `create:apikey` | | state | State parameter | Random string to prevent CSRF attacks, 22–128 characters from \[A-Z, a-z, 0-9, -, ., \_, ~] | | redirectUri | Callback URL | Must be configured in the admin panel | | codeChallenge | PKCE challenge | PKCE challenge value. Format defined in RFC 7636: 43–128 characters from \[A-Z, a-z, 0-9, -, ., _, ~] | | codeChallengeMethod | PKCE method | PKCE method. Currently only S256 is supported | **Note:** Since PKCE is enforced on the server side, the client must generate the PKCE parameters. **Step 1: Generate the Code Verifier** The client generates a high-entropy random string code_verifier. - **Requirements**: Consists of characters from \[A-Z, a-z, 0-9, -, ., _, ~] - **Length**: Recommended 43 characters or more (maximum 128 characters) **Step 2: Generate a Code Challenge** Apply SHA256 hashing to the code_verifier, then encode it using Base64URL (without the trailing "=" padding). `code_challenge = Base64URL(SHA256(code_verifier))` ```java import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.util.Base64; import java.security.SecureRandom; public class PKCEUtils { public static void main(String[] args) throws Exception { // 1. Generate code_verifier (random string) SecureRandom sr = new SecureRandom(); byte[] codeValue = new byte[32]; sr.nextBytes(codeValue); String codeVerifier = Base64.getUrlEncoder().withoutPadding().encodeToString(codeValue); // 2. Generate code_challenge (S256) byte[] bytes = codeVerifier.getBytes(StandardCharsets.US_ASCII); MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); byte[] digest = messageDigest.digest(bytes); String codeChallenge = Base64.getUrlEncoder().withoutPadding().encodeToString(digest); System.out.println("code_verifier: " + codeVerifier); System.out.println("code_challenge: " + codeChallenge); } } ``` ---- ### 2. Authorization callback successful After the user completes authorization, the page will perform a redirect 301 to the redirectUri callback URL ```bash # Assume redirect_uri = https://www.example.com/callback # Callback URL: https://www.example.com/callback/? code=sS38ddda0ddPC342342hhfuiu& state=1234abc ``` ---- ### 3. Fetch access_token API information: - URL: https://gateway.weex.com/v1/oauth/token - Method: POST - Note: After successfully refreshing the `access_token` using a refresh_token, the previous `access_token` will be invalidated. Each refresh_token can have only one active `access_token`. - Signature: Refer to [signature rules](/api-doc/broker/sign) Request parameters: | Parameter | Type | Required | Description | |:----------------|:---------|:------------|:-------------------------------------------------------------------------------------------------------| | grantType | string | Yes | Authorization type. Supported values: authorization_code, refresh_token | | code | string | No | Returned authorization code. Required when grantType=authorization_code | | redirectUri | string | No | Callback URL. Must match the one used during authorization. Required when grantType=authorization_code | | codeVerifier | string | No | PKCE original value. Required when grantType=authorization_code | | refresh_token | string | No | Refresh token. Required when grantType=refresh_token | Request example: ```powershell curl -v -X POST {url} \ -H 'Client-Id: weex123456' \ -H 'Sign: *******' \ -H 'Timestamp: 1735689600000' \ -H 'Nonce: Nonce' \ -d '{ "grantType": "authorization_code", "code": "auth_code_xxx", "redirectUri": "https://api.wundertrading.com/oauth/callback", "codeVerifier": "code-verifier-demo" }' ``` Response parameters: | Parameter | Type | Description | |:-----------------|:-------|:------------------------------------------| | accessToken | String | Access token | | refreshToken | String | Refresh token | | tokenType | String | Token type, fixed as Bearer | | expiresIn | int | Access token remaining time (in seconds) | | refreshExpiresIn | int | Refresh token remaining time (in seconds) | | scope | String | Scope | Response example: ```json { "code": "00000", "msg": "success", "requestTime": 1774621008941, "data": { "accessToken": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiI3NzU0MDkwNjQwIiwiYXVkIjoiY2FnZSIsInNjb3BlIjoiY3JlYXRlOmFwaWtleSIsImlzcyI6Imh0dHBzOi8vd2VleC5jb20iLCJleHAiOjE3NzQ2MjQ2MDgsImlhdCI6MTc3NDYyMTAwOCwianRpIjoiMzkifQ.mMVGvW0EeVO5TMxRiUDAyGmf64bcyEFXy0kz8xjv3wRp2pjsxpQUdT1Jn2V2SD0I6LhsCCRDp9Rhl6UuKnHYESBrqKWQONwf1nXTwIFB8Fmw_MqWFWVpi9nlaYBUIGiayuybllYZB1vN06fXRm5yq068UJFD_lSWMkrHJfUu5I7dD-JpwN9UNTsi5NY2a5vUc0WyBSPOnfnPBPr8x5PNB7uc9fr1Uew9QrmO2WnLuDCcDnZ2XGulzvmKC3b2ZXADDBKleuXAAgYzq-t-M4NBI2EjNP1wvpMGeTKyNTBKrXY4Wo0MQdipLGlKsr3cnpKdNqGWi9SzBSp-KctcGrpGew", "refreshToken": "o_3ubYfLM9zaqbwF_Xo9Jb13vyq-KPP6sVlGEAL3TjrBmbzao-xuT82VDVRFA-bCGuim2V-A_6vCbIiZsvdbjIefaGKaskNubXM9Wk3--7QwoSDqtpsUyD9KnJtoqToe", "tokenType": "Bearer", "expiresIn": 3600, "refreshExpiresIn": 36000, "scope": "create:apikey" } } ``` ---- ### 4\. Obtain the API key API information: - URL: https://gateway.weex.com/v1/oauth/resource/create-api - Method: POST - Authorization: Include authorization in the request header - Format: `Bearer {access_token}` - Example: `Authorization: Bearer 12345` Note: 1. Each user can create only one API key linked to a third-party platform. The request will succeed only if no API key is currently linked. To relink, the existing API key must be deleted first. 2. After the API key is created, securely store the API key, secret key, and passphrase. These values are returned only upon the first successful API key creation. 3. If the user's API status is not **normal**, the newly created API key may not be available for immediate use. Request example: ```powershell curl {url} \ -H "Authorization: Bearer {access_token}" ``` Response example: ```json { "code": "00000", "data": { "apiKey": "ak_xxxxxxxxx", "secret": "sk_xxxxxxxxx", "passphrase": "pp_xxxxxxxxx" }, "msg": "success", "requestTime": "1768529101682" } ``` ## Error example ```json { "code": "80000", "msg": "param error", "requestTime": "1768529101682" } ``` **Response codes** | Response code | Response message | Description | |----------------|----------------------------------------|----------------------------------------------| | 00000 | success | Request successful | | 40400 | resource not found | Endpoint path or resource not found | | 80000 | param error | Invalid request parameters | | 80002 | client invalid | Invalid client | | 80003 | client auth failed | Client signature verification failed | | 80004 | PKCE code_verifier verification failed | Client PKCE verification failed | | 80005 | client mismatch | Client mismatch | | 80006 | expired request | Request expired | | 80007 | replay request | Replay request | | 80008 | uid duplicate | The UID is already linked to a client | | 80009 | client unauthorized | Client unauthorized | | 80010 | user invalid | Invalid user | | 80100 | code invalid | Invalid authorization code | | 80200 | redirect uri invalid | Invalid redirect URI | | 80201 | redirect uri mismatch | Redirect URI mismatch | | 80300 | access token invalid | Invalid access token | | 80301 | access token auth fail | Access token authentication failed | | 80400 | refresh token invalid | Invalid refresh token | | 80500 | grant type invalid | Invalid grant_type | | 80600 | scope invalid | Invalid scope | | 80601 | scope insufficient | Insufficient scope permission | | 80700 | unsupported response type | Unsupported response type | | 80800 | state invalid | Invalid state | | 80900 | code challenge invalid | Invalid PKCE code_challenge | | 80901 | code challenge method invalid | Invalid PKCE code_challenge_method | | 81000 | api key permission invalid | Invalid API key permissions | | 81001 | api key already bound | API key already linked | | 81002 | user api key num exceeds max limit | User API key count exceeds the maximum limit | ## Security and best practices ### Protect your keys: client_secret, code_verifier, as well as the retrieved secret_key and passphrase must be stored on the backend. Never expose them in frontend code or applications. ### Validate state: Strictly verify the state parameter in the callback to prevent CSRF attacks. A random string is recommended. ### HTTPS requirement: All API requests must be made over HTTPS. --- ## Document: Request signing URL: /api-doc/broker/sign # Request signing ## Overview On the OAuth authorization platform, the access\_token endpoint is a sensitive API that is called by third-party servers to obtain tokens. In addition to validating standard OAuth parameters, the server must also verify that the request is initiated by a registered client, ensure the request has not been tampered with during transmission, and prevent replay attacks. To achieve this, a client-side request signing mechanism based on HMAC-SHA256 is introduced, providing: - Client authentication - Request integrity protection - Replay attack prevention ## Request headers | Header name | Required | Description | |---------------|------------|-----------------------------------------------------------------------| | Client-Id | Yes | Identifier for the client, corresponding to the registered client\_id | | Sign | Yes | The request signature | | Timestamp | Yes | The request initiation timestamp in milliseconds | | Nonce | Yes | A unique, single-use random string to prevent replay attacks | ## Signing rules **Field description** - timestamp: The request timestamp (in milliseconds) must match the `Timestamp` header - nonce: A one-time random string. Must match the `Nonce` header and is used to prevent replay attacks. - method: The HTTP request method (such as POST, GET), in uppercase. - requestPath: The API endpoint path, such as `/v1/oauth/token`. - queryString: The query string after `?` in the request URL. Leave empty if not present. - body: The request payload as a string. If there is no request body (typically for GET requests), use an empty string. **Signature format rules if queryString is empty** `timestamp + nonce + method.toUpperCase() + requestPath + body` **Signature format rules if queryString is not empty** `timestamp + nonce + method.toUpperCase() + requestPath + "?" + queryString + body` **Example** **Example 1: Without query string (token request)** - timestamp = `1710000000000` - nonce = `abc123xyz` - method = `"POST"` - requestPath = `"/v1/oauth/token"` - body = `{"grantType":"authorization_code","code":"code123","redirectUri":"https://client.example.com/callback","codeVerifier":"verifier123"}` **Generate the string to be signed:** `1710000000000abc123xyzPOST/v1/oauth/token{"grantType":"authorization_code","code":"code123","redirectUri":"https://client.example.com/callback","codeVerifier":"verifier123"}` **Steps to generate the final signature** 1. Use the `clientSecret` to compute an HMAC-SHA256 hash of the `baseString` and encode the result using Base64. - `Sign = Base64(HMAC-SHA256(clientSecret, baseString))` ## Signature example ```java package com.weex.utils; import org.apache.http.client.methods.CloseableHttpResponse; 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; import java.util.UUID; public class OAuthApiClient { /** * Replace with your actual clientId / clientSecret */ private static final String CLIENT_ID = "your-client-id"; private static final String CLIENT_SECRET = "your-client-secret"; /** * Replace with your OAuth authorization server base URL */ private static final String BASE_URL = "https://auth.example.com"; /** * HMAC-SHA256 algorithm */ private static final String HMAC_SHA256 = "HmacSHA256"; /** * Generate signature * * Signing rules: * 1. Without queryString: * timestamp + nonce + method.toUpperCase() + requestPath + body * *2. With queryString: * timestamp + nonce + method.toUpperCase() + requestPath + queryString + body * * Notes: * - Use "" if queryString is empty * - If not empty, queryString should include "?a=1&b=2" * - Use "" if body is empty */ public static String generateSignature(String clientSecret, String timestamp, String nonce, String method, String requestPath, String queryString, String body) throws Exception { String safeQueryString = queryString == null ? "" : queryString; String safeBody = body == null ? "" : body; String message = timestamp + nonce + method.toUpperCase() + requestPath + safeQueryString + safeBody; return hmacSha256Base64(clientSecret, message); } /** * Computes HMAC-SHA256 and encodes the result in Base64. */ private static String hmacSha256Base64(String secretKey, String message) throws Exception { SecretKeySpec secretKeySpec = new SecretKeySpec( secretKey.getBytes(StandardCharsets.UTF_8), HMAC_SHA256 ); Mac mac = Mac.getInstance(HMAC_SHA256); mac.init(secretKeySpec); byte[] signatureBytes = mac.doFinal(message.getBytes(StandardCharsets.UTF_8)); return Base64.getEncoder().encodeToString(signatureBytes); } /** * Generates a timestamp in milliseconds */ private static String generateTimestamp() { return String.valueOf(System.currentTimeMillis()); } /** * Generates a random nonce */ private static String generateNonce() { return UUID.randomUUID().toString().replace("-", ""); } /** * Sends a POST request * * Notes: * - The body must be the exact JSON string sent in the request * - The body used for signing must match the request body exactly */ public static String sendPost(String clientId, String clientSecret, String requestPath, String queryString, String body) throws Exception { String timestamp = generateTimestamp(); String nonce = generateNonce(); String signature = generateSignature( clientSecret, timestamp, nonce, "POST", requestPath, queryString, body ); String url = BASE_URL + requestPath + (queryString == null ? "" : queryString); HttpPost postRequest = new HttpPost(url); postRequest.setHeader("Client-Id", clientId); postRequest.setHeader("Sign", signature); postRequest.setHeader("Timestamp", timestamp); postRequest.setHeader("Nonce", nonce); postRequest.setHeader("Content-Type", "application/json"); StringEntity entity = new StringEntity(body, StandardCharsets.UTF_8); postRequest.setEntity(entity); try (CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = httpClient.execute(postRequest)) { int statusCode = response.getStatusLine().getStatusCode(); String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8); System.out.println("HTTP Status: " + statusCode); return responseBody; } } /** * Example: Exchange authorization_code for token */ public static void main(String[] args) { try { String requestPath = "/v1/oauth/token"; /** * Note: * This must be the exact JSON string sent in the request. * The same body must be used for both signing and sending. */ String body = "{" + "\"grantType\":\"authorization_code\"," + "\"code\":\"auth_code_xxx\"," + "\"redirectUri\":\"https://client.example.com/callback\"," + "\"codeVerifier\":\"code_verifier_xxx\"" + "}"; String response = sendPost( CLIENT_ID, CLIENT_SECRET, requestPath, "", body ); System.out.println("Response: " + response); } catch (Exception e) { e.printStackTrace(); } } } ``` --- ## Document: llms.txt URL: /api-doc/copy/AIResources/llms-txt # llms.txt --- ## Document: FAQs URL: /api-doc/copy/apifaq # FAQs ## Who can create a Copy Trading API? Only users with trader status can create a Copy Trading API. ## How many API keys can be created for each copy trading project? Each trader account can create up to 1 API key. ## Are assets and positions isolated for copy trading projects? Yes. The funds and positions in a copy trading account are fully isolated and completely independent from regular futures trading. ## Does the Copy Trading API support spot trading? No. The Copy Trading API does not currently support spot trading. ## How can I query a trader's copy trading position information? Use the Copy Trading API to query all positions by calling `/capi/v3/account/position/allPosition`. This endpoint returns the trader's current copy trading positions. If this endpoint is called with a regular API, it returns the trader's regular futures position information. --- ## Document: Update log URL: /api-doc/copy/changelog # Update log | Effective Time (UTC+8) | API | Update Type | Description | |------------------------|-------|--------------|-----------------------------------------| | 2026-06-23 | * | New | The Copy Trading API has been launched. | --- ## Document: Contact Us URL: /api-doc/copy/ContactUs # Contact Us For technical issues or any feedback, feel free to reach out to us via the following methods: - Email us at support@weex.com - Join our [Telegram community](https://t.me/+Y72JdNeHcUw3NWQ1) to stay updated and engage with the community. --- ## Document: Error Codes URL: /api-doc/copy/ExampleOfErrorCode # Error Codes Here is the error JSON payload: ```json { "code": -1121, "msg": "Invalid symbol." } ``` Errors consist of two parts: an error code and a message. Codes are universal, but messages can vary. ## 10xx - General Server or Network issues ### -1000 UNKNOWN_ERROR - An unknown error occurred. ### -1054 SYSTEM_ERROR - System error, please retry later. ## 10xx - Authentication / Access ### -1040 ACCESS_KEY_EMPTY - ACCESS_KEY header is required. ### -1041 ACCESS_SIGN_EMPTY - ACCESS_SIGN header is required. ### -1042 ACCESS_TIMESTAMP_EMPTY - ACCESS_TIMESTAMP header is required. ### -1043 INVALID_ACCESS_TIMESTAMP - Invalid ACCESS_TIMESTAMP. ### -1044 INVALID_ACCESS_KEY - Invalid ACCESS_KEY. ### -1045 INVALID_CONTENT_TYPE - Invalid Content-Type, please use application/json. ### -1046 ACCESS_TIMESTAMP_EXPIRED - Request timestamp expired. ### -1047 API_AUTH_ERROR - API authentication failed. ### -1049 API_KEY_OR_PASSPHRASE_INCORRECT - API key or passphrase incorrect. ### -1050 USER_STATUS_FORBIDDEN - User status is abnormal. ### -1051 PERMISSION_DENIED - Permission denied. ### -1052 INSUFFICIENT_PERMISSIONS - Insufficient permissions for this action. ### -1053 PERMISSION_VALIDATION_FAILED - Permission validation failed. ### -1055 USER_AUTH_NOT_SAFE - User must bind phone or Google authenticator. ### -1056 ILLEGAL_IP - Invalid IP address. ### -1057 USER_LOCKED - User account is locked. ### -1058 NO_PERMISSION_TRADE_PAIR - The trading pair is not supported via the API. Check the supported symbols here: [https://api-contract.weex.com/capi/v3/market/apiTradingSymbols](https://api-contract.weex.com/capi/v3/market/apiTradingSymbols). ### -1059 HIGH_FREQUENCY_ORDER_LIMITED - Too many high-frequency order requests in current window. ### -1060 API_KEY_SYMBOL_NOT_BOUND - This API key is not bound to the trading pair. ## 11xx - Request Content / Parameters ### -1115 INVALID_TIME_IN_FORCE - Invalid timeInForce. ### -1116 INVALID_ORDER_TYPE - Invalid order type. ### -1117 INVALID_SIDE - Invalid side. ### -1121 INVALID_SYMBOL - Invalid symbol. ### -1128 INVALID_PARAM_COMBINATION - Combination of optional parameters invalid. ### -1135 INVALID_JSON - Invalid JSON request. ### -1140 PARAM_VALIDATE_ERROR - Parameter validation failed. - limit must be between %d and %d. - startTime must be a valid millisecond timestamp. - endTime must be a valid millisecond timestamp. ### -1141 PARAM_EMPTY - Parameter '%s' cannot be empty. ### -1142 PARAM_ERROR - Parameter '%s' is invalid. ### -1150 REQUEST_METHOD_NOT_SUPPORTED - Request method not supported. ### -1160 DECIMAL_PRECISION_ERROR - Decimal precision error. ### -1170 QUERY_TIME_OUT_OF_RANGE - startTime must be within the last %d days. - Time range cannot exceed %d days. ### -1171 START_TIME_AFTER_END_TIME - startTime cannot be greater than endTime. ### -1180 CLIENT_OID_LENGTH_ERROR - client_oid length must not exceed 40 and must not contain special characters. ### -1190 FORBIDDEN_ACCESS - Access forbidden. Please contact support. ## 50xx - Copy Trading ### -5000 BROKER_CONTACT_ADMIN - Please contact the administrator. ### -5001 COPY_TRADE_API_KEY_ONLY - This API can only be called with a copy trade type API Key. ### -5002 COPY_TRADE_API_KEY_NOT_SUPPORTED - This API does not support copy trade type API Key. ### -5003 COPY_TRADE_TPSL_QUANTITY_MUST_BE_ZERO - Copy trade type API Key only supports full-position TP/SL; quantity must be 0. ### -5004 COPY_TRADE_TPSL_EXECUTE_PRICE_MUST_BE_MARKET - Copy trade type API Key only supports market TP/SL execution; executePrice must be null or 0. --- ## Document: Close Copy Follower Position (TRADE) URL: /api-doc/copy/future-copytrade/follower/CloseCopyFollowerPosition # Close Copy Follower Position (TRADE) - **POST** ```/capi/v3/copy/follower/closePos``` Weight(IP): 50
**Request Parameters** | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | symbol | String | Yes | Symbol. | | copyNo | Long | Yes | Tracking order ID to close. |
**Request Example** ```powershell curl -X POST "https://api-contract.weex.com/capi/v3/copy/follower/closePos" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "Content-Type: application/json" \ -d '{ "symbol": "BTCUSDT", "copyNo": 9000000001 }' ```
**Response Parameters** Returns the standard success response.
**Response Example** ```json { "code": "200", "msg": "success", "requestTime": 1627354109502 } ```
--- ## Document: Get Copy Follower History Orders (USER_DATA) URL: /api-doc/copy/future-copytrade/follower/GetCopyFollowerHistoryOrders # Get Copy Follower History Orders (USER_DATA) - **GET** ```/capi/v3/copy/follower/historyOrders``` Weight(IP): 10
**Request Parameters** | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | symbol | String | No | Filter by symbol, for example `BTCUSDT`. | | limit | Integer | No | Page size, 1-100. Default: 100. | | startTime | Long | No | Start time in milliseconds. The maximum query range is 90 days. | | endTime | Long | No | End time in milliseconds. The maximum query range is 90 days. | | nextKeyId | Long | No | Cursor ID returned from the previous page. | | nextKeyTime | Long | No | Cursor time returned from the previous page. |
**Request Example** ```powershell curl "https://api-contract.weex.com/capi/v3/copy/follower/historyOrders?symbol=BTCUSDT&limit=50" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" ```
**Response Parameters** | Parameter | Type | Description | |-----------|------|-------------| | list | Array | History tracking order list. The item structure is the same as [Get Copy Follower Open Orders](./GetCopyFollowerOpenOrders#response-parameters). | | nextFlag | Boolean | Whether there is a next page. | | nextKey | Object | Cursor for the next page. | | nextKey.nextKeyId | Long | Cursor ID. | | nextKey.nextKeyTime | Long | Cursor time in milliseconds. |
**Response Example** ```json { "list": [ { "trackingNo": 9000000001, "traderName": "Lead Trader", "openOrderId": 702345678901234600, "closeOrderId": 702345678901234700, "traderID": 123456, "symbol": "BTCUSDT", "openLeverage": 10, "openPriceAvg": "69000", "openTime": 1764505800000, "openSize": "0.01", "openFee": "0.414", "openMarginAmount": "69", "openFillSize": "0.01", "positionSide": "LONG", "status": "CLOSED", "tpTriggerPrice": "72000", "slTriggerPrice": "67000", "closeAvgPrice": "70000", "closeSize": "0.01", "closeTime": "1764505900000", "realizedPnl": "10", "profitRate": "0.12", "netProfit": "9.5", "createdTime": 1764505800000, "updateTime": 1764505900000 } ], "nextFlag": false, "nextKey": null } ```
--- ## Document: Get My Copy Traders (USER_DATA) URL: /api-doc/copy/future-copytrade/follower/GetCopyFollowerMyTraders # Get My Copy Traders (USER_DATA) - **GET** ```/capi/v3/copy/follower/myTraders``` Weight(IP): 10
**Request Parameters** | Parameter | Type | Required | Description | |-------------|---------|-----------|-----------------------------------------| | pageNo | Integer | No | Page number, starts from 1. Default: 1. | | pageSize | Integer | No | Page size, 1-100. Default: 100. |
**Request Example** ```powershell curl "https://api-contract.weex.com/capi/v3/copy/follower/myTraders?pageNo=1&pageSize=20" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" ```
**Response Parameters** | Parameter | Type | Description | |-----------|------|-------------| | list | Array | Trader list. | | list[].traderId | Long | Copy trader UID. | | list[].traderName | String | Copy trader name. | | list[].copyTradingBalance | String | Copy trading balance. | | list[].traceTotalProfit | String | Copy trading net profit. | | list[].totalInvestment | String | Total investment. | | list[].availableBalance | String | Available copy trading balance. | | list[].transferableBalance | String | Transferable copy trading balance. | | nextFlag | Boolean | Whether there is a next page. | | total | Integer | Total count. |
**Response Example** ```json { "list": [ { "traderId": 123456, "traderName": "Lead Trader", "copyTradingBalance": "1000", "traceTotalProfit": "125.5", "totalInvestment": "500", "availableBalance": "800", "transferableBalance": "300" } ], "nextFlag": false, "total": 1 } ```
--- ## Document: Get Copy Follower Open Orders (USER_DATA) URL: /api-doc/copy/future-copytrade/follower/GetCopyFollowerOpenOrders # Get Copy Follower Open Orders (USER_DATA) - **GET** ```/capi/v3/copy/follower/openOrders``` Weight(IP): 10
**Request Parameters** | Parameter | Type | Required | Description | |-------------|---------|------------|------------------------------------------| | symbol | String | No | Filter by symbol, for example `BTCUSDT`. | | limit | Integer | No | Page size, 1-100. Default: 100. | | page | Integer | No | Page number, starts from 1. Default: 1. |
**Request Example** ```powershell curl "https://api-contract.weex.com/capi/v3/copy/follower/openOrders?symbol=BTCUSDT&traderId=123456&limit=50&page=1" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" ```
**Response Parameters** Returns an array of follower tracking orders. | Parameter | Type | Description | |-----------|------|-------------| | trackingNo | Long | Tracking order ID. | | traderName | String | Copy trader name. | | openOrderId | Long | Open order ID generated by the trading system. | | closeOrderId | Long | Close order ID. | | traderID | Long | Copy trader UID. | | symbol | String | Symbol. | | openLeverage | Integer | Open leverage. | | openPriceAvg | String | Average open price. | | openTime | Long | Open time in milliseconds. | | openSize | String | Open order size. | | openFee | String | Open fee. | | openMarginAmount | String | Open margin amount. | | openFillSize | String | Filled open size. | | positionSide | String | Position side: `LONG`, `SHORT`, or `BOTH`. | | status | String | Tracking order status. | | tpTriggerPrice | String | Take-profit trigger price. | | slTriggerPrice | String | Stop-loss trigger price. | | closeAvgPrice | String | Average close price. | | closeSize | String | Close size. | | closeTime | String | Close time. | | realizedPnl | String | Realized PnL. | | profitRate | String | Profit rate. | | netProfit | String | Follower net profit. | | createdTime | Long | Create time in milliseconds. | | updateTime | Long | Update time in milliseconds. |
**Response Example** ```json [ { "trackingNo": 9000000001, "traderName": "Lead Trader", "openOrderId": 702345678901234600, "closeOrderId": 0, "traderID": 123456, "symbol": "BTCUSDT", "openLeverage": 10, "openPriceAvg": "69000", "openTime": 1764505800000, "openSize": "0.01", "openFee": "0.414", "openMarginAmount": "69", "openFillSize": "0.01", "positionSide": "LONG", "status": "HAVE_OPEN", "tpTriggerPrice": "72000", "slTriggerPrice": "67000", "closeAvgPrice": "", "closeSize": "0", "closeTime": "", "realizedPnl": "0", "profitRate": "0.12", "netProfit": "0", "createdTime": 1764505800000, "updateTime": 1764505900000 } ] ```
--- ## Document: Get Copy Follower Settings (USER_DATA) URL: /api-doc/copy/future-copytrade/follower/GetCopyFollowerSettings # Get Copy Follower Settings (USER_DATA) - **GET** ```/capi/v3/copy/follower/settings``` Weight(IP): 10
**Request Parameters** | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | traderId | Long | Yes | Copy trader UID. |
**Request Example** ```powershell curl "https://api-contract.weex.com/capi/v3/copy/follower/settings?traderId=123456" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" ```
**Response Parameters** Returns an array. Unified settings return one item; separated settings return one item per symbol. | Parameter | Type | Description | |-----------|------|-------------| | copyEnable | Boolean | Whether the user is currently copying this trader. | | symbol | String | Symbol. Unified settings return `null`. | | symbols | Array | Symbol list. Used for unified settings. | | productType | String | Product type, currently `USDT-FUTURES`. | | settingMode | String | Setting mode: `unified` or `per_symbol`. | | traceType | String | Copy type: `percent` or `amount`. | | traceValue | String | Copy value. | | maxHoldSize | String | Maximum copy holding size. | | marginType | String | Margin type: `cross`, `isolated`, or `trader`. | | marginCoin | String | Margin coin, currently `USDT`. | | leverageType | String | Leverage type: `fixed`, `trader`, or `specify`. | | longLeverage | Integer | Long leverage. | | shortLeverage | Integer | Short leverage. | | customLeverages | Array | Custom leverage list. | | customLeverages[].symbol | String | Symbol. | | customLeverages[].longLeverage | Integer | Long leverage. | | customLeverages[].shortLeverage | Integer | Short leverage. | | takeProfitRatio | String | Take-profit ratio. | | stopLossRatio | String | Stop-loss ratio. | | slippageRatio | String | Slippage ratio. |
**Response Example** ```json [ { "copyEnable": true, "symbol": null, "symbols": ["BTCUSDT", "ETHUSDT"], "productType": "USDT-FUTURES", "settingMode": "unified", "traceType": "amount", "traceValue": "100", "maxHoldSize": "1000", "marginType": "trader", "marginCoin": "USDT", "leverageType": "specify", "longLeverage": 10, "shortLeverage": 10, "customLeverages": [ { "symbol": "BTCUSDT", "longLeverage": 10, "shortLeverage": 10 } ], "takeProfitRatio": "0.2", "stopLossRatio": "0.1", "slippageRatio": "0.01" } ] ```
--- ## Document: Follower API URL: /api-doc/copy/future-copytrade/follower # Follower API --- ## Document: Stop Copying Trader (TRADE) URL: /api-doc/copy/future-copytrade/follower/StopCopyFollower # Stop Copying Trader (TRADE) - **POST** ```/capi/v3/copy/follower/stopCopy``` Weight(IP): 10
**Request Parameters** | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | traderId | Long | Yes | Copy trader UID to stop copying. |
**Request Example** ```powershell curl -X POST "https://api-contract.weex.com/capi/v3/copy/follower/stopCopy" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "Content-Type: application/json" \ -d '{ "traderId": 123456 }' ```
**Response Parameters** Returns the standard success response.
**Response Example** ```json { "code": "200", "msg": "success", "requestTime": 1627354109502 } ```
--- ## Document: Update Copy Follower Settings (TRADE) URL: /api-doc/copy/future-copytrade/follower/UpdateCopyFollowerSettings # Update Copy Follower Settings (TRADE) - **POST** ```/capi/v3/copy/follower/settings``` Weight(IP): 10
**Request Parameters** | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | traderId | Long | Yes | Copy trader UID. | | settingType | String | Yes | Setting mode: `unified` or `per_symbol`. | | unifiedTraceConfig | Object | Conditional | Required when `settingType` is `unified`. `symbols` controls which copy-trading symbols to follow. | | symbolTraceConfigs | Array | Conditional | Required when `settingType` is `per_symbol`. You must pass one config for every copy-trading symbol. | **TraceConfig Object** | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | symbol | String | Conditional | Symbol, for example `BTCUSDT`. Required only for `symbolTraceConfigs`. | | symbols | Array | Conditional | Symbol list. Required only for `unifiedTraceConfig`; every symbol must be supported by copy trading. | | traceType | String | Yes | Copy type: `percent` or `amount`. | | traceValue | String | Yes | Copy value. | | maxHoldQty | String | No | Maximum holding quantity, range `10`-`100000`. Required for `symbolTraceConfigs`. | | stopProfitRatio | String | No | Take-profit ratio, range `0`-`4`. Required for `symbolTraceConfigs`. | | stopLossRatio | String | No | Stop-loss ratio, range `0`-`4`. Required for `symbolTraceConfigs`. | | slippageRatio | String | No | Slippage ratio. `0` means no limit; otherwise the range is `0.001`-`0.01`. Required for `symbolTraceConfigs`. | | marginType | String | No | Margin type: `cross`, `isolated`, or `trader`. For `symbolTraceConfigs`, only `trader` is allowed. | | leverageType | String | No | Leverage type: `fixed`, `trader`, or `specify`. For `symbolTraceConfigs`, only `fixed` and `trader` are allowed. | | fixedLongLeverage | Integer | No | Fixed long leverage. Required when `symbolTraceConfigs[].leverageType` is `fixed`; defaults to `10` for unified settings when omitted. | | fixedShortLeverage | Integer | No | Fixed short leverage. Required when `symbolTraceConfigs[].leverageType` is `fixed`; defaults to `10` for unified settings when omitted. | | customLeverages | Array | Conditional | Custom leverage list. Required when unified `leverageType` is `specify`; its symbols must exactly match `unifiedTraceConfig.symbols`. | | customLeverages[].symbol | String | Yes | Symbol. | | customLeverages[].longLeverage | Integer | No | Long leverage. Default: `10`. | | customLeverages[].shortLeverage | Integer | No | Short leverage. Default: `10`. |
**Unified Request Example** ```powershell curl -X POST "https://api-contract.weex.com/capi/v3/copy/follower/settings" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" \ -H "Content-Type: application/json" \ -d '{ "traderId": 123456, "settingType": "unified", "unifiedTraceConfig": { "symbols": ["BTCUSDT", "ETHUSDT"], "traceType": "amount", "traceValue": "100", "maxHoldQty": "1000", "stopProfitRatio": "0.2", "stopLossRatio": "0.1", "slippageRatio": "0.001", "marginType": "trader", "leverageType": "specify", "customLeverages": [ { "symbol": "BTCUSDT", "longLeverage": 10, "shortLeverage": 10 }, { "symbol": "ETHUSDT", "longLeverage": 10, "shortLeverage": 10 } ] } }' ``` **Per-Symbol Request Example** ```json { "traderId": 123456, "settingType": "per_symbol", "symbolTraceConfigs": [ { "symbol": "BTCUSDT", "traceType": "amount", "traceValue": "100", "maxHoldQty": "1000", "stopProfitRatio": "0.2", "stopLossRatio": "0.1", "slippageRatio": "0.001", "marginType": "trader", "leverageType": "fixed", "fixedLongLeverage": 10, "fixedShortLeverage": 10 } ] } ```
**Response Parameters** Returns the standard success response.
**Response Example** ```json { "code": "200", "msg": "success", "requestTime": 1627354109502 } ```
--- ## Document: Get Copy Trader History Orders (USER_DATA) URL: /api-doc/copy/future-copytrade/Trader/GetCopyTraderHistoryOrders # Get Copy Trader History Orders (USER_DATA) - **GET** ```/capi/v3/copy/trader/historyOrders``` Weight(IP): 10 This endpoint is available only for copy-trade API keys.
**Request Parameters** | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | symbol | String | No | Filter by symbol, for example `BTCUSDT`. | | limit | Integer | No | Page size, 1-100. Default: 100. | | startTime | Long | No | Start time in milliseconds. The maximum query range is 90 days. | | endTime | Long | No | End time in milliseconds. The maximum query range is 90 days. | | nextKeyId | Long | No | Cursor ID returned from the previous page. | | nextKeyTime | Long | No | Cursor time returned from the previous page. |
**Request Example** ```powershell curl "https://api-contract.weex.com/capi/v3/copy/trader/historyOrders?symbol=BTCUSDT&limit=50" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" ```
**Response Parameters** | Parameter | Type | Description | |-----------|------|-------------| | list | Array | History tracking order list. The item structure is the same as [Get Copy Trader Open Orders](./GetCopyTraderOpenOrders#response-parameters). | | nextFlag | Boolean | Whether there is a next page. | | nextKey | Object | Cursor for the next page. | | nextKey.nextKeyId | Long | Cursor ID. | | nextKey.nextKeyTime | Long | Cursor time in milliseconds. |
**Response Example** ```json { "list": [ { "trackingNo": 9000000001, "symbol": "BTCUSDT", "openOrderId": 702345678901234600, "openLeverage": 10, "openPriceAvg": "69000", "openTime": 1764505800000, "openSize": "0.01", "openFee": "0.414", "openMarginAmount": "69", "openFillSize": "0.01", "positionSide": "LONG", "status": "CLOSED", "tpTriggerPrice": "72000", "slTriggerPrice": "67000", "realizedPnl": "10", "profitRate": "0.12", "netProfit": "9.5", "followCount": 3, "createdTime": 1764505800000, "updateTime": 1764505900000 } ], "nextFlag": false, "nextKey": null } ```
--- ## Document: Get Copy Trader Open Orders (USER_DATA) URL: /api-doc/copy/future-copytrade/Trader/GetCopyTraderOpenOrders # Get Copy Trader Open Orders (USER_DATA) - **GET** ```/capi/v3/copy/trader/openOrders``` Weight(IP): 10 This endpoint is available only for copy-trade API keys.
**Request Parameters** | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | symbol | String | No | Filter by symbol, for example `BTCUSDT`. | | limit | Integer | No | Page size, 1-100. Default: 100. | | page | Integer | No | Page number, starts from 1. Default: 1. |
**Request Example** ```powershell curl "https://api-contract.weex.com/capi/v3/copy/trader/openOrders?symbol=BTCUSDT&limit=50&page=1" \ -H "ACCESS-KEY:*******" \ -H "ACCESS-SIGN:*******" \ -H "ACCESS-PASSPHRASE:*****" \ -H "ACCESS-TIMESTAMP:1659076670000" ```
**Response Parameters** Returns an array of copy trader tracking orders. | Parameter | Type | Description | |-----------|------|-------------| | trackingNo | Long | Tracking order ID. | | symbol | String | Symbol. | | openOrderId | Long | Open order ID generated by the trading system. | | openLeverage | Integer | Open leverage. | | openPriceAvg | String | Average open price. | | openTime | Long | Open time in milliseconds. | | openSize | String | Open order size. | | openFee | String | Open fee. | | openMarginAmount | String | Open margin amount. | | openFillSize | String | Filled open size. | | positionSide | String | Position side: `LONG`, `SHORT`, or `BOTH`. | | status | String | Tracking order status. | | tpTriggerPrice | String | Take-profit trigger price. | | slTriggerPrice | String | Stop-loss trigger price. | | realizedPnl | String | Realized PnL. | | profitRate | String | Profit rate. | | netProfit | String | Net profit. | | followCount | Integer | Follower count. | | createdTime | Long | Create time in milliseconds. | | updateTime | Long | Update time in milliseconds. |
**Response Example** ```json [ { "trackingNo": 9000000001, "symbol": "BTCUSDT", "openOrderId": 702345678901234600, "openLeverage": 10, "openPriceAvg": "69000", "openTime": 1764505800000, "openSize": "0.01", "openFee": "0.414", "openMarginAmount": "69", "openFillSize": "0.01", "positionSide": "LONG", "status": "HAVE_OPEN", "tpTriggerPrice": "72000", "slTriggerPrice": "67000", "realizedPnl": "0", "profitRate": "0.12", "netProfit": "0", "followCount": 3, "createdTime": 1764505800000, "updateTime": 1764505900000 } ] ```
--- ## Document: Get Copy Trader Pairs URL: /api-doc/copy/future-copytrade/Trader/GetCopyTraderPairs # Get Copy Trader Pairs - **GET** ```/capi/v3/copy/trader/pairs``` Weight(IP): 1
**Request Parameters** No parameters.
**Request Example** ```powershell curl "https://api-contract.weex.com/capi/v3/copy/trader/pairs" ```
**Response Parameters** Returns an array of symbols supported by copy trading. | Parameter | Type | Description | |-------------|--------|--------------------------------| | - | String | Symbol, for example `BTCUSDT`. |
**Response Example** ```json [ "BTCUSDT", "ETHUSDT" ] ```
--- ## Document: Trader API URL: /api-doc/copy/future-copytrade/Trader # Trader API --- ## Document: API introduction URL: /api-doc/copy/intro # API introduction The WEEX Copy Trading API provides a complete set of programmatic trading and management tools for lead traders and followers. With this API, you can: - Become a lead trader: Use an independently authorized Copy Trading API Key to trade and allow other traders to follow your portfolio. The system automatically pushes execution signals to all followers in real time. - Act as a follower: Follow a lead trader's portfolio, configure copy trading strategies, and query copy trading positions and PnL. You can copy expert trades without placing orders manually. ## Account Model The WEEX copy trading system uses an isolated account design. Funds, positions, and risk ratios in the copy trading account are fully isolated, ensuring copy trading and self-directed futures trading remain completely independent: | Account Type | Purpose | Applicable API Key | |:---|:---|:---| | Copy trading account | Dedicated to lead traders and used to initiate copy trades | Copy Trading API Key | | Futures account | Used by regular users for self-directed futures trading | Regular API Key | ## API Key Permissions and Management WEEX provides two types of API Keys to meet the security requirements of different roles. ### API Creation - Go to "**User Center**" -> "**API Management**". The system displays the corresponding API Key types based on your account identity. Select "**Copy Trading API**" to create one. - During creation, you need to enter your fund password and complete two-factor verification. Please keep your API key, Secret key, and Passphrase secure. ### Regular API Key - Applies to futures accounts and supports regular trading operations, such as placing orders, canceling orders, and querying positions. - Applies to followers and allows API operations such as configuring copy trading strategies, starting or stopping copy trading, and closing copy trading positions. - Regular API Keys cannot directly operate copy trading transactions. ### Copy Trading API Key - Can only be created by lead traders who have passed platform review. - Copy trading permission: Allows copy trading operations through the API, such as placing orders, canceling orders, and closing positions. ## API Limitations Please review the current scope carefully before integration. ### Copy Trading API Quantity Limit Each trader account can create up to 1 API key. ### Supported Features The Copy Trading API currently supports the following operations: - Place orders for futures copy trading symbols - Cancel orders - Modify orders - Query copy trading positions - Query current open orders - Query historical positions - Query order history ### Unsupported Features The Copy Trading API currently does not support the following operations: - Spot trading - Futures trading for non-copy trading symbols ## Trade Execution (Reuse Existing Futures Interfaces) Lead traders use the Copy Trading API Key to call the following standard futures interfaces. The system automatically identifies the copy trading identity and triggers copy trading signals. | Function | Method | Path | Description | |:---------------------------|:---------|:-------------------------|:--------------------------------------------------------------------------| | Place order | POST | /capi/v3/Order | Supports market and limit orders, with optional take-profit and stop-loss | | Cancel order | DELETE | /capi/v3/Order | Cancel a specified order | | Batch cancel orders | DELETE | /capi/v3/batchOrders | Batch cancel specified orders | | Cancel all open orders | POST | /capi/v3/allOpenOrders | Cancel all unfilled orders under the account | | Place trigger order | POST | /capi/v3/algoOrder | Create a new trigger order | | Cancel trigger order | DELETE | /capi/v3/algoOrder | Cancel a specified trigger order | | Cancel all trigger orders | DELETE | /capi/v3/algoOpenOrders | Cancel all trigger orders | | One-click market close | POST | /capi/v3/closePosition | Fully close a specified position | | Place TP/SL trigger order | POST | /capi/v3/placeTpSlOrder | Create a new take-profit/stop-loss order | | Modify TP/SL trigger order | POST | /capi/v3/modifyTpSlOrder | Modify an existing take-profit/stop-loss order | ## Rate Limits and Security - **Rate limits**: See [Access Restrictions](/api-doc/contract/QuickStart/AccessRestrictions) for the latest rate limit rules. - **Authentication**: All API requests must include `ACCESS-KEY`, `ACCESS-SIGN`, `Passphrase`, and `ACCESS-TIMESTAMP`. - **IP whitelist**: We recommend binding an IP whitelist to all API Keys to improve account security. - **Permission isolation**: Do not mix API Key types, such as using a regular API Key to call copy trading management interfaces.