# 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**
| 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 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). |
**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). |
---
## 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). |
---
## 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
**Response parameters**
| Field | Type | Description |
|-------------|------|-------------|
| serverTime | Long | Current server time in milliseconds. |
**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. |
**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.
---
## 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. |
**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.
---
## 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`. |
**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.
---
## 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. |
**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. |
---
## 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. |
**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. |
---
## 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. |
**Response parameters**
| Field | Type | Description |
|-------------------|----------|---------------------------------|
| orderId | Long | Cancelled order ID. |
| status | String | Final status (e.g. `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.
---
## 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. |
---
## 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. |
**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). |
---
## 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.
---
## 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. |
**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. |
---
## 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`. |
**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`. |
**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\
---
## 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. |
**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`. |
**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\
---
## 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. |
**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`. |
**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\
---
## 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. |
**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`. |
**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. |
---
## 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.
**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`. |
> **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. |
**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`. |
**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). |
> **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. |
**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`. |
**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. |
---
## 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. |
**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`. |
**Update Payload (`trade`)**
| Field | Type | Description |
|:------|:-----|:------------|
| e | String | Event type, `trade`. |
| E | Number | Event time in milliseconds. |
| s | String | Trading pair (uppercase). |
| d | Array\
> 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. |
---
## 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
**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 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% |
---
## 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. |
---
## 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
---
## 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 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.
---
## 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
**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 |
---
## 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. |
**Response parameters**
Returns an array of objects identical to [Get Order Info](/api-doc/contract/Transaction_API/GetSingleOrderInfo#response-parameters).
---
## 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`. |
---
## 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
---
## 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. |
---
## 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. |
---
## 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. |
---
## Document: Get Order Book Depth
URL: /api-doc/contract/Market_API/GetDepthData
# Get Order Book Depth
- **GET** ```/capi/v3/market/depth```
Weight(IP): 1
**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 |
---
## 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.
---
## 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. |
---
## 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. |
---
## 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. |
---
## Document: Get Open Interest
URL: /api-doc/contract/Market_API/GetOpenInterest
# Get Open Interest
- **GET** ```/capi/v3/market/openInterest```
Weight(IP): 2
---
## Document: Get Symbol Price
URL: /api-doc/contract/Market_API/GetSymbolPrice
# Get Symbol Price
- **GET** ```/capi/v3/market/symbolPrice```
Weight(IP): 1
**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 |
---
## 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. |
**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`. |
---
## 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 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. |
**Response parameters**
Returns an array of objects that follow the schema described in [Cancel Order (TRADE)](/api-doc/contract/Transaction_API/CancelOrder).
---
## 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. |
**Response parameters**
Identical to the schema described in [Cancel Order (TRADE)](/api-doc/contract/Transaction_API/CancelOrder#response-parameters).
---
## 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`).
**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`. |
---
## 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. |
**Response parameters**
Returns an array of objects identical to [Get Order Info](/api-doc/contract/Transaction_API/GetSingleOrderInfo#response-parameters).
---
## 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. |
---
## 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. |
**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. |
---
## 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. |
**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. |
---
## 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. |
**Response parameters**
Returns an array of objects identical to [Get Order Info](/api-doc/contract/Transaction_API/GetSingleOrderInfo#response-parameters).
---
## 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. |
**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). |
---
## 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.
---
## 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. |
**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. |
---
## 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`. |
---
## 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. |
---
## 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). |
**Response parameters**
A JSON array where each element matches the response schema of [Place Order (TRADE)](/api-doc/contract/Transaction_API/PlaceOrder).
---
## 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. |
---
## 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. |
**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`. |
**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`. |
**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\
---
## 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. |
**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`. |
**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\
---
## 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. |
**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`. |
**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\
---
## 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. |
**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`. |
**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\
---
## 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.
**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`. |
**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\
> **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. |
**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`. |
**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). |
> **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. |
**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`. |
**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\
---
## 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. |
**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`. |
**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\
> **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`. |
**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. |
---
## 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`. |
---
## 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`. |
**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.
---
## 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
---
## 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) |
---
## 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) |
---
## 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`) |
**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`) |
---
## 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.
---
## 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.
---
## 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) |
**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 parameters**
| Field Name | Type | Description |
|:------------|:--------|:--------------------------------------------------------|
| uid | Long | UID that was checked |
| isRefferal | Boolean | `true` if the UID belongs to the current affiliate |
---
## 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
**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 |
**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.
---
## 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. |
---
## 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. |
**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. |
**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`. |
---
## 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. |
**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. |
---
## 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. |
**Response Parameters**
Returns an array of symbols supported by copy trading.
| Parameter | Type | Description |
|-------------|--------|--------------------------------|
| - | String | Symbol, for example `BTCUSDT`. |
---
## 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.