From 57b8e09f69bec28c465d565bcb52322f2968700a Mon Sep 17 00:00:00 2001 From: danielaster Date: Mon, 21 Jul 2025 03:54:54 -0700 Subject: [PATCH 001/131] Update aster-finance-api.md --- aster-finance-api.md | 142 +++++++++++++++++++++---------------------- 1 file changed, 71 insertions(+), 71 deletions(-) diff --git a/aster-finance-api.md b/aster-finance-api.md index 4c35dee..7c8cb70 100644 --- a/aster-finance-api.md +++ b/aster-finance-api.md @@ -2889,7 +2889,7 @@ timestamp | LONG | YES -## Account Information V2 (USER_DATA) +## Account Information V4 (USER_DATA) > **Response:** @@ -2897,81 +2897,81 @@ timestamp | LONG | YES ```javascript { - "feeTier": 0, // account commisssion tier - "canTrade": true, // if can trade - "canDeposit": true, // if can transfer in asset - "canWithdraw": true, // if can transfer out asset - "updateTime": 0, - "totalInitialMargin": "0.00000000", // total initial margin required with current mark price (useless with isolated positions), only for USDT asset - "totalMaintMargin": "0.00000000", // total maintenance margin required, only for USDT asset - "totalWalletBalance": "23.72469206", // total wallet balance, only for USDT asset - "totalUnrealizedProfit": "0.00000000", // total unrealized profit, only for USDT asset - "totalMarginBalance": "23.72469206", // total margin balance, only for USDT asset - "totalPositionInitialMargin": "0.00000000", // initial margin required for positions with current mark price, only for USDT asset - "totalOpenOrderInitialMargin": "0.00000000", // initial margin required for open orders with current mark price, only for USDT asset - "totalCrossWalletBalance": "23.72469206", // crossed wallet balance, only for USDT asset - "totalCrossUnPnl": "0.00000000", // unrealized profit of crossed positions, only for USDT asset - "availableBalance": "23.72469206", // available balance, only for USDT asset - "maxWithdrawAmount": "23.72469206" // maximum amount for transfer out, only for USDT asset - "assets": [ - { - "asset": "USDT", // asset name - "walletBalance": "23.72469206", // wallet balance - "unrealizedProfit": "0.00000000", // unrealized profit - "marginBalance": "23.72469206", // margin balance - "maintMargin": "0.00000000", // maintenance margin required - "initialMargin": "0.00000000", // total initial margin required with current mark price - "positionInitialMargin": "0.00000000", //initial margin required for positions with current mark price - "openOrderInitialMargin": "0.00000000", // initial margin required for open orders with current mark price - "crossWalletBalance": "23.72469206", // crossed wallet balance - "crossUnPnl": "0.00000000" // unrealized profit of crossed positions - "availableBalance": "23.72469206", // available balance - "maxWithdrawAmount": "23.72469206", // maximum amount for transfer out - "marginAvailable": true, // whether the asset can be used as margin in Multi-Assets mode - "updateTime": 1625474304765 // last update time - }, - { - "asset": "BUSD", // asset name - "walletBalance": "103.12345678", // wallet balance - "unrealizedProfit": "0.00000000", // unrealized profit - "marginBalance": "103.12345678", // margin balance - "maintMargin": "0.00000000", // maintenance margin required - "initialMargin": "0.00000000", // total initial margin required with current mark price - "positionInitialMargin": "0.00000000", //initial margin required for positions with current mark price - "openOrderInitialMargin": "0.00000000", // initial margin required for open orders with current mark price - "crossWalletBalance": "103.12345678", // crossed wallet balance - "crossUnPnl": "0.00000000" // unrealized profit of crossed positions - "availableBalance": "103.12345678", // available balance - "maxWithdrawAmount": "103.12345678", // maximum amount for transfer out - "marginAvailable": true, // whether the asset can be used as margin in Multi-Assets mode - "updateTime": 1625474304765 // last update time - } - ], - "positions": [ // positions of all symbols in the market are returned - // only "BOTH" positions will be returned with One-way mode - // only "LONG" and "SHORT" positions will be returned with Hedge mode - { - "symbol": "BTCUSDT", // symbol name - "initialMargin": "0", // initial margin required with current mark price - "maintMargin": "0", // maintenance margin required - "unrealizedProfit": "0.00000000", // unrealized profit - "positionInitialMargin": "0", // initial margin required for positions with current mark price - "openOrderInitialMargin": "0", // initial margin required for open orders with current mark price - "leverage": "100", // current initial leverage - "isolated": true, // if the position is isolated - "entryPrice": "0.00000", // average entry price - "maxNotional": "250000", // maximum available notional with current leverage - "positionSide": "BOTH", // position side - "positionAmt": "0", // position amount - "updateTime": 0 // last update time - } - ] + "feeTier": 0, // account commisssion tier + "canTrade": true, // if can trade + "canDeposit": true, // if can transfer in asset + "canWithdraw": true, // if can transfer out asset + "updateTime": 0, + "totalInitialMargin": "0.00000000", // total initial margin required with current mark price (useless with isolated positions), only for USDT asset + "totalMaintMargin": "0.00000000", // total maintenance margin required, only for USDT asset + "totalWalletBalance": "23.72469206", // total wallet balance, using BidRate/AskRate for value caculation under multi-asset mode + "totalUnrealizedProfit": "0.00000000", // total unrealized profit in USDT + "totalMarginBalance": "23.72469206", // total margin balance, using BidRate/AskRate for value caculation under multi-asset mode + "totalPositionInitialMargin": "0.00000000", // initial margin required for positions with current mark price, only for USDT asset + "totalOpenOrderInitialMargin": "0.00000000", // initial margin required for open orders with current mark price, only for USDT asset + "totalCrossWalletBalance": "23.72469206", // crossed wallet balance, using BidRate/AskRate for value caculation under multi-asset mode + "totalCrossUnPnl": "0.00000000", // unrealized profit of crossed positions in USDT + "availableBalance": "23.72469206", // available balance, only for USDT asset + "maxWithdrawAmount": "23.72469206" // maximum amount for transfer out, using BidRate for value caculation under multi-asset mode + "assets": [ + { + "asset": "USDT", // asset name + "walletBalance": "23.72469206", // wallet balance + "unrealizedProfit": "0.00000000", // unrealized profit + "marginBalance": "23.72469206", // margin balance + "maintMargin": "0.00000000", // maintenance margin required + "initialMargin": "0.00000000", // total initial margin required with current mark price + "positionInitialMargin": "0.00000000", //initial margin required for positions with current mark price + "openOrderInitialMargin": "0.00000000", // initial margin required for open orders with current mark price + "crossWalletBalance": "23.72469206", // crossed wallet balance + "crossUnPnl": "0.00000000" // unrealized profit of crossed positions + "availableBalance": "23.72469206", // available balance + "maxWithdrawAmount": "23.72469206", // maximum amount for transfer out + "marginAvailable": true, // whether the asset can be used as margin in Multi-Assets mode + "updateTime": 1625474304765 // last update time + }, + { + "asset": "BUSD", // asset name + "walletBalance": "103.12345678", // wallet balance + "unrealizedProfit": "0.00000000", // unrealized profit + "marginBalance": "103.12345678", // margin balance + "maintMargin": "0.00000000", // maintenance margin required + "initialMargin": "0.00000000", // total initial margin required with current mark price + "positionInitialMargin": "0.00000000", //initial margin required for positions with current mark price + "openOrderInitialMargin": "0.00000000", // initial margin required for open orders with current mark price + "crossWalletBalance": "103.12345678", // crossed wallet balance + "crossUnPnl": "0.00000000" // unrealized profit of crossed positions + "availableBalance": "103.12345678", // available balance + "maxWithdrawAmount": "103.12345678", // maximum amount for transfer out + "marginAvailable": true, // whether the asset can be used as margin in Multi-Assets mode + "updateTime": 1625474304765 // last update time + } + ], + "positions": [ // positions of all symbols in the market are returned + // only "BOTH" positions will be returned with One-way mode + // only "LONG" and "SHORT" positions will be returned with Hedge mode + { + "symbol": "BTCUSDT", // symbol name + "initialMargin": "0", // initial margin required with current mark price + "maintMargin": "0", // maintenance margin required + "unrealizedProfit": "0.00000000", // unrealized profit + "positionInitialMargin": "0", // initial margin required for positions with current mark price + "openOrderInitialMargin": "0", // initial margin required for open orders with current mark price + "leverage": "100", // current initial leverage + "isolated": true, // if the position is isolated + "entryPrice": "0.00000", // average entry price + "maxNotional": "250000", // maximum available notional with current leverage + "positionSide": "BOTH", // position side + "positionAmt": "0", // position amount + "updateTime": 0 // last update time + } + ] } ``` `` -GET /fapi/v2/account (HMAC SHA256) +GET /fapi/v4/account (HMAC SHA256) `` Get current account information. From 22c53fabadb2d7b7ac496dccc57cb1960cee27f3 Mon Sep 17 00:00:00 2001 From: danielaster Date: Mon, 21 Jul 2025 03:56:40 -0700 Subject: [PATCH 002/131] Update aster-finance-api_CN.md --- aster-finance-api_CN.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/aster-finance-api_CN.md b/aster-finance-api_CN.md index cc5ed9a..e5142a0 100644 --- a/aster-finance-api_CN.md +++ b/aster-finance-api_CN.md @@ -2786,7 +2786,7 @@ timestamp | LONG | YES -## 账户信息V2 (USER_DATA) +## 账户信息V4 (USER_DATA) > **响应:** @@ -2800,15 +2800,15 @@ timestamp | LONG | YES "updateTime": 0, "totalInitialMargin": "0.00000000", // 但前所需起始保证金总额(存在逐仓请忽略), 仅计算usdt资产 "totalMaintMargin": "0.00000000", // 维持保证金总额, 仅计算usdt资产 - "totalWalletBalance": "23.72469206", // 账户总余额, 仅计算usdt资产 + "totalWalletBalance": "23.72469206", // 账户总余额, 联保模式下采用BidRate/AskRate来计算余额 "totalUnrealizedProfit": "0.00000000", // 持仓未实现盈亏总额, 仅计算usdt资产 - "totalMarginBalance": "23.72469206", // 保证金总余额, 仅计算usdt资产 + "totalMarginBalance": "23.72469206", // 保证金总余额, 联保模式下采用BidRate/AskRate来计算余额 "totalPositionInitialMargin": "0.00000000", // 持仓所需起始保证金(基于最新标记价格), 仅计算usdt资产 "totalOpenOrderInitialMargin": "0.00000000", // 当前挂单所需起始保证金(基于最新标记价格), 仅计算usdt资产 - "totalCrossWalletBalance": "23.72469206", // 全仓账户余额, 仅计算usdt资产 + "totalCrossWalletBalance": "23.72469206", // 全仓账户余额, 联保模式下采用BidRate/AskRate来计算余额 "totalCrossUnPnl": "0.00000000", // 全仓持仓未实现盈亏总额, 仅计算usdt资产 "availableBalance": "23.72469206", // 可用余额, 仅计算usdt资产 - "maxWithdrawAmount": "23.72469206" // 最大可转出余额, 仅计算usdt资产 + "maxWithdrawAmount": "23.72469206" // 最大可转出余额, 联保模式下采用BidRate来计算余额 "assets": [ { "asset": "USDT", //资产 @@ -2866,7 +2866,7 @@ timestamp | LONG | YES `` -GET /fapi/v2/account (HMAC SHA256) +GET /fapi/v4/account (HMAC SHA256) `` **权重:** From fb9ea0953dae0089455071e28c528835a827c8bd Mon Sep 17 00:00:00 2001 From: mark Date: Tue, 26 Aug 2025 17:48:26 +0800 Subject: [PATCH 003/131] add funding rate config --- aster-finance-api.md | 38 ++++++++++++++++++++++++++++++++++++++ aster-finance-api_CN.md | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+) diff --git a/aster-finance-api.md b/aster-finance-api.md index 7c8cb70..d4a42b8 100644 --- a/aster-finance-api.md +++ b/aster-finance-api.md @@ -38,6 +38,7 @@ - [Mark Price Kline/Candlestick Data](#mark-price-klinecandlestick-data) - [Mark Price](#mark-price) - [Get Funding Rate History](#get-funding-rate-history) + - [Get Funding Rate Config](#get-funding-rate-config) - [24hr Ticker Price Change Statistics](#24hr-ticker-price-change-statistics) - [Symbol Price Ticker](#symbol-price-ticker) - [Symbol Order Book Ticker](#symbol-order-book-ticker) @@ -1247,7 +1248,44 @@ limit | INT | NO | Default 100; max 1000 * If the number of data between `startTime` and `endTime` is larger than `limit`, return as `startTime` + `limit`. * In ascending order. +## Get Funding Rate Config +> **Response:** + +```javascript +[ + { + "symbol": "INJUSDT", + "interestRate": "0.00010000", + "time": 1756197479000, + "fundingIntervalHours": 8, + "fundingFeeCap": 0.03, + "fundingFeeFloor": -0.03 + }, + { + "symbol": "ZORAUSDT", + "interestRate": "0.00005000", + "time": 1756197479000, + "fundingIntervalHours": 4, + "fundingFeeCap": 0.02, + "fundingFeeFloor": -0.02 + } +] +``` + +`` +GET /fapi/v1/fundingInfo +`` + + +**Weight:** +1 + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +symbol | STRING | NO | diff --git a/aster-finance-api_CN.md b/aster-finance-api_CN.md index e5142a0..95c3751 100644 --- a/aster-finance-api_CN.md +++ b/aster-finance-api_CN.md @@ -38,6 +38,7 @@ - [标记价格K线数据](#标记价格k线数据) - [最新标记价格和资金费率](#最新标记价格和资金费率) - [查询资金费率历史](#查询资金费率历史) + - [查询资金费率配置](#查询资金费率配置) - [24hr价格变动情况](#24hr价格变动情况) - [最新价格](#最新价格) - [当前最优挂单](#当前最优挂单) @@ -1181,6 +1182,44 @@ limit | INT | NO | 默认值:100 最大值:1000 * 如果 `startTime` 和 `endTime` 都未发送, 返回最近 `limit` 条数据. * 如果 `startTime` 和 `endTime` 之间的数据量大于 `limit`, 返回 `startTime` + `limit`情况下的数据。 +## 查询资金费率配置 + +> **响应:** + +```javascript +[ + { + "symbol": "INJUSDT", // 交易对 + "interestRate": "0.00010000", // 利率 + "time": 1756197479000, // 更新时间 + "fundingIntervalHours": 8, // 资金费间隔小时数 + "fundingFeeCap": 0.03, // 资金费上限 + "fundingFeeFloor": -0.03 // 资金费下限 + }, + { + "symbol": "ZORAUSDT", + "interestRate": "0.00005000", + "time": 1756197479000, + "fundingIntervalHours": 4, + "fundingFeeCap": 0.02, + "fundingFeeFloor": -0.02 + } +] +``` + +`` +GET /fapi/v1/fundingInfo +`` + +**权重:** +1 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +--------- | ------ | -------- | ----------------------------------------------------- +symbol | STRING | NO | 交易对 + ## 24hr价格变动情况 From 85c07fdb3aebad95e123dd987a18411956d92304 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Mon, 1 Sep 2025 23:04:40 +0800 Subject: [PATCH 004/131] spot doc --- apollox-finance-spot-api.md | 2768 ++++++++++++++++ apollox-finance-spot-api_CN.md | 2772 +++++++++++++++++ ...ance-api.md => aster-finance-future-api.md | 32 + ...pi_CN.md => aster-finance-future-api_CN.md | 30 + consolidation.js | 232 ++ 5 files changed, 5834 insertions(+) create mode 100644 apollox-finance-spot-api.md create mode 100644 apollox-finance-spot-api_CN.md rename aster-finance-api.md => aster-finance-future-api.md (99%) rename aster-finance-api_CN.md => aster-finance-future-api_CN.md (99%) create mode 100644 consolidation.js diff --git a/apollox-finance-spot-api.md b/apollox-finance-spot-api.md new file mode 100644 index 0000000..635b552 --- /dev/null +++ b/apollox-finance-spot-api.md @@ -0,0 +1,2768 @@ +# General Info +## General API Information + +* The base endpoint is: **https://sapi.asterdex.com** +* All endpoints return either a JSON object or array. +* All time and timestamp related fields are in **milliseconds**. + +## API Key Setup + +* Some endpoints will require an API Key. +* Once API key is created, it is recommended to set IP restrictions on the key for security reasons. +* **Never share your API key/secret key to ANYONE.** + + + +### Attention +* TESTUSDT or any other symbols starting with TEST are symbols used for Aster’s INTERNAL TESTING ONLY. Please DO NOT trade on these symbols starting with TEST. Aster does not hold any accountability for loss of funds due to trading on these symbols. However, if you run into issues, you may contact support about this any time, we will try to help you recover your funds. + + + +### HTTP Return Codes +* HTTP `4XX` return codes are used for malformed requests; + the issue is on the sender's side. +* HTTP `403` return code is used when the WAF Limit (Web Application Firewall) has been violated. +* HTTP `429` return code is used when breaking a request rate limit. +* HTTP `418` return code is used when an IP has been auto-banned for continuing to send requests after receiving `429` codes. +* HTTP `5XX` return codes are used for internal errors; the issue is on Aster's side. + It is important to **NOT** treat this as a failure operation; the execution status is + **UNKNOWN** and could have been a success. + +### Error Codes and Messages + +* If there is an error, the API will return an error with a message of the reason. + +> The error payload on API is as follows: + +```javascript +{ + "code": -1121, + "msg": "Invalid symbol." +} +``` + +### General Information on Endpoints + +* For `GET` endpoints, parameters must be sent as a `query string`. +* For `POST`, `PUT`, and `DELETE` endpoints, the parameters may be sent as a + `query string` or in the `request body` with content type + `application/x-www-form-urlencoded`. +* Parameters may be sent in any order. + +--- +## LIMITS + +### General Info on Limits +* The `/api/v1/exchangeInfo` `rateLimits` array contains objects related to the exchange's `REQUEST_WEIGHT`, and `ORDERS` rate limits. These are further defined in the `ENUM definitions` section under `Rate limiters (rateLimitType)`. +* A 429 will be returned when either rate limit is violated. + +### IP Limits +* Every request will contain `X-MBX-USED-WEIGHT-(intervalNum)(intervalLetter)` in the response headers which has the current used weight for the IP for all request rate limiters defined. +* Each route has a `weight` which determines for the number of requests each endpoint counts for. Heavier endpoints and endpoints that do operations on multiple symbols will have a heavier `weight`. +* When a 429 is received, it's your obligation as an API to back off and not spam the API. +* **Repeatedly violating rate limits and/or failing to back off after receiving 429s will result in an automated IP ban (HTTP status 418).** +* IP bans are tracked and **scale in duration** for repeat offenders, **from 2 minutes to 3 days**. +* A `Retry-After` header is sent with a 418 or 429 responses and will give the **number of seconds** required to wait, in the case of a 429, to prevent a ban, or, in the case of a 418, until the ban is over. +* **The limits on the API are based on the IPs, not the API keys.** + + + +### Order Rate Limits +* Every successful order response will contain a `X-MBX-ORDER-COUNT-(intervalNum)(intervalLetter)` header which has the current order count for the account for all order rate limiters defined. +* Rejected/unsuccessful orders are not guaranteed to have `X-MBX-ORDER-COUNT-**` headers in the response. +* **The order rate limit is counted against each account**. + +### Websocket Limits +* WebSocket connections have a limit of 5 incoming messages per second. A message is considered: + * A PING frame + * A PONG frame + * A JSON controlled message (e.g. subscribe, unsubscribe) +* A connection that goes beyond the limit will be disconnected; IPs that are repeatedly disconnected may be banned. +* A single connection can listen to a maximum of 1024 streams. + +--- + +## Endpoint security type +* Each endpoint has a security type that determines how you will + interact with it. This is stated next to the NAME of the endpoint. + * If no security type is stated, assume the security type is NONE. +* API-keys are passed into the Rest API via the `X-MBX-APIKEY` + header. +* API-keys and secret-keys **are case sensitive**. +* API-keys can be configured to only access certain types of secure endpoints. +* By default, API-keys can access all secure routes. + +Security Type | Description +------------ | ------------ +NONE | Endpoint can be accessed freely. +TRADE | Endpoint requires sending a valid API-Key and signature. +USER_DATA | Endpoint requires sending a valid API-Key and signature. +USER_STREAM | Endpoint requires sending a valid API-Key. +MARKET_DATA | Endpoint requires sending a valid API-Key. + +* `TRADE` and `USER_DATA` endpoints are `SIGNED` endpoints. + +## SIGNED (TRADE AND USER_DATA) Endpoint security +* `SIGNED` endpoints require an additional parameter, `signature`, to be + sent in the `query string` or `request body`. +* Endpoints use `HMAC SHA256` signatures. The `HMAC SHA256 signature` is a keyed `HMAC SHA256` operation. + Use your `secretKey` as the key and `totalParams` as the value for the HMAC operation. +* The `signature` is **not case sensitive**. +* `totalParams` is defined as the `query string` concatenated with the + `request body`. + +### Timing security +* A `SIGNED` endpoint also requires a parameter, `timestamp`, to be sent which + should be the millisecond timestamp of when the request was created and sent. +* An additional parameter, `recvWindow`, may be sent to specify the number of + milliseconds after `timestamp` the request is valid for. If `recvWindow` + is not sent, **it defaults to 5000**. + +> The logic is as follows: +```javascript + if (timestamp < (serverTime + 1000) && (serverTime - timestamp) <= recvWindow) + { + // process request + } + else + { + // reject request + } +``` + +**Serious trading is about timing.** Networks can be unstable and unreliable, +which can lead to requests taking varying amounts of time to reach the +servers. With `recvWindow`, you can specify that the request must be +processed within a certain number of milliseconds or be rejected by the +server. + + + +### SIGNED Endpoint Examples for POST /api/v1/order +Here is a step-by-step example of how to send a vaild signed payload from the +Linux command line using `echo`, `openssl`, and `curl`. + +Key | Value +------------ | ------------ +apiKey | 4452d7e2ed4da80b74105e02d06328c71a34488c9fdd60a5a0900d42d584b795 +secretKey | fdde510a2b71fa43a43bff3e3cf7819c8c66df34633d338050f4f59664b3b313 + +Parameter | Value +------------ | ------------ +symbol | BNBUSDT +side | BUY +type | LIMIT +timeInForce | GTC +quantity | 5 +price | 1.1 +recvWindow | 5000 +timestamp | 1756187806000 + + +#### Example 1: As a request body + + +> **Example 1** +> **HMAC SHA256 signature:** +```shell + $ echo -n "symbol=BNBUSDT&side=BUY&type=LIMIT&timeInForce=GTC&quantity=5&price=1.1&recvWindow=5000×tamp=1756187806000" | openssl dgst -sha256 -hmac "fdde510a2b71fa43a43bff3e3cf7819c8c66df34633d338050f4f59664b3b313" + (stdin)= e09169bf6c02ec4b29fa1bdc3a967f92c8c6cfcde0551ba1d477b2d3cf4c51b0 +``` + + +> **curl command:** +```shell + (HMAC SHA256) + $ curl -H "X-MBX-APIKEY: 4452d7e2ed4da80b74105e02d06328c71a34488c9fdd60a5a0900d42d584b795" -X POST 'https://sapi.asterdex.com/api/v1/order' -d 'symbol=BNBUSDT&side=BUY&type=LIMIT&timeInForce=GTC&quantity=5&price=1.1&recvWindow=5000×tamp=1756187806000&signature=e09169bf6c02ec4b29fa1bdc3a967f92c8c6cfcde0551ba1d477b2d3cf4c51b0' +``` + +* **requestBody:** + +symbol=BNBUSDT +&side=BUY +&type=LIMIT +&timeInForce=GTC +&quantity=5 +&price=1.1 +&recvWindow=5000 +×tamp=1756187806000 + + +#### Example 2: As a query string + +> **Example 2** +> **HMAC SHA256 signature:** +```shell + $ echo -n "symbol=BNBUSDT&side=BUY&type=LIMIT&timeInForce=GTC&quantity=5&price=1.1&recvWindow=5000×tamp=1756187806000" | openssl dgst -sha256 -hmac "fdde510a2b71fa43a43bff3e3cf7819c8c66df34633d338050f4f59664b3b313" + (stdin)= e09169bf6c02ec4b29fa1bdc3a967f92c8c6cfcde0551ba1d477b2d3cf4c51b0 +``` + +> **curl command:** +```shell + (HMAC SHA256) + $ curl -H "X-MBX-APIKEY: 4452d7e2ed4da80b74105e02d06328c71a34488c9fdd60a5a0900d42d584b795" -X POST 'https://sapi.asterdex.com/api/v1/order?symbol=BNBUSDT&side=BUY&type=LIMIT&timeInForce=GTC&quantity=5&price=1.1&recvWindow=5000×tamp=1756187806000&signature=e09169bf6c02ec4b29fa1bdc3a967f92c8c6cfcde0551ba1d477b2d3cf4c51b0' +``` + +* **queryString:** + +symbol=BNBUSDT +&side=BUY +&type=LIMIT +&timeInForce=GTC +&quantity=5 +&price=1.1 +&recvWindow=5000 +×tamp=1756187806000 + +--- + +## Public API Definitions +### Terminology + +These terms will be used throughout the documentation, so it is recommended especially for new users to read to help their understanding of the API. + +* `base asset` refers to the asset that is the `quantity` of a symbol. For the symbol BTCUSDT, BTC would be the `base asset.` +* `quote asset` refers to the asset that is the `price` of a symbol. For the symbol BTCUSDT, USDT would be the `quote asset`. + +### ENUM definitions +**Symbol status (status):** + +* TRADING + + +**Order status (status):** + +Status | Description +-----------| -------------- +`NEW` | The order has been accepted by the engine. +`PARTIALLY_FILLED`| A part of the order has been filled. +`FILLED` | The order has been completed. +`CANCELED` | The order has been canceled by the user. +`REJECTED` | The order was not accepted by the engine and not processed. +`EXPIRED` | The order was canceled according to the order type's rules (e.g. LIMIT FOK orders with no fill, LIMIT IOC or MARKET orders that partially fill) or by the exchange, (e.g. orders canceled during maintenance) + + +**Order types (orderTypes, type):** + +* LIMIT +* MARKET +* STOP +* TAKE_PROFIT +* STOP_MARKET +* TAKE_PROFIT_MARKET + +**Order Response Type (newOrderRespType):** + +* ACK +* RESULT +* FULL + +**Order side (side):** + +* BUY +* SELL + +**Time in force (timeInForce):** + +This sets how long an order will be active before expiration. + +Status | Description +-----------| -------------- +`GTC` | Good Till Canceled
An order will be on the book unless the order is canceled. +`IOC` | Immediate Or Cancel
An order will try to fill the order as much as it can before the order expires. +`FOK`| Fill or Kill
An order will expire if the full order cannot be filled upon execution. +`GTX`| Good Till Crossing
 Post only order + +**Kline/Candlestick chart intervals:** + +m -> minutes; h -> hours; d -> days; w -> weeks; M -> months + +* 1m +* 3m +* 5m +* 15m +* 30m +* 1h +* 2h +* 4h +* 6h +* 8h +* 12h +* 1d +* 3d +* 1w +* 1M + +**Rate limiters (rateLimitType)** + +> REQUEST_WEIGHT +```json + { + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200 + } +``` + +> ORDERS +```json + { + "rateLimitType": "ORDERS", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 100 + } +``` + +* REQUEST_WEIGHT + +* ORDERS + +**Rate limit intervals (interval)** + +* MINUTE + +--- +## Filters +Filters define trading rules on a symbol or an exchange. +Filters come in two forms: `symbol filters` and `exchange filters`. Currently only `symbol filters` is used. + +### Symbol Filters + +#### PRICE_FILTER + +> **ExchangeInfo format:** +```javascript + { + "minPrice": "556.72", + "maxPrice": "4529764", + "filterType": "PRICE_FILTER", + "tickSize": "0.01"   + } +``` + +The `PRICE_FILTER` defines the `price` rules for a symbol. There are 3 parts: + +* `minPrice` defines the minimum `price`/`stopPrice` allowed; disabled on `minPrice` == 0. +* `maxPrice` defines the maximum `price`/`stopPrice` allowed; disabled on `maxPrice` == 0. +* `tickSize` defines the intervals that a `price`/`stopPrice` can be increased/decreased by; disabled on `tickSize` == 0. + +Any of the above variables can be set to 0, which disables that rule in the `price filter`. In order to pass the `price filter`, the following must be true for `price`/`stopPrice` of the enabled rules: + +* `price` >= `minPrice` +* `price` <= `maxPrice` +* (`price`-`minPrice`) % `tickSize` == 0 + + +#### PERCENT_PRICE + +> **ExchangeInfo format:** +```javascript + { + "multiplierDown": "0.9500", + "multiplierUp": "1.0500", + "multiplierDecimal": "4", + "filterType": "PERCENT_PRICE" +  } +``` + +The `PERCENT_PRICE` filter defines valid range for a price based on the index price. + +In order to pass the `percent price`, the following must be true for `price`:   + +* `price` <=`indexPrice` *`multiplierUp` +* `price`> =`indexPrice` *`multiplierDown`     + + +#### LOT_SIZE + +> **ExchangeInfo format:** +```javascript + { + "stepSize": "0.00100000", +   "filterType": "LOT_SIZE", + "maxQty": "100000.00000000", +   "minQty": "0.00100000" + } +``` + +The `LOT_SIZE` filter defines the `quantity` (aka "lots" in auction terms) rules for a symbol. There are 3 parts: + +* `minQty` defines the minimum `quantity` allowed. +* `maxQty` defines the maximum `quantity` allowed. +* `stepSize` defines the intervals that a `quantity` can be increased/decreased by. + +In order to pass the `lot size`, the following must be true for `quantity`: + +* `quantity` >= `minQty` +* `quantity` <= `maxQty` +* (`quantity`-`minQty`) % `stepSize` == 0 + + + + +#### MARKET_LOT_SIZE + +> **ExchangeInfo format:** +```javascript + { + "stepSize": "0.00100000", + "filterType": "MARKET_LOT_SIZE" + "maxQty": "100000.00000000", + "minQty": "0.00100000"   + } +``` + + +The `MARKET_LOT_SIZE` filter defines the `quantity` (aka "lots" in auction terms) rules for `MARKET` orders on a symbol. There are 3 parts: + +* `minQty` defines the minimum `quantity` allowed. +* `maxQty` defines the maximum `quantity` allowed. +* `stepSize` defines the intervals that a `quantity` can be increased/decreased by. + +In order to pass the `market lot size`, the following must be true for `quantity`: + +* `quantity` >= `minQty` +* `quantity` <= `maxQty` +* (`quantity`-`minQty`) % `stepSize` == 0 + + + + + + + + + + + + +# Market Data Endpoints + +## Test Connectivity + + + +> **Response:** +```javascript +{} +``` + +`` +GET /api/v1/ping +`` + +Test connectivity to the Rest API. + +**Weight:** +1 + +**Parameters:** + +NONE + +## Check Server Time + + +> **Response:** +```javascript +{ + "serverTime": 1499827319559 +} +``` + +`` +GET /api/v1/time +`` + +Test connectivity to the Rest API and get the current server time. + +**Weight:** +1 + +**Parameters:** + +NONE + + +## Exchange Information + +> **Response:** + +```javascript   +{ + "timezone": "UTC", + "serverTime": 1756197279679, + "rateLimits": [{ + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 6000 + }, + { + "rateLimitType": "ORDERS", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 6000 + }, + { + "rateLimitType": "ORDERS", + "interval": "SECOND", + "intervalNum": 10, + "limit": 300 + } + ], + "exchangeFilters": [], + "assets": [{ + "asset": "USD" + }, { + "asset": "USDT" + }, + { + "asset": "BNB" + } + ], + "symbols": [{ + "status": "TRADING", + "baseAsset": "BNB", + "quoteAsset": "USDT", + "pricePrecision": 8, + "quantityPrecision": 8, + "baseAssetPrecision": 8, + "quotePrecision": 8, + "filters": [{ + "minPrice": "0.01000000", + "maxPrice": "100000", + "filterType": "PRICE_FILTER", + "tickSize": "0.01000000" + }, + { + "stepSize": "0.00100000", + "filterType": "LOT_SIZE", + "maxQty": "1000", + "minQty": "1" + }, + { + "stepSize": "0.00100000", + "filterType": "MARKET_LOT_SIZE", + "maxQty": "900000", + "minQty": "0.00100000" + }, + { + "limit": 200, + "filterType": "MAX_NUM_ORDERS" + }, + { + "minNotional": "5", + "filterType": "MIN_NOTIONAL" + }, + { + "maxNotional": "100", + "filterType": "MAX_NOTIONAL" + }, + { + "maxNotional": "100", + "minNotional": "5", + "avgPriceMins": 5, + "applyMinToMarket": true, + "filterType": "NOTIONAL", + "applyMaxToMarket": true + }, + { + "multiplierDown": "0", + "multiplierUp": "5", + "multiplierDecimal": "0", + "filterType": "PERCENT_PRICE" + }, + { + "bidMultiplierUp": "5", + "askMultiplierUp": "5", + "bidMultiplierDown": "0", + "avgPriceMins": 5, + "multiplierDecimal": "0", + "filterType": "PERCENT_PRICE_BY_SIDE", + "askMultiplierDown": "0" + } + ], + "orderTypes": [ + "LIMIT", + "MARKET", + "STOP", + "STOP_MARKET", + "TAKE_PROFIT", + "TAKE_PROFIT_MARKET" + ], + "timeInForce": [ + "GTC", + "IOC", + "FOK", + "GTX" + ], + "symbol": "BNBUSDT", + "ocoAllowed": false + }] +} +``` + +`` +GET /api/v1/exchangeInfo +`` + +Current exchange trading rules and symbol information + +**Weight:** +1 + +**Parameters:** +NONE + + +## Order Book + + +> **Response:** +```javascript +{ + "lastUpdateId": 1027024, + "E": 1589436922972, // Message output time + "T": 1589436922959, // Transaction time +  "bids": [ + [ + "4.00000000", // PRICE + "431.00000000" // QTY + ] + ], + "asks": [ + [ + "4.00000200", + "12.00000000" + ] + ] +} +``` + +`` +GET /api/v1/depth +`` + +**Weight(IP):** + +Adjusted based on the limit: + + +Limit | Weight +------------ | ------------ +5, 10, 20, 50 | 2 +100 | 5 +500 | 10 +1000 | 20 +   +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +limit | INT | NO | Default 100. Valid limits:[5, 10, 20, 50, 100, 500, 1000] + + +## Recent Trades List + + +> **Response:** +```javascript +[ + { + "id": 657, + "price": "1.01000000", + "qty": "5.00000000", + "baseQty": "4.95049505", + "time": 1755156533943, + "isBuyerMaker": false + } +] +``` + +`` +GET /api/v1/trades +`` + +Get recent trades. + +**Weight:** +1 + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +limit | INT | NO | Default 500;max 1000 + + +## Old Trade Lookup (MARKET_DATA) + +> **Response:** + +```javascript +[ + { + "id": 1140, + "price": "1.10000000", + "qty": "7.27200000", + "baseQty": "6.61090909", + "time": 1756094288700, + "isBuyerMaker": false + } +] +``` + +`` +GET /api/v1/historicalTrades +`` + +Get older market trades. + +**Weight:** +20 + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +limit | INT | NO | Default 500; max 1000. +fromId | LONG | NO | Trade id to fetch from. Default gets most recent trades. + + +## Compressed/Aggregate Trades List + + +> **Response:** +```javascript +[ + { + "a": 26129, // Aggregate tradeId + "p": "0.01633102", // Price + "q": "4.70443515", // Quantity + "f": 27781, // First tradeId + "l": 27781, // Last tradeId + "T": 1498793709153, // Timestamp + "m": true, // Was the buyer the maker? + } +] +``` + +`` +GET /api/v1/aggTrades +`` + +Get compressed, aggregate trades. Trades that fill at the time, from the same +order, with the same price will have the quantity aggregated. + +**Weight:** +20 + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +fromId | LONG | NO | id to get aggregate trades from INCLUSIVE. +startTime | LONG | NO | Timestamp in ms to get aggregate trades from INCLUSIVE. +endTime | LONG | NO | Timestamp in ms to get aggregate trades until INCLUSIVE. +limit | INT | NO | Default 500; max 1000. + +* If startTime and endTime are sent, time between startTime and endTime must be less than 1 hour. +* If fromId, startTime, and endTime are not sent, the most recent aggregate trades will be returned. + + +## Kline/Candlestick Data + + +> **Response:** +```javascript +[ + [ + 1499040000000, // Open time + "0.01634790", // Open + "0.80000000", // High + "0.01575800", // Low + "0.01577100", // Close + "148976.11427815", // Volume + 1499644799999, // Close time + "2434.19055334", // Quote asset volume + 308, // Number of trades + "1756.87402397", // Taker buy base asset volume + "28.46694368", // Taker buy quote asset volume + "17928899.62484339" // Ignore. + ] +] +``` + +`` +GET /api/v1/klines +`` + +Kline/candlestick bars for a symbol. +Klines are uniquely identified by their open time. + + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +interval | ENUM | YES | +startTime | LONG | NO | +endTime | LONG | NO | +limit | INT | NO | Default 500; max 1500. + +* If startTime and endTime are not sent, the most recent klines are returned. + + +## 24hr Ticker Price Change Statistics + +> **Response:** + +```javascript +{ + "symbol": "BTCUSDT", + "priceChange": "-94.99999800", //price change + "priceChangePercent": "-95.960", //price change percent + "weightedAvgPrice": "0.29628482", //weighted avgPrice + "prevClosePrice": "3.89000000", //prev close price + "lastPrice": "4.00000200", //last price + "lastQty": "200.00000000", //last qty + "bidPrice": "866.66000000", //first bid price + "bidQty": "72.05100000", //first bid qty + "askPrice": "866.73000000", //first ask price + "askQty": "1.21700000", //first ask qty + "openPrice": "99.00000000", //open price + "highPrice": "100.00000000", //high price + "lowPrice": "0.10000000", //low price + "volume": "8913.30000000", //volume + "quoteVolume": "15.30000000", //quote volume + "openTime": 1499783499040, //open time + "closeTime": 1499869899040, //close time + "firstId": 28385, // first id + "lastId": 28460, // last id + "count": 76 // count +} +``` + +`` +GET /api/v1/ticker/24hr +`` + +24 hour rolling window price change statistics. +**Careful** when accessing this with no symbol. + +**Weight:** + +1 for a single symbol; +**40** when the symbol parameter is omitted; + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +symbol | STRING | NO | + +* If the symbol is not sent, tickers for all symbols will be returned in an array.   + + +## 最新价格 + +> **Response** + +```javascript +{ + "symbol": "ADAUSDT", + "price": "1.30000000", + "time": 1649666690902 +} +``` + +> OR + +```javascript +[ + { + "symbol": "ADAUSDT", + "price": "1.30000000", + "time": 1649666690902 + } +] +``` + +`` +GET /api/v1/ticker/price +``   + +Latest price for a symbol or symbols. + +**Weight:** +1 for a single symbol; +2 when the symbol parameter is omitted + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +symbol | STRING | NO | + +* If the symbol is not sent, prices for all symbols will be returned in an array. + + +## Symbol Order Book Ticker     + +> **Response** +```javascript +{ + "symbol": "LTCBTC", + "bidPrice": "4.00000000", + "bidQty": "431.00000000", + "askPrice": "4.00000200", + "askQty": "9.00000000" + "time": 1589437530011 +} +``` + +> OR + +```javascript +[ + { + "symbol": "LTCBTC", + "bidPrice": "4.00000000", + "bidQty": "431.00000000", + "askPrice": "4.00000200", + "askQty": "9.00000000", + "time": 1589437530011 + } +] +``` + +`` +GET /api/v1/ticker/bookTicker +`` + +Best price/qty on the order book for a symbol or symbols. + +**Weight:** +1 for a single symbol; +2 when the symbol parameter is omitted + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +symbol | STRING | NO | + +* If the symbol is not sent, prices for all symbols will be returned in an array. + + +## Symbol Commmission Fee + +> **Response:** + +```javascript +{ + "symbol": "APXUSDT", + "makerCommission": "0.000200",     + "takerCommission": "0.000700" +} +``` + +`` +GET /api/v1/commissionRate +`` + +Get symbol commission fee. + +**Weight:** +20 + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +recvWindow | LONG | NO | +timestamp | LONG | YES | + + + + +# Spot Account/Trade + +## New Order (TRADE) + +> **Response:** +```javascript +{ + "symbol": "BTCUSDT", + "orderId": 28, + "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP", + "updateTime": 1507725176595, + "price": "0.00000000", + "avgPrice": "0.0000000000000000", + "origQty": "10.00000000", + "cumQty": "0", + "executedQty": "10.00000000", + "cumQuote": "10.00000000", + "status": "FILLED", + "timeInForce": "GTC", + "stopPrice": "0", + "origType": "LIMIT", + "type": "LIMIT", + "side": "SELL", +} +``` + +`` +POST /api/v1/order (HMAC SHA256) +`` + +Send in a new order. + +**Weight:** +1 + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +side | ENUM | YES | +type | ENUM | YES | +timeInForce | ENUM | NO | +quantity | DECIMAL | NO | +quoteOrderQty|DECIMAL|NO| +price | DECIMAL | NO | +newClientOrderId | STRING | NO | A unique id among open orders. Automatically generated if not sent. +stopPrice | DECIMAL | NO | Used with `STOP`, `STOP_MARKET`,`TAKE_PROFIT`, `TAKE_PROFIT_MARKET` orders. +recvWindow | LONG | NO |The value cannot be greater than ```60000``` +timestamp | LONG | YES | + +Additional mandatory parameters based on `type`: + +Type | Additional mandatory parameters +------------ | ------------ +`LIMIT` | `timeInForce`, `quantity`, `price` +`MARKET` | `quantity` or `quoteOrderQty` +`STOP`和`TAKE_PROFIT` | `quantity`, `price`, `stopPrice`   +`STOP_MARKET`和`TAKE_PROFIT_MARKET` | `quantity`, `stopPrice` + + +Other info: + +* `MARKET` `SELL` orders using the `quantity` field specifies the amount of the `base asset` the user wants to sell at the market price. + * For example, sending a `MARKET` `SELL` order on BTCUSDT will specify how much BTC the user is selling. +* `MARKET` `BUY` orders using `quoteOrderQty` specifies the amount the user wants to spend the `quote` asset; the correct `quantity` will be determined based on the market liquidity and `quoteOrderQty`. + * For example, sending a `MARKET` `BUY` order on BTCUSDT specify how much USDT the user is using to buy. The order will buy as many BTC as `quoteOrderQty` USDT can. +* `MARKET` orders using `quoteOrderQty` will not break `LOT_SIZE` filter rules; the order will execute a `quantity` that will have the notional value as close as possible to `quoteOrderQty`. +* same `newClientOrderId` can be accepted only when the previous one is filled, otherwise the order will be rejected. +   + +## Cancel Order (TRADE) + +> **Response:** +```javascript +{ + "symbol": "BTCUSDT", + "orderId": 28, + "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP", + "updateTime": 1507725176595, + "price": "0.00000000", + "avgPrice": "0.0000000000000000", + "origQty": "10.00000000", + "cumQty": "0", + "executedQty": "10.00000000", + "cumQuote": "10.00000000", + "status": "CANCELED", + "timeInForce": "GTC", + "stopPrice": "0", + "origType": "LIMIT", + "type": "LIMIT", + "side": "SELL", +} +``` + +`` +DELETE /api/v1/order (HMAC SHA256) +`` + +Cancel an active order. + +**Weight:** +1 + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +orderId | LONG | NO | +origClientOrderId | STRING | NO | +recvWindow | LONG | NO | +timestamp | LONG | YES | + +Either `orderId` or `origClientOrderId` must be sent.   + + +## Query Order (USER_DATA) + +> **Response:** + +```javascript +{ + "orderId": 38, + "symbol": "ADA25SLP25", + "status": "FILLED", + "clientOrderId": "afMd4GBQyHkHpGWdiy34Li", + "price": "20", + "avgPrice": "12.0000000000000000", + "origQty": "10", + "executedQty": "10", + "cumQuote": "120", + "timeInForce": "GTC", + "type": "LIMIT", + "side": "BUY", + "stopPrice": "0", + "origType": "LIMIT", + "time": 1649913186270, + "updateTime": 1649913186297 +} +``` + +`` +GET /api/v1/order (HMAC SHA256) +`` + +Check an order's status.   + +**Weight:** +1 + +* These orders will not be found: + * order status is `CANCELED` or `EXPIRED`, **AND** + * order has NO filled trade, **AND** + * created time + 7 days < current time   + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +orderId | LONG | NO | +origClientOrderId | STRING | NO | +recvWindow | LONG | NO | +timestamp | LONG | YES | + +Notes: + +* Either `orderId` or `origClientOrderId` must be sent. + + +## current one opne order (USER_DATA) + +> **Response:** +```javascript +{ + "orderId": 38, + "symbol": "ADA25SLP25", + "status": "NEW", + "clientOrderId": "afMd4GBQyHkHpGWdiy34Li", + "price": "20", + "avgPrice": "12.0000000000000000", + "origQty": "10", + "executedQty": "10", + "cumQuote": "120", + "timeInForce": "GTC", + "type": "LIMIT", + "side": "BUY", + "stopPrice": "0", + "origType": "LIMIT", + "time": 1649913186270, + "updateTime": 1649913186297 +} +``` + +`` +GET /api/v1/openOrder (HMAC SHA256) +`` + +get one current opne order + +**Weight:** +1 + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +orderId | LONG | NO | +origClientOrderId | STRING | NO | +recvWindow | LONG | NO | +timestamp | LONG | YES | + +**Notes:** + +Either `orderId` or `origClientOrderId` must be sent. + + +## Current Open Orders (USER_DATA) + +> **Response:** +```javascript +[ + { + "orderId": 349661, + "symbol": "BNBUSDT", + "status": "NEW", + "clientOrderId": "LzypgiMwkf3TQ8wwvLo8RA", + "price": "1.10000000", + "avgPrice": "0.0000000000000000", + "origQty": "5",   + "executedQty": "0", + "cumQuote": "0", + "timeInForce": "GTC", + "type": "LIMIT", + "side": "BUY", + "stopPrice": "0", + "origType": "LIMIT", + "time": 1756252940207, + "updateTime": 1756252940207, + } +] +``` + +`` +GET /api/v1/openOrders (HMAC SHA256) +`` + +Get all open orders on a symbol. **Careful** when accessing this with no symbol. + +**Weight:** +1 for a single symbol; **40** when the symbol parameter is omitted + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +symbol | STRING | NO | +recvWindow | LONG | NO | +timestamp | LONG | YES | + +* If the symbol is not sent, orders for all symbols will be returned in an array. + + + +## cancel all open order (USER_DATA) + +> **Response:** + +```javascript +{ + "code": 200, + "msg": "The operation of cancel all open order is done." +} +``` + +`` +DEL /api/v1/allOpenOrders (HMAC SHA256) +`` + +**Weight:** +- ***1*** + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +orderIdList | STRING | NO | id array +origClientOrderIdList | STRING | NO | clientOrderId array +recvWindow | LONG | NO | +timestamp | LONG | YES | + + + +## All Orders (USER_DATA) + +> **Response:** + +```javascript +[ + { + "orderId": 349661, + "symbol": "BNBUSDT", + "status": "NEW", + "clientOrderId": "LzypgiMwkf3TQ8wwvLo8RA", + "price": "1.10000000", + "avgPrice": "0.0000000000000000", + "origQty": "5",   + "executedQty": "0", + "cumQuote": "0", + "timeInForce": "GTC", + "type": "LIMIT", + "side": "BUY", + "stopPrice": "0", + "origType": "LIMIT", + "time": 1756252940207, + "updateTime": 1756252940207, + } +] +``` + +`` +GET /api/v1/allOrders (HMAC SHA256) +`` + +Get all account orders; active, canceled, or filled. + +* These orders will not be found: + * created time + 7 days < current time + +**Weight:** +5 + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +orderId | LONG | NO | +startTime | LONG | NO | +endTime | LONG | NO | +limit | INT | NO | Default 500; max 1000. +recvWindow | LONG | NO | +timestamp | LONG | YES | + +**Notes:** + +* If `orderId` is set, it will get orders >= that `orderId`. Otherwise most recent orders are returned. +* The query time period must be less then 7 days( default as the recent 7 days). ## Account Information (USER_DATA) + + +## Swap Between Futures and Spot (TRADE) + +> **Response:** + +```javascript +{ + "tranId": 21841, + "status": "SUCCESS" +} +``` + +`` +POST /api/v1/asset/transfer (HMAC SHA256) +`` + +**Weight:** +5 + +**Parameters:** + + +Name | Type | Mandatory | Description +---------------- | ------- | -------- | ---- +amount | DECIMAL | YES | +asset | STRING | YES | +clientTranId | STRING | YES | +kindType | STRING | YES | +recvWindow | LONG | NO | +timestamp | LONG | YES | + +**Notes:** +* kindType FUTURE_SPOT(future to spot)/SPOT_FUTURE(spot to future) + +## transfer asset to other address (TRADE) + +> **Response:** + +```javascript +{ + "tranId": 21841, + "status": "SUCCESS" +} +``` + +`` +POST /api/v1/asset/sendToAddress (HMAC SHA256) +`` + +**Weight:** +5 + +**Parameters:** + + +Name | Type | Mandatory | Description +---------------- | ------- | -------- | ---- +amount | DECIMAL | YES | +asset | STRING | YES | +toAddress | STRING | YES | +clientTranId | STRING | NO | +recvWindow | LONG | NO | +timestamp | LONG | YES | + +**Notes:** +* The target address must be a valid existing account and must not be the same as the sender’s account. +* The toAddress must be an EVM address. +* If clientTranId is provided, its length must be at least 20 characters. + + +## get withdraw fee (USER_DATA) +> **Response:** +```javascript +{ + "tokenPrice": 1.00019000, + "gasCost": 0.5000, + "gasUsdValue": 0.5 +} +``` + +`` +GET /api/v1/aster/withdraw/estimateFee (HMAC SHA256) +`` + +**Weight:** +1 + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +chainId | STRING | YES | +asset | STRING | YES | + +**Notes:** +* chainId: 1(ETH),56(BSC),42161(Arbi) +* gasCost: The minimum fee required for a withdrawal + +## withdraw (USER_DATA) +> **Response:** +```javascript +{ + "withdrawId": "1014729574755487744", + "hash":"0xa6d1e617a3f69211df276fdd8097ac8f12b6ad9c7a49ba75bbb24f002df0ebb" +} +``` + +`` +POST /api/v1/aster/user-withdraw (HMAC SHA256) +`` + +**Weight:** +1 + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +chainId | STRING | YES | 1(ETH),56(BSC),42161(Arbi) +asset | STRING | YES | +amount | STRING | YES | +fee | STRING | YES | +receiver | STRING | YES | The address of the current account +nonce | STRING | YES | The current time in microseconds +userSignature | STRING | YES | +recvWindow | LONG | NO | +timestamp | LONG | YES | + + +**Notes:** +* chainId: 1(ETH),56(BSC),42161(Arbi) +* receiver: The address of the current account +* If the futures account balance is insufficient, funds will be transferred from the spot account to the futures account for the withdrawal. +* userSignature demo + +```shell +const domain = { + name: 'Aster', + version: '1', + chainId: 56, + verifyingContract: ethers.ZeroAddress, + } + +const currentTime = Date.now() * 1000 + +const types = { + Action: [ + {name: "type", type: "string"}, + {name: "destination", type: "address"}, + {name: "destination Chain", type: "string"}, + {name: "token", type: "string"}, + {name: "amount", type: "string"}, + {name: "fee", type: "string"}, + {name: "nonce", type: "uint256"}, + {name: "aster chain", type: "string"}, + ], + } + const value = { + 'type': 'Withdraw', + 'destination': '0xD9cA6952F1b1349d27f91E4fa6FB8ef67b89F02d', + 'destination Chain': 'BSC', + 'token': 'USDT', + 'amount': '10.123400', + 'fee': '1.234567891', + 'nonce': currentTime, + 'aster chain': 'Mainnet', + } + + +const signature = await signer.signTypedData(domain, types, value) +``` + +## get user create apikey nonce (NONE) + +> **Response:** +```javascript + +111111 + +``` + +`` +POST /api/v1/getNonce +`` + +**Weight:** +1 + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +address | STRING | YES | +userOperationType | STRING | YES | CREATE_API_KEY +network | STRING | NO | + +**Notes:** +* userOperationType : CREATE_API_KEY +* network : For the Solana network, SOL must be provided; otherwise, this field is ignored. + +## create apikey (NONE) + +> **Response:** +```javascript +{ + "apiKey": "bb3b24d0a3dec88cb06be58a257e4575cb0b1bb256ad6fd90ae8fd0ee1d102ae", + "apiSecret": "9fe8f5642ae1961674ea0cb7f957fa99dc8e0421b607c985a963ad2ced90ae1c" +} +``` + +`` +POST /api/v1/createApiKey +`` + +**Weight:** +1 + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +address | STRING | YES | +userOperationType | STRING | YES | CREATE_API_KEY +network | STRING | NO | +userSignature | STRING | YES | +apikeyIP | STRING | NO | +desc | STRING | YES | +recvWindow | LONG | NO | +timestamp | LONG | YES | + +**Notes:** +* userOperationType : CREATE_API_KEY +* network : For the Solana network, SOL must be provided; otherwise, this field is ignored. +* desc: The same account cannot be duplicated, and the length must not exceed 20 characters. +* apikeyIP An array of IP addresses, separated by commas. +* Rate limit: 60 requests per minute per IP +* userSignature evm demo + +```shell +const nonce = 111111 +const message = 'You are signing into Astherus ${nonce}'; +const signature = await signer.signMessage(message); +``` + + +## Account Information (USER_DATA) + +> **Response:** +```javascript +{ + "feeTier": 0, + "canTrade": true, + "canDeposit": true, + "canWithdraw": true, + "canBurnAsset": true, + "updateTime": 0, + "balances": [ + { + "asset": "BTC", + "free": "4723846.89208129", + "locked": "0.00000000" + }, + { + "asset": "LTC", + "free": "4763368.68006011", + "locked": "0.00000000" + } + ] +} +``` + +`` +GET /api/v1/account (HMAC SHA256) +`` + +Get current account information. + +**Weight:** +5 + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +recvWindow | LONG | NO | +timestamp | LONG | YES | + + +## Account Trade List (USER_DATA) + +> **Response:** +```javascript   +[ + { + "symbol": "BNBUSDT", + "id": 1002, + "orderId": 266358, + "side": "BUY", + "price": "1", + "qty": "2", + "quoteQty": "2", + "commission": "0.00105000", + "commissionAsset": "BNB", + "time": 1755656788798, + "counterpartyId": 19, + "createUpdateId": null, + "maker": false, + "buyer": true + } +] +``` + +`` +GET /api/v1/userTrades (HMAC SHA256) +`` + +Get trades for a specific account and symbol. + +**Weight:** +5 + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +symbol | STRING | NO | +orderId|LONG|NO| This can only be used in combination with `symbol`. +startTime | LONG | NO | +endTime | LONG | NO | +fromId | LONG | NO | TradeId to fetch from. Default gets most recent trades. +limit | INT | NO | Default 500; max 1000. +recvWindow | LONG | NO | +timestamp | LONG | YES |   + +* 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. +* The parameter `fromId` cannot be sent with `startTime` or `endTime`.     + + + + + + + + +--- +# Websocket Market Streams + +* The base endpoint is: **wss://sstream.asterdex.com** +* Streams can be accessed either in a single raw stream or in a combined stream +* Raw streams are accessed at **/ws/\** +* Combined streams are accessed at **/stream?streams=\/\/\** +* Combined stream events are wrapped as follows: **{"stream":"\","data":\}** +* All symbols for streams are **lowercase** +* A single connection to **sstream.asterdex.com** is only valid for 24 hours; expect to be disconnected at the 24 hour mark +* The websocket server will send a `ping frame` every 3 minutes. If the websocket server does not receive a `pong frame` back from the connection within a 10 minute period, the connection will be disconnected. Unsolicited `pong frames` are allowed. + +## Live Subscribing/Unsubscribing to streams + +* The following data can be sent through the websocket instance in order to subscribe/unsubscribe from streams. Examples can be seen below. +* The `id` used in the JSON payloads is an unsigned INT used as an identifier to uniquely identify the messages going back and forth. +* In the response, if the `result` received is `null` this means the request sent was a success. + +### Subscribe to a stream + +> **Response** + ```javascript + { + "result": null, + "id": 1 + } + ``` + +* **Request** + + { + "method": "SUBSCRIBE", + "params": + [ + "btcusdt@aggTrade", + "btcusdt@depth" + ], + "id": 1 + } + + + +### Unsubscribe to a stream + +> **Response** + + ```javascript + { + "result": null, + "id": 312 + } + ``` + + +* **Request** + + { + "method": "UNSUBSCRIBE", + "params": + [ + "btcusdt@depth" + ], + "id": 312 + } + + + +### Listing Subscriptions + +> **Response** + + ```javascript + { + "result": [ + "btcusdt@aggTrade" + ], + "id": 3 + } + ``` + + +* **Request** + + { + "method": "LIST_SUBSCRIPTIONS", + "id": 3 + } + + + +### Setting Properties +Currently, the only property can be set is to set whether `combined` stream payloads are enabled or not. +The combined property is set to `false` when connecting using `/ws/` ("raw streams") and `true` when connecting using `/stream/`. + +> **Response** + + ```javascript +{ + "result": null, + "id": 5 +} + ``` + +* **Request** + + { + "method": "SET_PROPERTY", + "params": + [ + "combined", + true + ], + "id": 5 + } + + + + +### Retrieving Properties + +> **Response** + ```javascript + { + "result": true, // Indicates that combined is set to true. + "id": 2 + } + ``` + +* **Request** + + { + "method": "GET_PROPERTY", + "params": + [ + "combined" + ], + "id": 2 + } + + + + +### Error Messages + +Error Message | Description +---|--- +{"code": 0, "msg": "Unknown property", "id": '%s'} | Parameter used in the `SET_PROPERTY` or `GET_PROPERTY` was invalid +{"code": 1, "msg": "Invalid value type: expected Boolean", "id": '%s'} | Value should only be `true` or `false` +{"code": 2, "msg": "Invalid request: property name must be a string"}| Property name provided was invalid +{"code": 2, "msg": "Invalid request: request ID must be an unsigned integer"}| Parameter `id` had to be provided or the value provided in the `id` parameter is an unsupported type +{"code": 2, "msg": "Invalid request: unknown variant %s, expected one of `SUBSCRIBE`, `UNSUBSCRIBE`, `LIST_SUBSCRIPTIONS`, `SET_PROPERTY`, `GET_PROPERTY` at line 1 column 28"} | Possible typo in the provided method or provided method was neither of the expected values +{"code": 2, "msg": "Invalid request: too many parameters"}| Unnecessary parameters provided in the data +{"code": 2, "msg": "Invalid request: property name must be a string"} | Property name was not provided +{"code": 2, "msg": "Invalid request: missing field `method` at line 1 column 73"} | `method` was not provided in the data +{"code":3,"msg":"Invalid JSON: expected value at line %s column %s"} | JSON data sent has incorrect syntax. + + +## Aggregate Trade Streams + + +> **Payload:** +```javascript +{ + "e": "aggTrade", // Event type + "E": 123456789, // Event time + "s": "BNBBTC", // Symbol + "a": 12345, // Aggregate trade ID + "p": "0.001", // Price + "q": "100", // Quantity + "f": 100, // First trade ID + "l": 105, // Last trade ID + "T": 123456785, // Trade time + "m": true, // Is the buyer the market maker? + "M": true // Ignore +} +``` + +The Aggregate Trade Streams push trade information that is aggregated for a single taker order. + +**Stream Name:** `@aggTrade` + +**Update Speed:** Real-time + + +## Trade Streams + + +> **Payload:** +```javascript +{ + "e": "trade", // Event type + "E": 123456789, // Event time + "s": "BNBBTC", // Symbol + "t": 12345, // Trade ID + "p": "0.001", // Price + "q": "100", // Quantity + "T": 123456785, // Trade time + "m": true, // Is the buyer the market maker? +} +``` + +The Trade Streams push raw trade information; each trade has a unique buyer and seller. + +**Stream Name:** `@trade` + +**Update Speed:** Real-time + + + + + + +## Kline/Candlestick Streams + + +> **Payload:** +```javascript +{ + "e": "kline", // Event type + "E": 123456789, // Event time + "s": "BNBBTC", // Symbol + "k": { + "t": 123400000, // Kline start time + "T": 123460000, // Kline close time + "s": "BNBBTC", // Symbol + "i": "1m", // Interval + "f": 100, // First trade ID + "L": 200, // Last trade ID + "o": "0.0010", // Open price + "c": "0.0020", // Close price + "h": "0.0025", // High price + "l": "0.0015", // Low price + "v": "1000", // Base asset volume + "n": 100, // Number of trades + "x": false, // Is this kline closed? + "q": "1.0000", // Quote asset volume + "V": "500", // Taker buy base asset volume + "Q": "0.500", // Taker buy quote asset volume + "B": "123456" // Ignore + } +} +``` + +The Kline/Candlestick Stream push updates to the current klines/candlestick every second. + +**Stream Name:** `@kline_` + +**Update Speed:** 2000ms + +**Kline/Candlestick chart intervals:** + +m -> minutes; h -> hours; d -> days; w -> weeks; M -> months + +* 1m +* 3m +* 5m +* 15m +* 30m +* 1h +* 2h +* 4h +* 6h +* 8h +* 12h +* 1d +* 3d +* 1w +* 1M + + + + +## Individual Symbol Mini Ticker Stream + +> **Payload:** +```javascript + { + "e": "24hrMiniTicker", // Event type + "E": 123456789, // Event time + "s": "BNBBTC", // Symbol + "c": "0.0025", // Close price + "o": "0.0010", // Open price + "h": "0.0025", // High price + "l": "0.0010", // Low price + "v": "10000", // Total traded base asset volume + "q": "18" // Total traded quote asset volume + } +``` + +24hr rolling window mini-ticker statistics. These are NOT the statistics of the UTC day, but a 24hr rolling window for the previous 24hrs. + +**Stream Name:** `@miniTicker` + +**Update Speed:** 1000ms + + + + +## All Market Mini Tickers Stream + +> **Payload:** +```javascript +[ + { + // Same as @miniTicker payload + } +] +``` + +24hr rolling window mini-ticker statistics for all symbols that changed in an array. These are NOT the statistics of the UTC day, but a 24hr rolling window for the previous 24hrs. Note that only tickers that have changed will be present in the array. + +**Stream Name:** `!miniTicker@arr` + +**Update Speed:** 1000ms + + + +## Individual Symbol Ticker Streams + + +> **Payload:** +```javascript +{ + "e": "24hrTicker", // Event type + "E": 123456789, // Event time + "s": "BNBBTC", // Symbol + "p": "0.0015", // Price change + "P": "250.00", // Price change percent + "w": "0.0018", // Weighted average price + "c": "0.0025", // Last price + "Q": "10", // Last quantity + "o": "0.0010", // Open price + "h": "0.0025", // High price + "l": "0.0010", // Low price + "v": "10000", // Total traded base asset volume + "q": "18", // Total traded quote asset volume + "O": 0, // Statistics open time + "C": 86400000, // Statistics close time + "F": 0, // First trade ID + "L": 18150, // Last trade Id + "n": 18151 // Total number of trades +} +``` + + +24hr rolling window ticker statistics for a single symbol. These are NOT the statistics of the UTC day, but a 24hr rolling window for the previous 24hrs. + +**Stream Name:** `@ticker` + +**Update Speed:** 1000ms + + +## All Market Tickers Stream + +> **Payload:** +```javascript +[ + { + // Same as @ticker payload + } +] +``` + +24hr rolling window ticker statistics for all symbols that changed in an array. These are NOT the statistics of the UTC day, but a 24hr rolling window for the previous 24hrs. Note that only tickers that have changed will be present in the array. + +**Stream Name:** `!ticker@arr` + +**Update Speed:** 1000ms + + + + + +## Individual Symbol Book Ticker Streams + +> **Payload:** +```javascript +{ + "u":400900217, // order book updateId + "s":"BNBUSDT", // symbol + "b":"25.35190000", // best bid price + "B":"31.21000000", // best bid qty + "a":"25.36520000", // best ask price + "A":"40.66000000" // best ask qty +} +``` + + +Pushes any update to the best bid or ask's price or quantity in real-time for a specified symbol. + +**Stream Name:** `@bookTicker` + +**Update Speed:** Real-time + + + + + +## All Book Tickers Stream + +> **Payload:** +```javascript +{ + // Same as @bookTicker payload +} +``` + +Pushes any update to the best bid or ask's price or quantity in real-time for all symbols. + +**Stream Name:** `!bookTicker` + +**Update Speed:** Real-time + + + +## Partial Book Depth Streams + +> **Payload:** +```javascript +{ + "e": "depthUpdate", // Event type + "E": 123456789, // Event time + "T": 123456788, // Transaction time + "s": "BTCUSDT", // Symbol + "U": 100, // First update ID in event + "u": 120, // Final update ID in event + "pu": 99, // Final update Id in last stream(ie `u` in last stream) +  "bids": [ // Bids to be updated + [ + "0.0024", // Price level to be updated + "10" // Quantity + ] + ], + "asks": [ // Asks to be updated + [ + "0.0026", // Price level to be updated + "100" // Quantity + ] + ] +} +``` + +Top **** bids and asks, Valid **** are 5, 10, or 20. + +**Stream Names:** `@depth` OR `@depth@100ms`. + +**Update Speed:** 1000ms or 100ms + + + + +## Diff. Depth Stream + + +> **Payload:** +```javascript +{ + "e": "depthUpdate", // Event type + "E": 123456789, // Event time + "T": 123456788, // Transaction time + "s": "BTCUSDT", // Symbol + "U": 100, // First update ID in event + "u": 120, // Final update ID in event + "pu": 99, // Final update Id in last stream(ie `u` in last stream) + "b": [ // Bids to be updated + [ + "5.4", // Price level to be updated + "10" // Quantity + ] + ], + "a": [ // Asks to be updated + [ + "5.6", // Price level to be updated + "100" // Quantity + ] + ] +} +``` + +Order book price and quantity depth updates used to locally manage an order book. + +**Stream Name:** `@depth` OR `@depth@100ms` + +**Update Speed:** 1000ms or 100ms + + + +## How to manage a local order book correctly +1. Open a stream to **wss://sstream.asterdex.com/ws/bnbbtc@depth**. +2. Buffer the events you receive from the stream. +3. Get a depth snapshot from **https://sapi.asterdex.com/v1/depth?symbol=BNBBTC&limit=1000** . +4. Drop any event where `u` is <= `lastUpdateId` in the snapshot. +5. The first processed event should have `U` <= `lastUpdateId`+1 **AND** `u` >= `lastUpdateId`+1. +6. While listening to the stream, each new event's `U` should be equal to the previous event's `u`+1. +7. The data in each event is the **absolute** quantity for a price level. +8. If the quantity is 0, **remove** the price level. +9. Receiving an event that removes a price level that is not in your local order book can happen and is normal. + + + + + + +# User Data Streams + + +* The base API endpoint is: **https://sapi.asterdex.com** +* A User Data Stream `listenKey` is valid for 60 minutes after creation. +* Doing a `PUT` on a `listenKey` will extend its validity for 60 minutes. +* Doing a `DELETE` on a `listenKey` will close the stream and invalidate the `listenKey`. +* Doing a `POST` on an account with an active `listenKey` will return the currently active `listenKey` and extend its validity for 60 minutes. +* The base websocket endpoint is: **wss://sstream.asterdex.com** +* User Data Streams are accessed at **/ws/\** +* A single connection to **sstream.asterdex.com** is only valid for 24 hours; expect to be disconnected at the 24 hour mark + + +## LISTEN KEY + +### Create a ListenKey (USER_STREAM) + +> **Response:** +```javascript +{ + "listenKey": "pqia91ma19a5s61cv6a81va65sdf19v8a65a1a5s61cv6a81va65sdf19v8a65a1" +} +``` + + +`` +POST /api/v1/listenKey +`` + +Start a new user data stream. The stream will close after 60 minutes unless a keepalive is sent. If the account has an active `listenKey`, that `listenKey` will be returned and its validity will be extended for 60 minutes. + +**Weight:** +1 + +**Parameters:** +NONE + +### Ping/Keep-alive a ListenKey (USER_STREAM) + +> **Response:** +```javascript +{} +``` + +`` +PUT /api/v1/listenKey +`` + +Keepalive a user data stream to prevent a time out. User data streams will close after 60 minutes. It's recommended to send a ping about every 30 minutes. + +**Weight:** +1 + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +listenKey | STRING | YES + + +### Close a ListenKey (USER_STREAM) + +> **Response:** +```javascript +{} +``` + +`` +DELETE /api/v1/listenKey +`` + +Close out a user data stream. + +**Weight:** +1 + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +listenKey | STRING | YES + + + +## Payload: Balance Update + +`outboundAccountPosition` is sent any time an account balance has changed and contains the assets that were possibly changed by the event that generated the balance change. + +> **Payload:** +```javascript +{ + "B":[ //Balance + { + "a":"SLP25",   //Asset + "f":"10282.42029415",   //Free + "l":"653.00000001"   //Locked + }, + { + "a":"ADA25", + "f":"9916.96229880", + "l":"34.00510000" + } + ], + "e":"outboundAccountPosition",   //Event type + "T":1649926447190,   //Time of last account update + "E":1649926447205   //Event Time + "m":"WITHDRAW" // Event reason type +} +``` + + +## Payload: Order Update + +Orders are updated with the `executionReport` event. + +> **Payload:**   + +```javascript +{ + "s":"ADA25SLP25",   // symbol + "c":"Xzh0gnxT41PStbwqOtXnjD",  // client order id + "S":"SELL",   // order direction + "o":"LIMIT",   // order type + "f":"GTC",   // Time in force + "q":"10.001000",   // Order quantity + "p":"19.1000000000",   // Order price + "ap":"19.0999999955550656", //average price + "P":"0", //stop price + "x":"TRADE",   // Current execution type + "X":"PARTIALLY_FILLED",   // Current order status + "i":27,   // Order ID + "l":"1",   // Last executed quantity + "z":"8.999000",   // Cumulative filled quantity + "L":"19.1000000000",   // Last executed price + "n":"0.00382000",  // Commission amount + "N":"SLP25",   // Commission asset + "T":1649926447190,   //Trasanction Time + "t":18,   // transaction id + "m":true,   // is this trade the maker side? + "ot":"LIMIT", //original order type + "O":0,   // Order creation time + "Z":"171.88089996", // Cumulative quote asset transacted quantity + "Y":"19.1000000000000000",   // Last quote asset transacted quantity (i.e. lastPrice * lastQty) + "Q":"0",   // Quote Order Qty + "e":"executionReport",   // event + "E":1649926447209  // event time +} +``` + +**Execution types:** + +* NEW - The order has been accepted into the engine. +* CANCELED - The order has been canceled by the user. +* REPLACED (currently unused) +* TRADE - Part of the order or all of the order's quantity has filled. +* EXPIRED - The order was canceled according to the order type's rules (e.g. LIMIT FOK orders with no fill, LIMIT IOC or MARKET orders that partially fill) or by the exchange, (e.g. orders canceled during maintenance) + + + +# Error Codes + +> Here is the error JSON payload: + +```javascript +{ +"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 +* An unknown error occured while processing the request. + +### -1001 DISCONNECTED +* Internal error; unable to process your request. Please try again. + +### -1002 UNAUTHORIZED +* You are not authorized to execute this request. + +### -1003 TOO_MANY_REQUESTS +* Too many requests queued. +* Too many requests; please use the websocket for live updates. +* Too many requests; current limit is %s requests per minute. Please use the websocket for live updates to avoid polling the API. +* Way too many requests; IP banned until %s. Please use the websocket for live updates to avoid bans. + +### -1004 DUPLICATE_IP +* This IP is already on the white list + +### -1005 NO_SUCH_IP +* No such IP has been white listed + +### -1006 UNEXPECTED_RESP +* An unexpected response was received from the message bus. Execution status unknown. + +### -1007 TIMEOUT +* Timeout waiting for response from backend server. Send status unknown; execution status unknown. + +### -1010 ERROR_MSG_RECEIVED +* ERROR_MSG_RECEIVED. + +### -1011 NON_WHITE_LIST +* This IP cannot access this route. + +### -1013 INVALID_MESSAGE +* INVALID_MESSAGE. + +### -1014 UNKNOWN_ORDER_COMPOSITION +* Unsupported order combination. + +### -1015 TOO_MANY_ORDERS +* Too many new orders. +* Too many new orders; current limit is %s orders per %s. + +### -1016 SERVICE_SHUTTING_DOWN +* This service is no longer available. + +### -1020 UNSUPPORTED_OPERATION +* This operation is not supported. + +### -1021 INVALID_TIMESTAMP +* Timestamp for this request is outside of the recvWindow. +* Timestamp for this request was 1000ms ahead of the server's time. + +### -1022 INVALID_SIGNATURE +* Signature for this request is not valid. + +### -1023 START_TIME_GREATER_THAN_END_TIME +* Start time is greater than end time. + + +## 11xx - Request issues +### -1100 ILLEGAL_CHARS +* Illegal characters found in a parameter. +* Illegal characters found in parameter '%s'; legal range is '%s'. + +### -1101 TOO_MANY_PARAMETERS +* Too many parameters sent for this endpoint. +* Too many parameters; expected '%s' and received '%s'. +* Duplicate values for a parameter detected. + +### -1102 MANDATORY_PARAM_EMPTY_OR_MALFORMED +* A mandatory parameter was not sent, was empty/null, or malformed. +* Mandatory parameter '%s' was not sent, was empty/null, or malformed. +* Param '%s' or '%s' must be sent, but both were empty/null! + +### -1103 UNKNOWN_PARAM +* An unknown parameter was sent. + +### -1104 UNREAD_PARAMETERS +* Not all sent parameters were read. +* Not all sent parameters were read; read '%s' parameter(s) but was sent '%s'. + +### -1105 PARAM_EMPTY +* A parameter was empty. +* Parameter '%s' was empty. + +### -1106 PARAM_NOT_REQUIRED +* A parameter was sent when not required. +* Parameter '%s' sent when not required. + +### -1108 BAD_ASSET +* Invalid asset. + +### -1109 BAD_ACCOUNT +* Invalid account. + +### -1110 BAD_INSTRUMENT_TYPE +* Invalid symbolType. + +### -1111 BAD_PRECISION +* Precision is over the maximum defined for this asset. + +### -1112 NO_DEPTH +* No orders on book for symbol. + +### -1113 WITHDRAW_NOT_NEGATIVE +* Withdrawal amount must be negative. + +### -1114 TIF_NOT_REQUIRED +* TimeInForce parameter sent when not required. + +### -1115 INVALID_TIF +* Invalid timeInForce. + +### -1116 INVALID_ORDER_TYPE +* Invalid orderType. + +### -1117 INVALID_SIDE +* Invalid side. + +### -1118 EMPTY_NEW_CL_ORD_ID +* New client order ID was empty. + +### -1119 EMPTY_ORG_CL_ORD_ID +* Original client order ID was empty. + +### -1120 BAD_INTERVAL +* Invalid interval. + +### -1121 BAD_SYMBOL +* Invalid symbol. + +### -1125 INVALID_LISTEN_KEY +* This listenKey does not exist. + +### -1127 MORE_THAN_XX_HOURS +* Lookup interval is too big. +* More than %s hours between startTime and endTime. + +### -1128 OPTIONAL_PARAMS_BAD_COMBO +* Combination of optional parameters invalid. + +### -1130 INVALID_PARAMETER +* Invalid data sent for a parameter. +* Data sent for parameter '%s' is not valid. + +### -1136 INVALID_NEW_ORDER_RESP_TYPE +* Invalid newOrderRespType. + + +## 20xx - Processing Issues + +### -2010 NEW_ORDER_REJECTED +* NEW_ORDER_REJECTED + +### -2011 CANCEL_REJECTED +* CANCEL_REJECTED + +### -2013 NO_SUCH_ORDER +* Order does not exist. + +### -2014 BAD_API_KEY_FMT +* API-key format invalid. + +### -2015 REJECTED_MBX_KEY +* Invalid API-key, IP, or permissions for action. + +### -2016 NO_TRADING_WINDOW +* No trading window could be found for the symbol. Try ticker/24hrs instead. + +### -2018 BALANCE_NOT_SUFFICIENT +* Balance is insufficient. + +### -2020 UNABLE_TO_FILL +* Unable to fill. + +### -2021 ORDER_WOULD_IMMEDIATELY_TRIGGER +* Order would immediately trigger. + +### -2022 REDUCE_ONLY_REJECT +* ReduceOnly Order is rejected. + +### -2024 POSITION_NOT_SUFFICIENT +* Position is not sufficient. + +### -2025 MAX_OPEN_ORDER_EXCEEDED +* Reach max open order limit. + +### -2026 REDUCE_ONLY_ORDER_TYPE_NOT_SUPPORTED +* This OrderType is not supported when reduceOnly. + + +## 40xx - Filters and other Issues +### -4000 INVALID_ORDER_STATUS +* Invalid order status. + +### -4001 PRICE_LESS_THAN_ZERO +* Price less than 0. + +### -4002 PRICE_GREATER_THAN_MAX_PRICE +* Price greater than max price. + +### -4003 QTY_LESS_THAN_ZERO +* Quantity less than zero. + +### -4004 QTY_LESS_THAN_MIN_QTY +* Quantity less than min quantity. + +### -4005 QTY_GREATER_THAN_MAX_QTY +* Quantity greater than max quantity. + +### -4006 STOP_PRICE_LESS_THAN_ZERO +* Stop price less than zero. + +### -4007 STOP_PRICE_GREATER_THAN_MAX_PRICE +* Stop price greater than max price. + +### -4008 TICK_SIZE_LESS_THAN_ZERO +* Tick size less than zero. + +### -4009 MAX_PRICE_LESS_THAN_MIN_PRICE +* Max price less than min price. + +### -4010 MAX_QTY_LESS_THAN_MIN_QTY +* Max qty less than min qty. + +### -4011 STEP_SIZE_LESS_THAN_ZERO +* Step size less than zero. + +### -4012 MAX_NUM_ORDERS_LESS_THAN_ZERO +* Max mum orders less than zero. + +### -4013 PRICE_LESS_THAN_MIN_PRICE +* Price less than min price. + +### -4014 PRICE_NOT_INCREASED_BY_TICK_SIZE +* Price not increased by tick size. + +### -4015 INVALID_CL_ORD_ID_LEN +* Client order id is not valid. +* Client order id length should not be more than 36 chars + +### -4016 PRICE_HIGHTER_THAN_MULTIPLIER_UP +* Price is higher than mark price multiplier cap. + +### -4017 MULTIPLIER_UP_LESS_THAN_ZERO +* Multiplier up less than zero. + +### -4018 MULTIPLIER_DOWN_LESS_THAN_ZERO +* Multiplier down less than zero. + +### -4019 COMPOSITE_SCALE_OVERFLOW +* Composite scale too large. + +### -4020 TARGET_STRATEGY_INVALID +* Target strategy invalid for orderType '%s',reduceOnly '%b'. + +### -4021 INVALID_DEPTH_LIMIT +* Invalid depth limit. +* '%s' is not valid depth limit. + +### -4022 WRONG_MARKET_STATUS +* market status sent is not valid. + +### -4023 QTY_NOT_INCREASED_BY_STEP_SIZE +* Qty not increased by step size. + +### -4024 PRICE_LOWER_THAN_MULTIPLIER_DOWN +* Price is lower than mark price multiplier floor. + +### -4025 MULTIPLIER_DECIMAL_LESS_THAN_ZERO +* Multiplier decimal less than zero. + +### -4026 COMMISSION_INVALID +* Commission invalid. +* `%s` less than zero. +* `%s` absolute value greater than `%s` + +### -4027 INVALID_ACCOUNT_TYPE +* Invalid account type. + +### -4029 INVALID_TICK_SIZE_PRECISION +* Tick size precision is invalid. + +### -4030 INVALID_STEP_SIZE_PRECISION +* Step size precision is invalid. + +### -4031 INVALID_WORKING_TYPE +* Invalid parameter working type +* Invalid parameter working type: `%s` + +### -4032 EXCEED_MAX_CANCEL_ORDER_SIZE +* Exceed maximum cancel order size. +* Invalid parameter working type: `%s` + +### -4044 INVALID_BALANCE_TYPE +* Balance Type is invalid. + +### -4045 MAX_STOP_ORDER_EXCEEDED +* Reach max stop order limit. + +### -4055 AMOUNT_MUST_BE_POSITIVE +* Amount must be positive. + +### -4056 INVALID_API_KEY_TYPE +* Invalid api key type. + +### -4057 INVALID_RSA_PUBLIC_KEY +* Invalid api public key + +### -4058 MAX_PRICE_TOO_LARGE +* maxPrice and priceDecimal too large,please check. + + +### -4060 INVALID_POSITION_SIDE +* Invalid position side. + +### -4061 POSITION_SIDE_NOT_MATCH +* Order's position side does not match user's setting. + +### -4062 REDUCE_ONLY_CONFLICT +* Invalid or improper reduceOnly value. + +### -4083 PLACE_BATCH_ORDERS_FAIL +* Fail to place batch orders. + +### -4084 UPCOMING_METHOD +* Method is not allowed currently. Upcoming soon. + +### -4086 INVALID_PRICE_SPREAD_THRESHOLD +* Invalid price spread threshold + +### -4087 REDUCE_ONLY_ORDER_PERMISSION +* User can only place reduce only order + +### -4088 NO_PLACE_ORDER_PERMISSION +* User can not place order currently + +### -4114 INVALID_CLIENT_TRAN_ID_LEN +* clientTranId is not valid +* Client tran id length should be less than 64 chars + +### -4115 DUPLICATED_CLIENT_TRAN_ID +* clientTranId is duplicated +* Client tran id should be unique within 7 days + +### -4118 REDUCE_ONLY_MARGIN_CHECK_FAILED +* ReduceOnly Order Failed. Please check your existing position and open orders + +### -4131 MARKET_ORDER_REJECT +* The counterparty's best price does not meet the PERCENT_PRICE filter limit + +### -4135 INVALID_ACTIVATION_PRICE +* Invalid activation price + +### -4137 QUANTITY_EXISTS_WITH_CLOSE_POSITION +* Quantity must be zero with closePosition equals true + +### -4138 REDUCE_ONLY_MUST_BE_TRUE +* Reduce only must be true with closePosition equals true + +### -4139 ORDER_TYPE_CANNOT_BE_MKT +* Order type can not be market if it's unable to cancel + +### -4140 INVALID_OPENING_POSITION_STATUS +* Invalid symbol status for opening position + +### -4141 SYMBOL_ALREADY_CLOSED +* Symbol is closed + +### -4142 STRATEGY_INVALID_TRIGGER_PRICE +* REJECT: take profit or stop order will be triggered immediately + +### -4164 MIN_NOTIONAL +* Order's notional must be no smaller than 5.0 (unless you choose reduce only) +* Order's notional must be no smaller than %s (unless you choose reduce only) + +### -4165 INVALID_TIME_INTERVAL +* Invalid time interval +* Maximum time interval is %s days + +### -4183 PRICE_HIGHTER_THAN_STOP_MULTIPLIER_UP +* Price is higher than stop price multiplier cap. +* Limit price can't be higher than %s. + +### -4184 PRICE_LOWER_THAN_STOP_MULTIPLIER_DOWN +* Price is lower than stop price multiplier floor. +* Limit price can't be lower than %s. diff --git a/apollox-finance-spot-api_CN.md b/apollox-finance-spot-api_CN.md new file mode 100644 index 0000000..2bb35de --- /dev/null +++ b/apollox-finance-spot-api_CN.md @@ -0,0 +1,2772 @@ +# 基本信息 +## API 基本信息 +* 本篇列出接口的baseurl: **https://sapi.asterdex.com** +* 所有接口的响应都是 JSON 格式。 +* 所有时间、时间戳均为UNIX时间,单位为**毫秒**。 + +## API Key 设置 +* 很多接口需要API Key才可以访问. +* 设置API Key的同时,为了安全,建议设置IP访问白名单. +* **永远不要把你的API key/secret告诉给任何人** + + + +### 注意事项 +* TESTUSDT 或任何其他以 TEST 开头的交易对仅用于 Aster 的内部测试。请不要在这些以 TEST 开头的交易品种上进行交易。Aster 对因交易这些交易对而造成的资金损失不承担任何责任。但是,如果您遇到问题,您可以随时联系支持人员,我们将尽力帮助您收回资金。 + + +### HTTP 返回代码 +* HTTP `4XX` 错误码用于指示错误的请求内容、行为、格式。问题在于请求者。 +* HTTP `403` 错误码表示违反WAF限制(Web应用程序防火墙)。 +* HTTP `429` 错误码表示警告访问频次超限,即将被封IP。 +* HTTP `418` 表示收到429后继续访问,IP已经被封禁。 +* HTTP `5XX` 错误码用于指示Aster服务侧的问题。 + +### 接口错误代码 +* 使用接口 `/api/v1`, 每个接口都有可能抛出异常; +> API的错误代码返回形式如下: +```javascript +{ + "code": -1121, + "msg": "Invalid symbol." +} +``` + +### 接口的基本信息 + +* `GET` 方法的接口, 参数必须在 `query string`中发送。 +* `POST`, `PUT`, 和 `DELETE` 方法的接口,参数可以在内容形式为`application/x-www-form-urlencoded`的 `query string` 中发送,也可以在 `request body` 中发送。 +* 对参数的顺序不做要求。 + +--- +## 访问限制 +### 访问限制基本信息 + +* 在 `/api/v1/exchangeInfo` `rateLimits` 数组中包含与交易的有关REQUEST_WEIGHT和ORDERS速率限制相关的对象。这些在 `限制种类 (rateLimitType)` 下的 `枚举定义` 部分中进一步定义。 +* 违反任何一个速率限制时,将返回429。 + +### IP 访问限制 +* 每个请求的回报中包含一个`X-MBX-USED-WEIGHT-(intervalNum)(intervalLetter)`的头,其中包含当前IP所有请求的已使用权重。 +* 每一个接口均有一个相应的权重(weight),有的接口根据参数不同可能拥有不同的权重。越消耗资源的接口权重就会越大。 +* 收到429时,您有责任停止发送请求,不得滥用API。 +* **收到429后仍然继续违反访问限制,会被封禁IP,并收到418错误码** +* 频繁违反限制,封禁时间会逐渐延长,**从最短2分钟到最长3天**。 +* `Retry-After`的头会与带有418或429的响应发送,并且会给出**以秒为单位**的等待时长(如果是429)以防止禁令,或者如果是418,直到禁令结束。 +* **访问限制是基于IP的,而不是API Key** + + + + +### 下单频率限制 +* 每个成功的下单回报将包含一个`X-MBX-ORDER-COUNT-(intervalNum)(intervalLetter)`的头,其中包含当前账户已用的下单限制数量。 +* 当下单数超过限制时,会收到带有429但不含`Retry-After`头的响应。请检查 `GET api/v1/exchangeInfo` 的下单频率限制 (rateLimitType = ORDERS) 并等待封禁时间结束。 +* 被拒绝或不成功的下单并不保证回报中包含以上头内容。 +* **下单频率限制是基于每个账户计数的。** + +### WEB SOCKET 连接限制 + +* Websocket服务器每秒最多接受5个消息。消息包括: + * PING帧 + * PONG帧 + * JSON格式的消息, 比如订阅, 断开订阅. +* 如果用户发送的消息超过限制,连接会被断开连接。反复被断开连接的IP有可能被服务器屏蔽。 +* 单个连接最多可以订阅 **1024** 个Streams。 + + +--- +## 接口鉴权类型 +* 每个接口都有自己的鉴权类型,鉴权类型决定了访问时应当进行何种鉴权。 +* 鉴权类型会在本文档中各个接口名称旁声明,如果没有特殊声明即默认为 `NONE`。 +* 如果需要 API-keys,应当在HTTP头中以 `X-MBX-APIKEY`字段传递。 +* API-keys 与 secret-keys **是大小写敏感的**。 +* 默认 API-keys 可访问所有鉴权路径. + +鉴权类型 | 描述 +------------ | ------------ +NONE | 不需要鉴权的接口 +TRADE | 需要有效的 API-Key 和签名 +USER_DATA | 需要有效的 API-Key 和签名 +USER_STREAM | 需要有效的 API-Key +MARKET_DATA | 需要有效的 API-Key + + +* `TRADE` 和`USER_DATA` 接口是 签名(SIGNED)接口. + +--- +## SIGNED (TRADE AND USER_DATA) Endpoint security +* 调用`SIGNED` 接口时,除了接口本身所需的参数外,还需要在`query string` 或 `request body`中传递 `signature`, 即签名参数。 +* 签名使用`HMAC SHA256`算法. API-KEY所对应的API-Secret作为 `HMAC SHA256` 的密钥,其他所有参数作为`HMAC SHA256`的操作对象,得到的输出即为签名。 +* `签名` **大小写不敏感**. +* "totalParams"定义为与"request body"串联的"query string"。 + +### 时间同步安全 +* 签名接口均需要传递 `timestamp`参数,其值应当是请求发送时刻的unix时间戳(毫秒)。 +* 服务器收到请求时会判断请求中的时间戳,如果是5000毫秒之前发出的,则请求会被认为无效。这个时间空窗值可以通过发送可选参数 `recvWindow`来定义。 + +> 逻辑伪代码如下: +```javascript + if (timestamp < (serverTime + 1000) && (serverTime - timestamp) <= recvWindow) + { + // process request + } + else + { + // reject request + } +``` + +**关于交易时效性** 互联网状况并不完全稳定可靠,因此你的程序本地到Aster服务器的时延会有抖动。这是我们设置`recvWindow`的目的所在,如果你从事高频交易,对交易时效性有较高的要求,可以灵活设置`recvWindow`以达到你的要求。 + + + +### POST /api/v1/order 的示例 +以下是在linux bash环境下使用 echo openssl 和curl工具实现的一个调用接口下单的示例 apikey、secret仅供示范 + +Key | Value +------------ | ------------ +apiKey | 4452d7e2ed4da80b74105e02d06328c71a34488c9fdd60a5a0900d42d584b795 +secretKey | fdde510a2b71fa43a43bff3e3cf7819c8c66df34633d338050f4f59664b3b313 + + +参数 | 取值 +------------ | ------------ +symbol | BNBUSDT +side | BUY +type | LIMIT +timeInForce | GTC +quantity | 5 +price | 1.1 +recvWindow | 5000 +timestamp | 1756187806000 + + +#### 示例 1: 所有参数通过 request body 发送 + +> **Example 1** +> **HMAC SHA256 signature:** +```shell + $ echo -n "symbol=BNBUSDT&side=BUY&type=LIMIT&timeInForce=GTC&quantity=5&price=1.1&recvWindow=5000×tamp=1756187806000" | openssl dgst -sha256 -hmac "fdde510a2b71fa43a43bff3e3cf7819c8c66df34633d338050f4f59664b3b313" + (stdin)= e09169bf6c02ec4b29fa1bdc3a967f92c8c6cfcde0551ba1d477b2d3cf4c51b0 +``` + + +> **curl command:** +```shell + (HMAC SHA256) + $ curl -H "X-MBX-APIKEY: 4452d7e2ed4da80b74105e02d06328c71a34488c9fdd60a5a0900d42d584b795" -X POST 'https://sapi.asterdex.com/api/v1/order' -d 'symbol=BNBUSDT&side=BUY&type=LIMIT&timeInForce=GTC&quantity=5&price=1.1&recvWindow=5000×tamp=1756187806000&signature=e09169bf6c02ec4b29fa1bdc3a967f92c8c6cfcde0551ba1d477b2d3cf4c51b0' +``` + +* **requestBody:** + +symbol=BNBUSDT +&side=BUY +&type=LIMIT +&timeInForce=GTC +&quantity=5 +&price=1.1 +&recvWindow=5000 +×tamp=1756187806000 + + +#### 示例 2: 所有参数通过 query string 发送 + +> **Example 2** +> **HMAC SHA256 signature:** +```shell + $ echo -n "symbol=BNBUSDT&side=BUY&type=LIMIT&timeInForce=GTC&quantity=5&price=1.1&recvWindow=5000×tamp=1756187806000" | openssl dgst -sha256 -hmac "fdde510a2b71fa43a43bff3e3cf7819c8c66df34633d338050f4f59664b3b313" + (stdin)= e09169bf6c02ec4b29fa1bdc3a967f92c8c6cfcde0551ba1d477b2d3cf4c51b0 +``` +> **curl command:** +```shell + (HMAC SHA256) + $ curl -H "X-MBX-APIKEY: 4452d7e2ed4da80b74105e02d06328c71a34488c9fdd60a5a0900d42d584b795" -X POST 'https://sapi.asterdex.com/api/v1/order?symbol=BNBUSDT&side=BUY&type=LIMIT&timeInForce=GTC&quantity=5&price=1.1&recvWindow=5000×tamp=1756187806000&signature=e09169bf6c02ec4b29fa1bdc3a967f92c8c6cfcde0551ba1d477b2d3cf4c51b0' +``` +* **queryString:** + +symbol=BNBUSDT +&side=BUY +&type=LIMIT +&timeInForce=GTC +&quantity=5 +&price=1.1 +&recvWindow=5000 +×tamp=1756187806000 + +--- + +## 公开 API 参数 +### 术语 + +这里的术语适用于全部文档,建议特别是新手熟读,也便于理解。 + +* `base asset` 指一个交易对的交易对象,即写在靠前部分的资产名, 比如`BTCUSDT`, `BTC`是`base asset`。 +* `quote asset` 指一个交易对的定价资产,即写在靠后部分的资产名, 比如`BTCUSDT`, `USDT`是`quote asset`。 + +### 枚举定义 +**交易对状态 (状态 status):** + +* TRADING 交易中 + + +**交易对类型:** + +* SPOT 现货 + +**订单状态 (状态 status):** + +状态 | 描述 +-----------| -------------- +`NEW` | 订单被交易引擎接受 +`PARTIALLY_FILLED`| 部分订单被成交 +`FILLED` | 订单完全成交 +`CANCELED` | 用户撤销了订单 +`REJECTED` | 订单没有被交易引擎接受,也没被处理 +`EXPIRED` | 订单被交易引擎取消, 比如
LIMIT FOK 订单没有成交
市价单没有完全成交
交易所维护期间被取消的订单 + + +**订单类型 (orderTypes, type):** + +* LIMIT 限价单 +* MARKET 市价单 +* STOP 限价止损单 +* TAKE_PROFIT 限价止盈单 +* STOP_MARKET 市价止损单 +* TAKE_PROFIT_MARKET 市价止盈单 + +**订单返回类型 (newOrderRespType):** + +* ACK +* RESULT +* FULL + +**订单方向 (方向 side):** + +* BUY 买入 +* SELL 卖出 + +**有效方式 (timeInForce):** + +这里定义了订单多久能够失效 + +Status | Description +-----------| -------------- +`GTC` | 成交为止
订单会一直有效,直到被成交或者取消。 +`IOC` | 无法立即成交的部分就撤销
订单在失效前会尽量多的成交。 +`FOK` | 无法全部立即成交就撤销
如果无法全部成交,订单会失效。 +`GTX` | 直到挂单成交
限价只挂单。 + +**K线间隔:** + +m -> 分钟; h -> 小时; d -> 天; w -> 周; M -> 月 + +* 1m +* 3m +* 5m +* 15m +* 30m +* 1h +* 2h +* 4h +* 6h +* 8h +* 12h +* 1d +* 3d +* 1w +* 1M + +**限制种类 (rateLimitType)** + +> REQUEST_WEIGHT +```json + { + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200 + } +``` + +> ORDERS +```json + { + "rateLimitType": "ORDERS", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 100 + } +``` + + +* REQUEST_WEIGHT 单位时间请求权重之和上限 + +* ORDERS 单位时间下单次数限制 + + +**限制间隔 (interval)** + +* MINUTE 分 + +--- +## 过滤器 +过滤器,即Filter,定义了一系列交易规则。 +共有两类,分别是针对交易对的过滤器`symbol filters`,和针对整个交易所的过滤器`exchange filters`(暂不支持) + +### 交易对过滤器   + +#### PRICE_FILTER 价格过滤器 + +> **/exchangeInfo 响应中的格式:** +```javascript + { + "minPrice": "556.72", + "maxPrice": "4529764", + "filterType": "PRICE_FILTER", + "tickSize": "0.01"   + } +``` + +`价格过滤器` 用于检测订单中 `price` 参数的合法性。包含以下三个部分: + +* `minPrice` 定义了 `price`/`stopPrice` 允许的最小值。 +* `maxPrice` 定义了 `price`/`stopPrice` 允许的最大值。 +* `tickSize` 定义了 `price`/`stopPrice` 的步进间隔,即price必须等于minPrice+(tickSize的整数倍) + +以上每一项均可为0,为0时代表这一项不再做限制。 + +逻辑伪代码如下: + +* `price` >= `minPrice` +* `price` <= `maxPrice` +* (`price`-`minPrice`) % `tickSize` == 0 + + +#### PERCENT_PRICE 价格振幅过滤器 + +> **/exchangeInfo 响应中的格式:** +```javascript + { + "multiplierDown": "0.9500", + "multiplierUp": "1.0500", + "multiplierDecimal": "4", + "filterType": "PERCENT_PRICE" +  } +``` + +`PERCENT_PRICE`过滤器基于指数价格来定义价格的有效范围。 + +为了通过"价格百分比","价格"必须符合以下条件: + +* `price` <=`indexPrice` *`multiplierUp` +* `price`> =`indexPrice` *`multiplierDown` + + +#### LOT_SIZE 订单尺寸 + +> **/exchangeInfo 响应中的格式:** +```javascript + { + "stepSize": "0.00100000", +   "filterType": "LOT_SIZE", + "maxQty": "100000.00000000", +   "minQty": "0.00100000" + } +``` + +Lots是拍卖术语,`LOT_SIZE` 过滤器对订单中的 `quantity` 也就是数量参数进行合法性检查。包含三个部分: + +* `minQty` 表示 `quantity` 允许的最小值。 +* `maxQty` 表示 `quantity` 允许的最大值。 +* `stepSize` 表示 `quantity` 允许的步进值。 + +逻辑伪代码如下: + +* `quantity` >= `minQty` +* `quantity` <= `maxQty` +* (`quantity`-`minQty`) % `stepSize` == 0 + + + + +#### MARKET_LOT_SIZE 市价订单尺寸 + +> ***/exchangeInfo 响应中的格式:** +```javascript + { + "stepSize": "0.00100000", +   "filterType": "MARKET_LOT_SIZE" + "maxQty": "100000.00000000", + "minQty": "0.00100000" + } +``` + + +`MARKET_LOT_SIZE`过滤器为交易对上的`MARKET`订单定义了`数量`(即拍卖中的"手数")规则。 共有3部分: + +* `minQty`定义了允许的最小`quantity`。 +* `maxQty`定义了允许的最大数量。 +* `stepSize`定义了可以增加/减少数量的间隔。 + +为了通过`market lot size`,`quantity`必须满足以下条件: + +* `quantity` >= `minQty` +* `quantity` <= `maxQty` +* (`quantity`-`minQty`) % `stepSize` == 0 + + + + + + + + + + +# 行情接口 +## 测试服务器连通性 +> **响应** +```javascript +{} +``` +`` +GET /api/v1/ping +`` + +测试能否联通 Rest API。 + +**权重:** +1 + +**参数:** +NONE + + +## 获取服务器时间 +> **响应** +```javascript +{ + "serverTime": 1499827319559 +} +``` +`` +GET /api/v1/time +`` + +测试能否联通 Rest API 并获取服务器时间。 + +**权重:** +1 + +**参数:** +NONE + + +## 交易规范信息 + +> **响应** + +```javascript     +{ + "timezone": "UTC", + "serverTime": 1756197279679, + "rateLimits": [{ + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 6000 + }, + { + "rateLimitType": "ORDERS", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 6000 + }, + { + "rateLimitType": "ORDERS", + "interval": "SECOND", + "intervalNum": 10, + "limit": 300 + } + ], + "exchangeFilters": [], + "assets": [{ + "asset": "USD" + }, { + "asset": "USDT" + }, + { + "asset": "BNB" + } + ], + "symbols": [{ + "status": "TRADING", + "baseAsset": "BNB", + "quoteAsset": "USDT", + "pricePrecision": 8, + "quantityPrecision": 8, + "baseAssetPrecision": 8, + "quotePrecision": 8, + "filters": [{ + "minPrice": "0.01000000", + "maxPrice": "100000", + "filterType": "PRICE_FILTER", + "tickSize": "0.01000000" + }, + { + "stepSize": "0.00100000", + "filterType": "LOT_SIZE", + "maxQty": "1000", + "minQty": "1" + }, + { + "stepSize": "0.00100000", + "filterType": "MARKET_LOT_SIZE", + "maxQty": "900000", + "minQty": "0.00100000" + }, + { + "limit": 200, + "filterType": "MAX_NUM_ORDERS" + }, + { + "minNotional": "5", + "filterType": "MIN_NOTIONAL" + }, + { + "maxNotional": "100", + "filterType": "MAX_NOTIONAL" + }, + { + "maxNotional": "100", + "minNotional": "5", + "avgPriceMins": 5, + "applyMinToMarket": true, + "filterType": "NOTIONAL", + "applyMaxToMarket": true + }, + { + "multiplierDown": "0", + "multiplierUp": "5", + "multiplierDecimal": "0", + "filterType": "PERCENT_PRICE" + }, + { + "bidMultiplierUp": "5", + "askMultiplierUp": "5", + "bidMultiplierDown": "0", + "avgPriceMins": 5, + "multiplierDecimal": "0", + "filterType": "PERCENT_PRICE_BY_SIDE", + "askMultiplierDown": "0" + } + ], + "orderTypes": [ + "LIMIT", + "MARKET", + "STOP", + "STOP_MARKET", + "TAKE_PROFIT", + "TAKE_PROFIT_MARKET" + ], + "timeInForce": [ + "GTC", + "IOC", + "FOK", + "GTX" + ], + "symbol": "BNBUSDT", + "ocoAllowed": false + }] +} +``` + +`` +GET /api/v1/exchangeInfo +`` + +获取交易规则和交易对信息。 + +**权重:** +1 + +**参数:** +无 + + +## 深度信息 + +> **响应** + +```javascript +{ + "lastUpdateId": 1027024, + "E":1589436922972, // 消息时间 + "T":1589436922959, // 撮合引擎时间 + "bids": [ + [ + "4.00000000", // 价位 + "431.00000000" // 挂单量 + ] + ], + "asks": [ + [ + "4.00000200", + "12.00000000" + ] + ] +} +``` +`` +GET /api/v1/depth +`` + +**权重:** + +基于限制调整: + +限制 | 权重 +------------ | ------------ +5, 10, 20, 50 | 2 +100 | 5 +500 | 10 +1000 | 20 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +limit | INT | NO | 默认 100. 可选值:[5, 10, 20, 50, 100, 500, 1000] + + +## 近期成交列表 + +> **响应** + +```javascript +[ + { + "id": 657, + "price": "1.01000000", + "qty": "5.00000000", + "baseQty": "4.95049505", + "time": 1755156533943, + "isBuyerMaker": false + } +] +``` +`` +GET /api/v1/trades +`` + +获取近期成交 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +limit | INT | NO | 默认 500;最大1000 + + +## 查询历史成交 (MARKET_DATA) + +> **响应** + +```javascript +[ + { + "id": 1140, + "price": "1.10000000", + "qty": "7.27200000", + "baseQty": "6.61090909", + "time": 1756094288700, + "isBuyerMaker": false + } +] +``` +`` +GET /api/v1/historicalTrades +`` + +获取历史成交。 + +**权重:** +20 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +limit | INT | NO | 默认 500; 最大值 1000. +fromId | LONG | NO | 从哪一条成交id开始返回. 缺省返回最近的成交记录。 + + +## 近期成交(归集) + +> **响应** + +```javascript +[ + { + "a": 26129, // 归集成交ID + "p": "0.01633102", // 成交价 + "q": "4.70443515", // 成交量 + "f": 27781, // 被归集的首个成交ID + "l": 27781, // 被归集的末个成交ID + "T": 1498793709153, // 成交时间 + "m": true, // 是否为主动卖出单 + } +] +``` +`` +GET /api/v1/aggTrades +`` + +归集交易与逐笔交易的区别在于,同一价格、同一方向、同一时间的trade会被聚合为一条 + +**权重:** +20 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +fromId | LONG | NO | 从包含fromId的成交id开始返回结果 +startTime | LONG | NO | 从该时刻之后的成交记录开始返回结果 +endTime | LONG | NO | 返回该时刻为止的成交记录 +limit | INT | NO | 默认 500; 最大 1000. +* 如果发送startTime和endTime,间隔必须小于一小时。 +* 如果没有发送任何筛选参数(fromId, startTime,endTime),默认返回最近的成交记录 + + +## K线数据 + +> **响应** +```javascript +[ + [ + 1499040000000, // 开盘时间 + "0.01634790", // 开盘价 + "0.80000000", // 最高价 + "0.01575800", // 最低价 + "0.01577100", // 收盘价(当前K线未结束的即为最新价) + "148976.11427815", // 成交量 + 1499644799999, // 收盘时间 + "2434.19055334", // 成交额 + 308, // 成交笔数 + "1756.87402397", // 主动买入成交量 + "28.46694368", // 主动买入成交额 + ] +] +``` +`` +GET /api/v1/klines +`` + +每根K线代表一个交易对。 +每根K线的开盘时间可视为唯一ID + + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +interval | ENUM | YES | 详见枚举定义:K线间隔 +startTime | LONG | NO | +endTime | LONG | NO | +limit | INT | NO | 默认 500; 最大 1500. +* 如果未发送 startTime 和 endTime ,默认返回最近的交易。 + + + +## 24hr 价格变动情况 + +> **响应** + +```javascript +{ + "symbol": "BTCUSDT", + "priceChange": "-94.99999800", //24小时价格变动 + "priceChangePercent": "-95.960", //24小时价格变动百分比 + "weightedAvgPrice": "0.29628482", //加权平均价 + "prevClosePrice": "3.89000000", //上一次结束价格 + "lastPrice": "4.00000200", //最近一次成交价 + "lastQty": "200.00000000", //最近一次成交额 + "bidPrice": "866.66000000", //最高的买入价格 + "bidQty": "72.05100000", //最高的买入价格的数量 + "askPrice": "866.73000000", //最低的卖出价 + "askQty": "1.21700000", //最低的卖出价格的数量 + "openPrice": "99.00000000", //24小时内第一次成交的价格 + "highPrice": "100.00000000", //24小时最高价 + "lowPrice": "0.10000000", //24小时最低价 + "volume": "8913.30000000", //24小时成交量 + "quoteVolume": "15.30000000", //24小时成交额 + "openTime": 1499783499040, //24小时内,第一笔交易的发生时间 + "closeTime": 1499869899040, //24小时内,最后一笔交易的发生时间 + "firstId": 28385, // 首笔成交id + "lastId": 28460, // 末笔成交id + "count": 76 // 成交笔数 +} +``` + +`` +GET /api/v1/ticker/24hr +`` + +24 小时滚动窗口价格变动数据。 请注意,不携带symbol参数会返回全部交易对数据,此时返回的数据为示例相应的数组,不仅数据庞大,而且权重极高 + +**权重:** +1 单一交易对; +**40** 交易对参数缺失; + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | NO | +* 请注意,不携带symbol参数会返回全部交易对数据 + +## 最新价格 + +> **响应** + +```javascript +{ + "symbol": "ADAUSDT", + "price": "1.30000000", + "time": 1649666690902 +} +``` + +> OR + +```javascript +[ + { + "symbol": "ADAUSDT", + "price": "1.30000000", + "time": 1649666690902 + } +] +``` + +`` +GET /api/v1/ticker/price +`` + +获取交易对最新价格 + +**权重:** +1 单一交易对; +**2** 交易对参数缺失; + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | NO | +* 不发送交易对参数,则会返回所有交易对信息 + + +## 当前最优挂单 +> **响应** +```javascript +{ + "symbol": "LTCBTC", + "bidPrice": "4.00000000", + "bidQty": "431.00000000", + "askPrice": "4.00000200", + "askQty": "9.00000000" + "time": 1589437530011 // 交易时间 +} +``` +> OR +```javascript +[ + { + "symbol": "LTCBTC", + "bidPrice": "4.00000000", + "bidQty": "431.00000000", + "askPrice": "4.00000200", + "askQty": "9.00000000", + "time": 1589437530011 // 交易时间 + } +] +``` + +`` +GET /api/v1/ticker/bookTicker +`` + +返回当前最优的挂单(最高买单,最低卖单) + +**权重:** +1 单一交易对; +**2** 交易对参数缺失; + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | NO | +* 不发送交易对参数,则会返回所有交易对信息 + +## 获取Symbol手续费 + +> **响应** + +```javascript +{ + "symbol": "APXUSDT", + "makerCommission": "0.000200",     + "takerCommission": "0.000700" +} +``` +`` +GET /api/v1/commissionRate +`` + +获取Symbol手续费。 + +**权重:** +20 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +recvWindow | LONG | NO |赋值不能大于 ```60000``` +timestamp | LONG | YES | + + + + + +# 现货账户和交易接口 + + +## 下单 (TRADE) + +> **Response ACK:** + +```javascript +{ + "symbol": "BTCUSDT", // 交易对 + "orderId": 28, // 系统的订单ID + "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP", // 客户自己设置的ID + "updateTime": 1507725176595, // 交易的时间戳 + "price": "0.00000000", // 订单价格 + "avgPrice": "0.0000000000000000", //平均价格 + "origQty": "10.00000000", // 用户设置的原始订单数量 + "cumQty": "0", //累计数量 + "executedQty": "10.00000000", // 交易的订单数量 + "cumQuote": "10.00000000", // 累计交易的金额 + "status": "FILLED", // 订单状态 + "timeInForce": "GTC", // 订单的时效方式 + "stopPrice": "0", //触发价格 + "origType": "LIMIT", //触发前订单类型 + "type": "LIMIT", // 订单类型, 比如市价单,现价单等 + "side": "SELL", // 订单方向,买还是卖 +} +``` + +`` +POST /api/v1/order (HMAC SHA256) +`` + +发送下单。 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +side | ENUM | YES | 详见枚举定义:订单方向 +type | ENUM | YES | 详见枚举定义:订单类型 +timeInForce | ENUM | NO | 详见枚举定义:有效方式 +quantity | DECIMAL | NO | +quoteOrderQty|DECIMAL|NO| +price | DECIMAL | NO | +newClientOrderId | STRING | NO | 客户自定义的唯一订单ID。 如果未发送,则自动生成 +stopPrice | DECIMAL | NO | 仅 `STOP`, `STOP_MARKET` , `TAKE_PROFIT`,`TAKE_PROFIT_MARKET` 需要此参数。 +recvWindow | LONG | NO |赋值不能大于 ```60000``` +timestamp | LONG | YES | + +基于订单 `type`不同,强制要求某些参数: + +类型 | 强制要求的参数 +------------ | ------------ +`LIMIT` | `timeInForce`, `quantity`, `price` +`MARKET` | `quantity` 或 `quoteOrderQty` +`STOP`和`TAKE_PROFIT` | `quantity`, `price`, `stopPrice` +`STOP_MARKET`和`TAKE_PROFIT_MARKET` | `quantity`, `stopPrice` + +其他信息: + +* 下`MARKET` `SELL`市价单,用户通过`QUANTITY`控制想用市价单卖出的基础资产数量。 + * 比如在`BTCUSDT`交易对上下一个`MARKET` `SELL`市价单, 通过`QUANTITY`让用户指明想卖出多少BTC。 +* 下`MARKET` `BUY`的市价单,用户使用 `quoteOrderQty` 控制想用市价单买入的报价资产数量,`QUANTITY`将由系统根据市场流动性计算出来。 +  * 比如在`BTCUSDT`交易对上下一个`MARKET` `BUY`市价单, 通过`quoteOrderQty`让用户选择想使用多少USDT买入BTC。 +* 使用 `quoteOrderQty` 的市价单`MARKET`不会突破`LOT_SIZE`的限制规则; 报单会按给定的`quoteOrderQty`尽可能接近地被执行。 +* 除非之前的订单已经成交, 不然设置了相同的`newClientOrderId`订单会被拒绝。 + + + +## 撤销订单 (TRADE) + +> **响应** + +```javascript +{ + "symbol": "BTCUSDT", // 交易对 + "orderId": 28, // 系统的订单ID + "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP", // 客户自己设置的ID + "updateTime": 1507725176595, // 交易的时间戳 + "price": "0.00000000", // 订单价格 + "avgPrice": "0.0000000000000000", //平均价格 + "origQty": "10.00000000", // 用户设置的原始订单数量 + "cumQty": "0", //累计数量 + "executedQty": "10.00000000", // 交易的订单数量 + "cumQuote": "10.00000000", // 累计交易的金额 + "status": "CANCELED", // 订单状态 + "timeInForce": "GTC", // 订单的时效方式 + "stopPrice": "0", //触发价格 + "origType": "LIMIT", //触发前订单类型 + "type": "LIMIT", // 订单类型, 比如市价单,现价单等 + "side": "SELL", // 订单方向,买还是卖 +} +``` + +`` +DELETE /api/v1/order (HMAC SHA256) +`` + +取消有效订单。 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +orderId | LONG | NO | +origClientOrderId | STRING | NO | +recvWindow | LONG | NO | +timestamp | LONG | YES | + +`orderId` 或 `origClientOrderId` 必须至少发送一个 + +## 查询订单 (USER_DATA) + +> **响应** +```javascript +{ + "orderId": 38,   // 系统订单号 + "symbol": "ADA25SLP25",  // 交易对 + "status": "FILLED",  // 订单状态 + "clientOrderId": "afMd4GBQyHkHpGWdiy34Li",  // 用户自定义的订单号 + "price": "20",  // 委托价格 + "avgPrice": "12.0000000000000000",  // 平均成交价 + "origQty": "10",  // 原始委托数量 + "executedQty": "10",  // 成交量 + "cumQuote": "120",  // 成交金额 + "timeInForce": "GTC",  // 有效方法 + "type": "LIMIT",  // 订单类型 + "side": "BUY",  // 买卖方向 + "stopPrice": "0",  // 触发价 + "origType": "LIMIT",  // 触发前订单类型 + "time": 1649913186270,  // 订单时间 + "updateTime": 1649913186297  // 更新时间 +} +``` + +`` +GET /api/v1/order (HMAC SHA256) +`` + +查询订单状态。 + +* 请注意,如果订单满足如下条件,不会被查询到: + * 订单的最终状态为 `CANCELED` 或者 `EXPIRED`, **并且** + * 订单没有任何的成交记录, **并且** + * 订单生成时间 + 7天 < 当前时间 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +orderId | LONG | NO | +origClientOrderId | STRING | NO | +recvWindow | LONG | NO | +timestamp | LONG | YES | + +注意: + +* 至少需要发送 `orderId` 与 `origClientOrderId`中的一个 + + +## 查询当前挂单 (USER_DATA) + +> **响应** +```javascript +{ + "orderId": 38,   // 系统订单号 + "symbol": "ADA25SLP25",  // 交易对 + "status": "NEW",  // 订单状态 + "clientOrderId": "afMd4GBQyHkHpGWdiy34Li",  // 用户自定义的订单号 + "price": "20",  // 委托价格 + "avgPrice": "12.0000000000000000",  // 平均成交价 + "origQty": "10",  // 原始委托数量 + "executedQty": "10",  // 成交量 + "cumQuote": "120",  // 成交金额 + "timeInForce": "GTC",  // 有效方法 + "type": "LIMIT",  // 订单类型 + "side": "BUY",  // 买卖方向 + "stopPrice": "0",  // 触发价 + "origType": "LIMIT",  // 触发前订单类型 + "time": 1649913186270,  // 订单时间 + "updateTime": 1649913186297  // 更新时间 +} +``` + +`` +GET /api/v1/openOrder (HMAC SHA256) +`` + +查询订单状态。 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +orderId | LONG | NO | +origClientOrderId | STRING | NO | +recvWindow | LONG | NO | +timestamp | LONG | YES | + +注意: + +* 至少需要发送 `orderId` 与 `origClientOrderId`中的一个 + + +## 当前所有挂单 (USER_DATA) + +> **响应** + +```javascript +[ + { + "orderId": 349661, // 系统订单号 + "symbol": "BNBUSDT", // 交易对 + "status": "NEW", // 订单状态 + "clientOrderId": "LzypgiMwkf3TQ8wwvLo8RA", // 用户自定义的订单号 + "price": "1.10000000", // 委托价格 + "avgPrice": "0.0000000000000000", // 平均成交价 + "origQty": "5",  // 原始委托数量 + "executedQty": "0", // 成交量 + "cumQuote": "0", // 成交金额 + "timeInForce": "GTC", // 有效方法 + "type": "LIMIT", // 订单类型 + "side": "BUY", // 买卖方向 + "stopPrice": "0", // 触发价 + "origType": "LIMIT", // 触发前订单类型 + "time": 1756252940207, // 订单时间 + "updateTime": 1756252940207, // 更新时间 + } +] +``` + +`` +GET /api/v1/openOrders (HMAC SHA256) +`` + +获取交易对的所有当前挂单, 请小心使用不带交易对参数的调用。 + +**权重:** +- 带symbol ***1*** +- 不带 ***40***   + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | NO | +recvWindow | LONG | NO | +timestamp | LONG | YES | + +* 不带symbol参数,会返回所有交易对的挂单 + + + +## 取消当前所有挂单 (USER_DATA) + +> **响应** + +```javascript +{ + "code": 200, + "msg": "The operation of cancel all open order is done." +} +``` + +`` +DEL /api/v1/allOpenOrders (HMAC SHA256) +`` + +**权重:** +- ***1*** + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +orderIdList | STRING | NO | id数组字符串 +origClientOrderIdList | STRING | NO | clientOrderId数组字符串 +recvWindow | LONG | NO | +timestamp | LONG | YES | + + +## 查询所有订单 (USER_DATA) +> **响应** +```javascript +[ + { + "orderId": 349661, // 系统订单号 + "symbol": "BNBUSDT", // 交易对 + "status": "NEW", // 订单状态 + "clientOrderId": "LzypgiMwkf3TQ8wwvLo8RA", // 用户自定义的订单号 + "price": "1.10000000", // 委托价格 + "avgPrice": "0.0000000000000000", // 平均成交价 + "origQty": "5",  // 原始委托数量 + "executedQty": "0", // 成交量 + "cumQuote": "0", // 成交金额 + "timeInForce": "GTC", // 有效方法 + "type": "LIMIT", // 订单类型 + "side": "BUY", // 买卖方向 + "stopPrice": "0", // 触发价 + "origType": "LIMIT", // 触发前订单类型 + "time": 1756252940207, // 订单时间 + "updateTime": 1756252940207, // 更新时间 + } +] +``` + +`` +GET /api/v1/allOrders (HMAC SHA256) +`` + +获取所有帐户订单; 有效,已取消或已完成。 + +* 请注意,如果订单满足如下条件,不会被查询到: + * 订单生成时间 + 7天 < 当前时间 + +**权重:** +5 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +orderId | LONG | NO | +startTime | LONG | NO | +endTime | LONG | NO | +limit | INT | NO | 默认 500; 最大 1000. +recvWindow | LONG | NO | +timestamp | LONG | YES |   + +* 查询时间范围最大不得超过7天 +* 默认查询最近7天内的数据 + + +## 期货现货互转 (TRADE) + +> **响应:** + +```javascript +{ + "tranId": 21841, //交易id + "status": "SUCCESS" //状态 +} +``` + +`` +POST /api/v1/asset/transfer (HMAC SHA256) +`` + +**权重:** +5 + +**参数:** + + +名称 | 类型 | 是否必需 | 描述 +---------------- | ------- | -------- | ---- +amount | DECIMAL | YES | 数量 +asset | STRING | YES | 资产 +clientTranId | STRING | YES | 交易id +kindType | STRING | YES | 交易类型 +recvWindow | LONG | NO | +timestamp | LONG | YES | 时间戳 + +注意: +* kindType 取值为FUTURE_SPOT(期货转现货),SPOT_FUTURE(现货转期货) + +## 转账给其他地址账户 (TRADE) + +> **响应:** + +```javascript +{ + "tranId": 21841, //交易id + "status": "SUCCESS" //状态 +} +``` + +`` +POST /api/v1/asset/sendToAddress (HMAC SHA256) +`` + +**权重:** +1 + +**参数:** + + +名称 | 类型 | 是否必需 | 描述 +---------------- | ------- | -------- | ---- +amount | DECIMAL | YES | 数量 +asset | STRING | YES | 资产 +toAddress | STRING | YES | 目标地址 +clientTranId | STRING | NO | 交易id +recvWindow | LONG | NO | +timestamp | LONG | YES | 时间戳 + +注意: +* toAddress必须存在, 且不能为发送方账户 +* toAddress为evm地址 +* clientTranId如果传入则长度最少为20 + + + +## 现货提现手续费 (USER_DATA) +> **响应** +```javascript +{ + "tokenPrice": 1.00019000, + "gasCost": 0.5000, + "gasUsdValue": 0.5 +} +``` + +`` +GET /api/v1/aster/withdraw/estimateFee (HMAC SHA256) +`` + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +chainId | STRING | YES | +asset | STRING | YES | + +注意: +* chainId: 1(ETH),56(BSC),42161(Arbi) +* gasCost: 提现所需的最少数量的手续费 + +## 现货提现 (USER_DATA) +> **响应** +```javascript +{ + "withdrawId": "1014729574755487744", + "hash":"0xa6d1e617a3f69211df276fdd8097ac8f12b6ad9c7a49ba75bbb24f002df0ebb" +} +``` + +`` +POST /api/v1/aster/user-withdraw (HMAC SHA256) +`` + +**权重:** +5 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +chainId | STRING | YES | +asset | STRING | YES | +amount | STRING | YES | +fee | STRING | YES | +receiver | STRING | YES | +nonce | STRING | YES | 当前时间的微秒值 +userSignature | STRING | YES | +recvWindow | LONG | NO | +timestamp | LONG | YES | + +注意: +* chainId: 1(ETH),56(BSC),42161(Arbi) +* receiver : 当前账户的地址 +* 如果期货余额不足,会从spot账户划转到期货账户,进行提现 +* userSignature demo + +```shell +const domain = { + name: 'Aster', + version: '1', + chainId: 56, + verifyingContract: ethers.ZeroAddress, + } + +const currentTime = Date.now() * 1000 + +const types = { + Action: [ + {name: "type", type: "string"}, + {name: "destination", type: "address"}, + {name: "destination Chain", type: "string"}, + {name: "token", type: "string"}, + {name: "amount", type: "string"}, + {name: "fee", type: "string"}, + {name: "nonce", type: "uint256"}, + {name: "aster chain", type: "string"}, + ], + } + const value = { + 'type': 'Withdraw', + 'destination': '0xD9cA6952F1b1349d27f91E4fa6FB8ef67b89F02d', + 'destination Chain': 'BSC', + 'token': 'USDT', + 'amount': '10.123400', + 'fee': '1.234567891', + 'nonce': currentTime, + 'aster chain': 'Mainnet', + } + + +const signature = await signer.signTypedData(domain, types, value) +``` + +## 获取创建apikey nonce (NONE) +> **响应** +```javascript + +111111 + +``` + +`` +POST /api/v1/getNonce +`` + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +address | STRING | YES | +userOperationType | STRING | YES | CREATE_API_KEY +network | STRING | NO | + +注意: +* userOperationType 仅可取值: CREATE_API_KEY +* network: sol网络必须传入SOL,其他忽略 + + +## 创建apikey (NONE) +> **响应** +```javascript +{ + "apiKey": "bb3b24d0a3dec88cb06be58a257e4575cb0b1bb256ad6fd90ae8fd0ee1d102ae", + "apiSecret": "9fe8f5642ae1961674ea0cb7f957fa99dc8e0421b607c985a963ad2ced90ae1c" +} +``` + +`` +POST /api/v1/createApiKey +`` + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +address | STRING | YES | +userOperationType | STRING | YES | CREATE_API_KEY +network | STRING | NO | +userSignature | STRING | YES | +apikeyIP | STRING | NO | +desc | STRING | YES | +recvWindow | LONG | NO | +timestamp | LONG | YES | + +注意: +* userOperationType 仅可取值: CREATE_API_KEY +* network: sol网络必须传入SOL,其他忽略 +* desc: 同一账户不能重复,长度不能超过20个字符 +* apikeyIP ip数组以,分隔 +* 限流单IP一分钟60次 +* userSignature evm demo + +```shell + +const nonce = 111111 +const message = 'You are signing into Astherus ${nonce}' ; + +const signature = await signer.signMessage(message); +``` + + +## 账户信息 (USER_DATA) +> **响应** +```javascript +{ + "feeTier": 0, + "canTrade": true, + "canDeposit": true, + "canWithdraw": true, + "canBurnAsset": true, + "updateTime": 0, +   "balances": [ + { + "asset": "BTC", + "free": "4723846.89208129", + "locked": "0.00000000" + }, + { + "asset": "LTC", + "free": "4763368.68006011", + "locked": "0.00000000" + } + ] +} +``` + +`` +GET /api/v1/account (HMAC SHA256) +`` + +获取当前账户信息。 + +**权重:** +5 + +**参数:** + +名称 | 类型 | 是否必需| 描述 +------------ | ------------ | ------------ | ------------ +recvWindow | LONG | NO | +timestamp | LONG | YES | + + +## 账户成交历史 (USER_DATA) +> **响应** +```javascript +[ + { + "symbol": "BNBUSDT", + "id": 1002, + "orderId": 266358, + "side": "BUY", + "price": "1", + "qty": "2", + "quoteQty": "2", + "commission": "0.00105000", + "commissionAsset": "BNB", + "time": 1755656788798, + "counterpartyId": 19, + "createUpdateId": null, + "maker": false, + "buyer": true + } +] +``` + +`` +GET /api/v1/userTrades (HMAC SHA256) +`` + +获取账户指定交易对的成交历史 + +**权重:** +5 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | NO | +orderId|LONG|NO| 必须要和参数`symbol`一起使用. +startTime | LONG | NO | +endTime | LONG | NO | +fromId | LONG | NO | 起始Trade id。 默认获取最新交易。 +limit | INT | NO | 默认 500; 最大 1000. +recvWindow | LONG | NO | +timestamp | LONG | YES | + +* 如果`startTime` 和 `endTime` 均未发送, 只会返回最近7天的数据。 +* startTime 和 endTime 的最大间隔为7天 +* 不能同时传`fromId`与`startTime` 或 `endTime` +       + + + + +--- +# Websocket 行情推送 + +* 本篇所列出的所有wss接口的baseurl为: **wss://sstream.asterdex.com** +* Streams有单一原始 stream 或组合 stream +* 单一原始 streams 格式为 **/ws/\** +* 组合streams的URL格式为 **/stream?streams=\/\/\** +* 订阅组合streams时,事件payload会以这样的格式封装: **{"stream":"\","data":\}** +* stream名称中所有交易对均为 **小写** +* 每个到 **sstream.asterdex.com** 的链接有效期不超过24小时,请妥善处理断线重连。 +* 每3分钟,服务端会发送ping帧,客户端应当在10分钟内回复pong帧,否则服务端会主动断开链接。允许客户端发送不成对的pong帧(即客户端可以以高于10分钟每次的频率发送pong帧保持链接)。 + +## 实时订阅/取消数据流 + +* 以下数据可以通过websocket发送以实现订阅或取消订阅数据流。示例如下。 +* 响应内容中的`id`是无符号整数,作为往来信息的唯一标识。 +* 如果相应内容中的 `result` 为 `null`,表示请求发送成功。 + + +### 订阅一个信息流 +> **响应** + ```javascript + { + "result": null, + "id": 1 + } + ``` +* **请求** + { + "method": "SUBSCRIBE", + "params": + [ + "btcusdt@aggTrade", + "btcusdt@depth" + ], + "id": 1 + } + + +### 取消订阅一个信息流 + +> **响应** + + ```javascript + { + "result": null, + "id": 312 + } + ``` + +* **请求** + { + "method": "UNSUBSCRIBE", + "params": + [ + "btcusdt@depth" + ], + "id": 312 + } + + +### 已订阅信息流 + +> **响应** + + ```javascript + { + "result": [ + "btcusdt@aggTrade" + ], + "id": 3 + } + ``` + +* **请求** + + { + "method": "LIST_SUBSCRIPTIONS", + "id": 3 + } + + +### 设定属性 +当前,唯一可以设置的属性是设置是否启用`combined`("组合")信息流。 +当使用`/ws/`("原始信息流")进行连接时,combined属性设置为`false`,而使用 `/stream/`进行连接时则将属性设置为`true`。 + +> **响应** + + ```javascript +{ + "result": null, + "id": 5 +} + ``` + +* **请求** + { + "method": "SET_PROPERTY", + "params": + [ + "combined", + true + ], + "id": 5 + } + + +### 检索属性 + +> **响应** + ```javascript + { + "result": true, // Indicates that combined is set to true. + "id": 2 + } + ``` + +* **请求** + + { + "method": "GET_PROPERTY", + "params": + [ + "combined" + ], + "id": 2 + } + + +###错误信息 + +错误信息 | 描述 +---|--- +{"code": 0, "msg": "Unknown property"} | `SET_PROPERTY` 或 `GET_PROPERTY`中应用的参数无效 +{"code": 1, "msg": "Invalid value type: expected Boolean", "id": '%s'} | 仅接受`true`或`false` +{"code": 2, "msg": "Invalid request: property name must be a string"}| 提供的属性名无效 +{"code": 2, "msg": "Invalid request: request ID must be an unsigned integer"}| 参数`id`未提供或`id`值是无效类型 +{"code": 2, "msg": "Invalid request: unknown variant %s, expected one of `SUBSCRIBE`, `UNSUBSCRIBE`, `LIST_SUBSCRIPTIONS`, `SET_PROPERTY`, `GET_PROPERTY` at line 1 column 28"} | 错字提醒,或提供的值不是预期类型 +{"code": 2, "msg": "Invalid request: too many parameters"}| 数据中提供了不必要参数 +{"code": 2, "msg": "Invalid request: property name must be a string"} | 未提供属性名 +{"code": 2, "msg": "Invalid request: missing field `method` at line 1 column 73"} | 数据未提供`method` +{"code":3,"msg":"Invalid JSON: expected value at line %s column %s"} | JSON 语法有误. + + +## 归集交易流 + + +> **Payload:** +```javascript +{ + "e": "aggTrade", // 事件类型 + "E": 123456789, // 事件时间 + "s": "BNBBTC", // 交易对 + "a": 12345, // 归集交易ID + "p": "0.001", // 成交价格 + "q": "100", // 成交数量 + "f": 100, // 被归集的首个交易ID + "l": 105, // 被归集的末次交易ID + "T": 123456785, // 成交时间 + "m": true, // 买方是否是做市方。如true,则此次成交是一个主动卖出单,否则是一个主动买入单。 +} +``` + +归集交易 stream 推送交易信息,是对单一订单的集合。 + +**Stream 名称:** `@aggTrade` + +**Update Speed:** 实时 + + +## 逐笔交易 + + +> **Payload:** +```javascript +{ + "e": "trade", // 事件类型 + "E": 123456789, // 事件时间 + "s": "BNBBTC", // 交易对 + "t": 12345, // 交易ID + "p": "0.001", // 成交价格 + "q": "100", // 成交数量 + "T": 123456785, // 成交时间 + "m": true, // 买方是否是做市方。如true,则此次成交是一个主动卖出单,否则是一个主动买入单。 +} +``` + +**Stream Name:** `@trade` + +逐笔交易推送每一笔成交的信息。**成交**,或者说交易的定义是仅有一个吃单者与一个挂单者相互交易 + + +## K线 Streams +> **Payload:** +```javascript +{ + "e": "kline", // 事件类型 + "E": 123456789, // 事件时间 + "s": "BNBBTC", // 交易对 + "k": { + "t": 123400000, // 这根K线的起始时间 + "T": 123460000, // 这根K线的结束时间 + "s": "BNBBTC", // 交易对 + "i": "1m", // K线间隔 + "f": 100, // 这根K线期间第一笔成交ID + "L": 200, // 这根K线期间末一笔成交ID + "o": "0.0010", // 这根K线期间第一笔成交价 + "c": "0.0020", // 这根K线期间末一笔成交价 + "h": "0.0025", // 这根K线期间最高成交价 + "l": "0.0015", // 这根K线期间最低成交价 + "v": "1000", // 这根K线期间成交量 + "n": 100, // 这根K线期间成交笔数 + "x": false, // 这根K线是否完结(是否已经开始下一根K线) + "q": "1.0000", // 这根K线期间成交额 + "V": "500", // 主动买入的成交量 + "Q": "0.500", // 主动买入的成交额 + "B": "123456" // 忽略此参数 + } +} +``` + +K线stream逐秒推送所请求的K线种类(最新一根K线)的更新。 + +**Stream Name:** `@kline_` + +**Update Speed:** 2000ms + +**K线图间隔参数:** + +m -> 分钟; h -> 小时; d -> 天; w -> 周; M -> 月 + +* 1m +* 3m +* 5m +* 15m +* 30m +* 1h +* 2h +* 4h +* 6h +* 8h +* 12h +* 1d +* 3d +* 1w +* 1M + + +## 按 Symbol 的精简Ticker + +> **Payload:** +```javascript + { + "e": "24hrMiniTicker", // 事件类型 + "E": 123456789, // 事件时间 + "s": "BNBBTC", // 交易对 + "c": "0.0025", // 最新成交价格 + "o": "0.0010", // 24小时前开始第一笔成交价格 + "h": "0.0025", // 24小时内最高成交价 + "l": "0.0010", // 24小时内最低成交价 + "v": "10000", // 成交量 + "q": "18" // 成交额 + } +``` + +按Symbol刷新的最近24小时精简ticker信息 + +**Stream 名称:** `@miniTicker` + +**Update Speed:** 1000ms + + +## 全市场所有Symbol的精简Ticker + +> **Payload:** +```javascript +[ + { + // 数组每一个元素对应一个交易对,内容与 \@miniTicker相同 + } +] +``` + +同上,只是推送所有交易对.需要注意的是,只有更新的ticker才会被推送. + +**Stream名称:** !miniTicker@arr + +**Update Speed:** 1000ms + +## 按Symbol的完整Ticker + +> **Payload:** +```javascript +{ + "e": "24hrTicker", // 事件类型 + "E": 123456789, // 事件时间 + "s": "BNBBTC", // 交易对 + "p": "0.0015", // 24小时价格变化 + "P": "250.00", // 24小时价格变化(百分比) + "w": "0.0018", // 平均价格 + "c": "0.0025", // 最新成交价格 + "Q": "10", // 最新成交交易的成交量 + "o": "0.0010", // 整整24小时前,向后数的第一次成交价格 + "h": "0.0025", // 24小时内最高成交价 + "l": "0.0010", // 24小时内最低成交价 + "v": "10000", // 24小时内成交量 + "q": "18", // 24小时内成交额 + "O": 0, // 统计开始时间 + "C": 86400000, // 统计结束时间 + "F": 0, // 24小时内第一笔成交交易ID + "L": 18150, // 24小时内最后一笔成交交易ID + "n": 18151 // 24小时内成交数 +} +``` + +每秒推送单个交易对的过去24小时滚动窗口标签统计信息。 + +**Stream 名称:** `@ticker` + +**Update Speed:** 1000ms + +## 全市场所有交易对的完整Ticker + +> **Payload:** +```javascript +[ + { + // Same as @ticker payload + } +] +``` + +推送全市场所有交易对刷新的24小时完整ticker信息。需要注意的是,没有更新的ticker不会被推送。 + +**Stream Name:** `!ticker@arr` + +**Update Speed:** 1000ms + + +## 按Symbol的最优挂单信息 + +> **Payload:** +```javascript +{ + "u":400900217, // order book updateId + "s":"BNBUSDT", // 交易对 + "b":"25.35190000", // 买单最优挂单价格 + "B":"31.21000000", // 买单最优挂单数量 + "a":"25.36520000", // 卖单最优挂单价格 + "A":"40.66000000" // 卖单最优挂单数量 +} +``` + +实时推送指定交易对最优挂单信息 + +**Stream Name:** `@bookTicker` + +**Update Speed:** 实时 + +## 全市场最优挂单信息 +> **Payload:** +```javascript +{ + // 同 @bookTicker payload +} +``` + +实时推送所有交易对最优挂单信息 + +**Stream Name:** `!bookTicker` + +**Update Speed:** 实时 + + +## 有限档深度信息 + +> **Payload:** +```javascript +{ + "e": "depthUpdate", // Event type + "E": 123456789, // Event time + "T": 123456788, // Transaction time + "s": "BTCUSDT", // Symbol + "U": 100, // First update ID in event + "u": 120, // Final update ID in event + "pu": 99, // Final update Id in last stream(ie `u` in last stream) +  "bids": [ // Bids to be updated + [ + "0.0024", // Price level to be updated + "10" // Quantity + ] + ], + "asks": [ // Asks to be updated + [ + "0.0026", // Price level to be updated + "100" // Quantity + ] + ] +} +``` + +每秒或每100毫秒推送有限档深度信息。levels表示几档买卖单信息, 可选 5/10/20档 + +**Stream Names:** `@depth` 或 `@depth@100ms`. + +**Update Speed:** 1000ms 或 100ms + + +## 增量深度信息 +> **Payload:** +```javascript +{ + "e": "depthUpdate", // Event type + "E": 123456789, // Event time + "T": 123456788, // Transaction time + "s": "BTCUSDT", // Symbol + "U": 100, // First update ID in event + "u": 120, // Final update ID in event + "pu": 99, // Final update Id in last stream(ie `u` in last stream) + "b": [ // Bids to be updated + [ + "5.4", // Price level to be updated + "10" // Quantity + ] + ], + "a": [ // Asks to be updated + [ + "5.6", // Price level to be updated + "100" // Quantity + ] + ] +} +``` + +每秒或每100毫秒推送orderbook的变化部分(如果有) + +**Stream Name:** `@depth` 或 `@depth@100ms` + +**Update Speed:** 1000ms 或 100ms + +## 如何正确在本地维护一个orderbook副本 +1. 订阅 **wss://sstream.asterdex.com/ws/bnbbtc@depth** +2. 开始缓存收到的更新。同一个价位,后收到的更新覆盖前面的。 +3. 访问Rest接口 **https://sapi.asterdex.com/api/v1/depth?symbol=BNBBTC&limit=1000** 获得一个1000档的深度快照 +4. 将目前缓存到的信息中`u` <= 步骤3中获取到的快照中的`lastUpdateId`的部分丢弃(丢弃更早的信息,已经过期)。 +5. 将深度快照中的内容更新到本地orderbook副本中,并从websocket接收到的第一个`U` <= `lastUpdateId`+1 **且** `u` >= `lastUpdateId`+1 的event开始继续更新本地副本。 +6. 每一个新event的`U`应该恰好等于上一个event的`u`+1,否则可能出现了丢包,请从step3重新进行初始化。 +7. 每一个event中的挂单量代表这个价格目前的挂单量**绝对值**,而不是相对变化。 +8. 如果某个价格对应的挂单量为0,表示该价位的挂单已经撤单或者被吃,应该移除这个价位。 + + + + + + +# Websocket账户信息推送 + +* 本篇所列出API接口的base url : **https://sapi.asterdex.com** +* 用于订阅账户数据的 `listenKey` 从创建时刻起有效期为60分钟 +* 可以通过 `PUT` 一个 `listenKey` 延长60分钟有效期 +* 可以通过`DELETE`一个 `listenKey` 立即关闭当前数据流,并使该`listenKey` 无效 +* 在具有有效`listenKey`的帐户上执行`POST`将返回当前有效的`listenKey`并将其有效期延长60分钟 +* websocket接口的baseurl: **wss://sstream.asterdex.com** +* U订阅账户数据流的stream名称为 **/ws/\** +* 每个链接有效期不超过24小时,请妥善处理断线重连。 + + +## Listen Key(现货账户) + +### 生成 Listen Key (USER_STREAM) + +> **响应** +```javascript +{ + "listenKey": "pqia91ma19a5s61cv6a81va65sdf19v8a65a1a5s61cv6a81va65sdf19v8a65a1" +} +``` + +`` +POST /api/v1/listenKey +`` + +开始一个新的数据流。除非发送 keepalive,否则数据流于60分钟后关闭。如果该帐户具有有效的`listenKey`,则将返回该`listenKey`并将其有效期延长60分钟。 + +**权重:** +1 + +**参数:** +NONE + +### 延长 Listen Key 有效期 (USER_STREAM) + +> **响应** +```javascript +{} +``` + +`` +PUT /api/v1/listenKey +`` + +有效期延长至本次调用后60分钟,建议每30分钟发送一个 ping 。 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +listenKey | STRING | YES + + +### 关闭 Listen Key (USER_STREAM) + +> **响应** +```javascript +{} +``` + +`` +DELETE /api/v1/listenKey +`` + +关闭用户数据流。 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +listenKey | STRING | YES + + +## Payload: 账户更新 + +每当帐户余额发生更改时,都会发送一个事件`outboundAccountPosition`,其中包含可能由生成余额变动的事件而变动的资产。 + +> **Payload** +```javascript +{ + "B":[// 余额 + { + "a":"SLP25",   // 资产名称 + "f":"10282.42029415",   // 可用余额 + "l":"653.00000001"   // 冻结余额 + }, + { + "a":"ADA25", + "f":"9916.96229880", + "l":"34.00510000" + } + ], + "e":"outboundAccountPosition",   // 事件类型 + "T":1649926447190,   // 账户末次更新时间戳 + "E":1649926447205   // 事件时间 + "m":"WITHDRAW" // 事件推出原因 +} +``` + + +## Payload: 订单更新 + +订单通过`executionReport`事件进行更新。 + +> **Payload** + +```javascript +{ + "s":"ADA25SLP25",   // 交易对 + "c":"Xzh0gnxT41PStbwqOtXnjD",  // 客户端自定订单ID + "S":"SELL",   // 订单方向 + "o":"LIMIT",   // 订单类型 + "f":"GTC",   // 有效方式 + "q":"10.001000",   // 订单原始数量 + "p":"19.1000000000",   // 订单原始价格 + "ap":"19.0999999955550656", //平均价格 + "P":"0",  // 条件订单触发价格 + "x":"TRADE",   // 本次事件的具体执行类型 + "X":"PARTIALLY_FILLED",   // 订单的当前状态 + "i":27,   // 订单ID + "l":"1",     // 订单末次成交量 + "z":"8.999000",   // 订单累计已成交量 + "L":"19.1000000000",   // 订单末次成交价格 + "n":"0.00382000",   // 手续费数量 + "N":"SLP25",   // 手续费资产类型 + "T":1649926447190,   // 成交时间 + "t":18,   // 成交ID + "m":true,   // 该成交是作为挂单成交吗? + "ot":"LIMIT", //初始订单类型 + "O":0,   // 订单时间 + "Z":"171.88089996",   // 累计报价资产交易数量 + "Y":"19.1000000000000000",   // 最近报价交易数量 + "Q":"0",   // 报价数量 + "e":"executionReport",   // 事件类型 + "E":1649926447209  // 事件时间 +} +``` + + +**执行类型:** +* NEW 新订单 +* CANCELED 订单被取消 +* REJECTED 新订单被拒绝 +* TRADE 订单有新成交 +* EXPIRED 订单失效(根据订单的Time In Force参数) + + + + + + +#错误代码 + +> error JSON payload: + +```javascript +{ + "code":-1121, + "msg":"Invalid symbol." +} +``` + +错误由两部分组成:错误代码和消息。 代码是通用的,但是消息可能会有所不同。 + + +## 10xx - 常规服务器或网络问题 +### -1000 UNKNOWN + * An unknown error occured while processing the request. + * 处理请求时发生未知错误。 + +### -1001 DISCONNECTED + * Internal error; unable to process your request. Please try again. + * 内部错误; 无法处理您的请求。 请再试一次. + +### -1002 UNAUTHORIZED + * You are not authorized to execute this request. + * 您无权执行此请求。 + +### -1003 TOO_MANY_REQUESTS + * Too many requests queued. + * 排队的请求过多。 + * Too many requests; please use the websocket for live updates. + * 请求权重过多; 请使用websocket获取最新更新。 + * Too many requests; current limit is %s requests per minute. Please use the websocket for live updates to avoid polling the API. + * 请求权重过多; 当前限制为每分钟%s请求权重。 请使用websocket进行实时更新,以避免轮询API。 + * Way too many requests; IP banned until %s. Please use the websocket for live updates to avoid bans. + * 请求权重过多; IP被禁止,直到%s。 请使用websocket进行实时更新,以免被禁。 + +### -1004 DUPLICATE_IP + * This IP is already on the white list + * IP地址已经在白名单 + +### -1005 NO_SUCH_IP + * No such IP has been white listed + * 白名单上没有此IP地址 + +### -1006 UNEXPECTED_RESP + * An unexpected response was received from the message bus. Execution status unknown. + * 从消息总线收到意外的响应。执行状态未知。 + +### -1007 TIMEOUT + * Timeout waiting for response from backend server. Send status unknown; execution status unknown. + * 等待后端服务器响应超时。 发送状态未知; 执行状态未知。 + +### -1014 UNKNOWN_ORDER_COMPOSITION + * Unsupported order combination. + * 不支持当前的下单参数组合 + +### -1015 TOO_MANY_ORDERS + * Too many new orders. + * 新订单太多。 + * Too many new orders; current limit is %s orders per %s. + * 新订单太多; 当前限制为每%s %s个订单。 + +### -1016 SERVICE_SHUTTING_DOWN + * This service is no longer available. + * 该服务不可用。 + +### -1020 UNSUPPORTED_OPERATION + * This operation is not supported. + * 不支持此操作。 + +### -1021 INVALID_TIMESTAMP + * Timestamp for this request is outside of the recvWindow. + * 此请求的时间戳在recvWindow之外。 + * Timestamp for this request was 1000ms ahead of the server's time. + * 此请求的时间戳比服务器时间提前1000毫秒。 + +### -1022 INVALID_SIGNATURE + * Signature for this request is not valid. + * 此请求的签名无效。 + +### -1023 START_TIME_GREATER_THAN_END_TIME + * Start time is greater than end time. + * 参数里面的开始时间在结束时间之后 + + +## 11xx - Request issues +### -1100 ILLEGAL_CHARS + * Illegal characters found in a parameter. + * 在参数中发现非法字符。 + * Illegal characters found in parameter '%s'; legal range is '%s'. + * 在参数`%s`中发现非法字符; 合法范围是`%s`。 + +### -1101 TOO_MANY_PARAMETERS + * Too many parameters sent for this endpoint. + * 为此端点发送的参数太多。 + * Too many parameters; expected '%s' and received '%s'. + * 参数太多;预期为`%s`并收到了`%s`。 + * Duplicate values for a parameter detected. + * 检测到的参数值重复。 + +### -1102 MANDATORY_PARAM_EMPTY_OR_MALFORMED + * A mandatory parameter was not sent, was empty/null, or malformed. + * 未发送强制性参数,该参数为空/空或格式错误。 + * Mandatory parameter '%s' was not sent, was empty/null, or malformed. + * 强制参数`%s`未发送,为空/空或格式错误。 + * Param '%s' or '%s' must be sent, but both were empty/null! + * 必须发送参数`%s`或`%s`,但两者均为空! + +### -1103 UNKNOWN_PARAM + * An unknown parameter was sent. + * 发送了未知参数。 + +### -1104 UNREAD_PARAMETERS + * Not all sent parameters were read. + * 并非所有发送的参数都被读取。 + * Not all sent parameters were read; read '%s' parameter(s) but was sent '%s'. + * 并非所有发送的参数都被读取; 读取了`%s`参数,但被发送了`%s`。 + +### -1105 PARAM_EMPTY + * A parameter was empty. + * 参数为空。 + * Parameter '%s' was empty. + * 参数`%s`为空。 + +### -1106 PARAM_NOT_REQUIRED + * A parameter was sent when not required. + * 发送了不需要的参数。 + * Parameter '%s' sent when not required. + * 发送了不需要参数`%s`。 + +### -1111 BAD_PRECISION + * Precision is over the maximum defined for this asset. + * 精度超过为此资产定义的最大值。 + +### -1112 NO_DEPTH + * No orders on book for symbol. + * 交易对没有挂单。 + +### -1114 TIF_NOT_REQUIRED + * TimeInForce parameter sent when not required. + * 发送的`TimeInForce`参数不需要。 + +### -1115 INVALID_TIF + * Invalid timeInForce. + * 无效的`timeInForce` + +### -1116 INVALID_ORDER_TYPE + * Invalid orderType. + * 无效订单类型。 + +### -1117 INVALID_SIDE + * Invalid side. + * 无效买卖方向。 + +### -1118 EMPTY_NEW_CL_ORD_ID + * New client order ID was empty. + * 新的客户订单ID为空。 + +### -1119 EMPTY_ORG_CL_ORD_ID + * Original client order ID was empty. + * 客户自定义的订单ID为空。 + +### -1120 BAD_INTERVAL + * Invalid interval. + * 无效时间间隔。 + +### -1121 BAD_SYMBOL + * Invalid symbol. + * 无效的交易对。 + +### -1125 INVALID_LISTEN_KEY + * This listenKey does not exist. + * 此`listenKey`不存在。 + +### -1127 MORE_THAN_XX_HOURS + * Lookup interval is too big. + * 查询间隔太大。 + * More than %s hours between startTime and endTime. + * 从开始时间到结束时间之间超过`%s`小时。 + +### -1128 OPTIONAL_PARAMS_BAD_COMBO + * Combination of optional parameters invalid. + * 可选参数组合无效。 + +### -1130 INVALID_PARAMETER + * Invalid data sent for a parameter. + * 发送的参数为无效数据。 + * Data sent for parameter '%s' is not valid. + * 发送参数`%s`的数据无效。 + +### -1136 INVALID_NEW_ORDER_RESP_TYPE + * Invalid newOrderRespType. + * 无效的 newOrderRespType。 + + +## 20xx - Processing Issues +### -2010 NEW_ORDER_REJECTED + * NEW_ORDER_REJECTED + * 新订单被拒绝 + +### -2011 CANCEL_REJECTED + * CANCEL_REJECTED + * 取消订单被拒绝 + +### -2013 NO_SUCH_ORDER + * Order does not exist. + * 订单不存在。 + +### -2014 BAD_API_KEY_FMT + * API-key format invalid. + * API-key 格式无效。 + +### -2015 REJECTED_MBX_KEY + * Invalid API-key, IP, or permissions for action. + * 无效的API密钥,IP或操作权限。 + +### -2016 NO_TRADING_WINDOW + * No trading window could be found for the symbol. Try ticker/24hrs instead. + * 找不到该交易对的交易窗口。 尝试改为24小时自动报价。 + +### -2018 BALANCE_NOT_SUFFICIENT + * Balance is insufficient. + * 余额不足 + +### -2020 UNABLE_TO_FILL + * Unable to fill. + * 无法成交 + +### -2021 ORDER_WOULD_IMMEDIATELY_TRIGGER + * Order would immediately trigger. + * 订单可能被立刻触发 + +### -2022 REDUCE_ONLY_REJECT + * ReduceOnly Order is rejected. + * `ReduceOnly`订单被拒绝 + +### -2024 POSITION_NOT_SUFFICIENT + * Position is not sufficient. + * 持仓不足 + +### -2025 MAX_OPEN_ORDER_EXCEEDED + * Reach max open order limit. + * 挂单量达到上限 + +### -2026 REDUCE_ONLY_ORDER_TYPE_NOT_SUPPORTED + * This OrderType is not supported when reduceOnly. + * 当前订单类型不支持`reduceOnly` + +## 40xx - Filters and other Issues +### -4000 INVALID_ORDER_STATUS + * Invalid order status. + * 订单状态不正确 + +### -4001 PRICE_LESS_THAN_ZERO + * Price less than 0. + * 价格小于0 + +### -4002 PRICE_GREATER_THAN_MAX_PRICE + * Price greater than max price. + * 价格超过最大值 + +### -4003 QTY_LESS_THAN_ZERO + * Quantity less than zero. + * 数量小于0 + +### -4004 QTY_LESS_THAN_MIN_QTY + * Quantity less than min quantity. + * 数量小于最小值 + +### -4005 QTY_GREATER_THAN_MAX_QTY + * Quantity greater than max quantity. + * 数量大于最大值 + +### -4006 STOP_PRICE_LESS_THAN_ZERO + * Stop price less than zero. + * 触发价小于最小值 + +### -4007 STOP_PRICE_GREATER_THAN_MAX_PRICE + * Stop price greater than max price. + * 触发价大于最大值 + +### -4008 TICK_SIZE_LESS_THAN_ZERO + * Tick size less than zero. + * 价格精度小于0 + +### -4009 MAX_PRICE_LESS_THAN_MIN_PRICE + * Max price less than min price. + * 最大价格小于最小价格 + +### -4010 MAX_QTY_LESS_THAN_MIN_QTY + * Max qty less than min qty. + * 最大数量小于最小数量 + +### -4011 STEP_SIZE_LESS_THAN_ZERO + * Step size less than zero. + * 步进值小于0 + +### -4012 MAX_NUM_ORDERS_LESS_THAN_ZERO + * Max num orders less than zero. + * 最大订单量小于0 + +### -4013 PRICE_LESS_THAN_MIN_PRICE + * Price less than min price. + * 价格小于最小价格 + +### -4014 PRICE_NOT_INCREASED_BY_TICK_SIZE + * Price not increased by tick size. + * 价格增量不是价格精度的倍数。 + +### -4015 INVALID_CL_ORD_ID_LEN + * Client order id is not valid. + * 客户订单ID有误。 + * Client order id length should not be more than 36 chars + * 客户订单ID长度应该不多于36字符 + +### -4016 PRICE_HIGHTER_THAN_MULTIPLIER_UP + * Price is higher than mark price multiplier cap. + +### -4017 MULTIPLIER_UP_LESS_THAN_ZERO + * Multiplier up less than zero. + * 价格上限小于0 + +### -4018 MULTIPLIER_DOWN_LESS_THAN_ZERO + * Multiplier down less than zero. + * 价格下限小于0 + +### -4019 COMPOSITE_SCALE_OVERFLOW + * Composite scale too large. + +### -4020 TARGET_STRATEGY_INVALID + * Target strategy invalid for orderType '%s',reduceOnly '%b'. + * 目标策略值不适合`%s`订单状态, 只减仓`%b`。 + +### -4021 INVALID_DEPTH_LIMIT + * Invalid depth limit. + * 深度信息的`limit`值不正确。 + * '%s' is not valid depth limit. + * `%s`不是合理的深度信息的`limit`值。 + +### -4022 WRONG_MARKET_STATUS + * market status sent is not valid. + * 发送的市场状态不正确。 + +### -4023 QTY_NOT_INCREASED_BY_STEP_SIZE + * Qty not increased by step size. + * 数量的递增值不是步进值的倍数。 + +### -4024 PRICE_LOWER_THAN_MULTIPLIER_DOWN + * Price is lower than mark price multiplier floor. + +### -4025 MULTIPLIER_DECIMAL_LESS_THAN_ZERO + * Multiplier decimal less than zero. + +### -4026 COMMISSION_INVALID + * Commission invalid. + * 收益值不正确 + * `%s` less than zero. + * `%s`少于0 + * `%s` absolute value greater than `%s` + * `%s`绝对值大于`%s` + +### -4027 INVALID_ACCOUNT_TYPE + * Invalid account type. + * 账户类型不正确。 + +### -4029 INVALID_TICK_SIZE_PRECISION + * Tick size precision is invalid. + * 价格精度小数点位数不正确。 + +### -4030 INVALID_STEP_SIZE_PRECISION + * Step size precision is invalid. + * 步进值小数点位数不正确。 + +### -4031 INVALID_WORKING_TYPE + * Invalid parameter working type + * 不正确的参数类型 + * Invalid parameter working type: `%s` + * 不正确的参数类型: `%s` + +### -4032 EXCEED_MAX_CANCEL_ORDER_SIZE + * Exceed maximum cancel order size. + * 超过可以取消的最大订单量。 + * Invalid parameter working type: `%s` + * 不正确的参数类型: `%s` + +### -4044 INVALID_BALANCE_TYPE + * Balance Type is invalid. + * 余额类型不正确。 + +### -4045 MAX_STOP_ORDER_EXCEEDED + * Reach max stop order limit. + * 达到止损单的上限。 + +### -4055 AMOUNT_MUST_BE_POSITIVE + * Amount must be positive. + * 数量必须是正整数 + +### -4056 INVALID_API_KEY_TYPE + * Invalid api key type. + * API key的类型不正确 + +### -4057 INVALID_RSA_PUBLIC_KEY + * Invalid api public key + * API key不正确 + +### -4058 MAX_PRICE_TOO_LARGE + * maxPrice and priceDecimal too large,please check. + * maxPrice和priceDecimal太大,请检查。 + +### -4060 INVALID_POSITION_SIDE + * Invalid position side. + * 仓位方向不正确。 + +### -4061 POSITION_SIDE_NOT_MATCH + * Order's position side does not match user's setting. + * 订单的持仓方向和用户设置不一致。 + +### -4062 REDUCE_ONLY_CONFLICT + * Invalid or improper reduceOnly value. + * 仅减仓的设置不正确。 + +### -4084 UPCOMING_METHOD + * Method is not allowed currently. Upcoming soon. + * 方法不支持 + +### -4086 INVALID_PRICE_SPREAD_THRESHOLD + * Invalid price spread threshold + * 无效的价差阀值 + +### -4087 REDUCE_ONLY_ORDER_PERMISSION + * User can only place reduce only order + * 用户只能下仅减仓订单 + +### -4088 NO_PLACE_ORDER_PERMISSION + * User can not place order currently + * 用户当前不能下单 + +### -4114 INVALID_CLIENT_TRAN_ID_LEN + * clientTranId is not valid + * clientTranId不正确 + * Client tran id length should be less than 64 chars + * 客户的tranId长度应该小于64个字符 + +### -4115 DUPLICATED_CLIENT_TRAN_ID + * clientTranId is duplicated + * clientTranId重复 + * Client tran id should be unique within 7 days + * 客户的tranId应在7天内唯一 + +### -4118 REDUCE_ONLY_MARGIN_CHECK_FAILED + * ReduceOnly Order Failed. Please check your existing position and open orders + * 仅减仓订单失败。请检查现有的持仓和挂单 + +### -4131 MARKET_ORDER_REJECT + * The counterparty's best price does not meet the PERCENT_PRICE filter limit + * 交易对手的最高价格未达到PERCENT_PRICE过滤器限制 + +### -4135 INVALID_ACTIVATION_PRICE + * Invalid activation price + * 无效的激活价格 + +### -4137 QUANTITY_EXISTS_WITH_CLOSE_POSITION + * Quantity must be zero with closePosition equals true + * 数量必须为0,当closePosition为true时 + +### -4138 REDUCE_ONLY_MUST_BE_TRUE + * Reduce only must be true with closePosition equals true + * Reduce only 必须为true,当closePosition为true时 + +### -4139 ORDER_TYPE_CANNOT_BE_MKT + * Order type can not be market if it's unable to cancel + * 订单类型不能为市价单如果不能取消 + +### -4140 INVALID_OPENING_POSITION_STATUS + * Invalid symbol status for opening position + * 无效的交易对状态 + +### -4141 SYMBOL_ALREADY_CLOSED + * Symbol is closed + * 交易对已下架 + +### -4142 STRATEGY_INVALID_TRIGGER_PRICE + * REJECT: take profit or stop order will be triggered immediately + * 拒绝:止盈止损单将立即被触发 + +### -4164 MIN_NOTIONAL + * Order's notional must be no smaller than 5.0 (unless you choose reduce only) + * 订单的名义价值不可以小于5,除了使用reduce only + * Order's notional must be no smaller than %s (unless you choose reduce only) + * 订单的名义价值不可以小于`%s`,除了使用reduce only + +### -4165 INVALID_TIME_INTERVAL + * Invalid time interval + * 无效的间隔 + * Maximum time interval is %s days + * 最大的时间间隔为 `%s` 天 + +### -4183 PRICE_HIGHTER_THAN_STOP_MULTIPLIER_UP + * Price is higher than stop price multiplier cap. + * 止盈止损订单价格不应高于触发价与报价乘数上限的乘积 + * Limit price can't be higher than %s. + * 止盈止损订单价格不应高于 `%s` + +### -4184 PRICE_LOWER_THAN_STOP_MULTIPLIER_DOWN + * Price is lower than stop price multiplier floor. + * 止盈止损订单价格不应低于触发价与报价乘数下限的乘积 + * Limit price can't be lower than %s. + * 止盈止损订单价格不应低于 `%s`f diff --git a/aster-finance-api.md b/aster-finance-future-api.md similarity index 99% rename from aster-finance-api.md rename to aster-finance-future-api.md index d4a42b8..51c1241 100644 --- a/aster-finance-api.md +++ b/aster-finance-future-api.md @@ -72,6 +72,7 @@ - [Get Current Multi-Assets Mode (USER_DATA)](#get-current-multi-assets-mode-user_data) - [New Order (TRADE)](#new-order--trade) - [Place Multiple Orders (TRADE)](#place-multiple-orders--trade) + - [Transfer Between Futures And Spot (TRADE)](#transfer-between-futures-and-spot--trade) - [Query Order (USER_DATA)](#query-order-user_data) - [Cancel Order (TRADE)](#cancel-order-trade) - [Cancel All Open Orders (TRADE)](#cancel-all-open-orders-trade) @@ -2462,8 +2463,39 @@ newOrderRespType | ENUM | NO | "ACK", "RESULT", default "ACK" * Batch orders are processed concurrently, and the order of matching is not guaranteed. * The order of returned contents for batch orders is the same as the order of the order list. +## Transfer Between Futures And Spot (TRADE) +> **Response:** + +```javascript +{ + "tranId": 21841, //transaction id + "status": "SUCCESS" //status +} +``` + +`` +POST /fapi/v1/asset/transfer (HMAC SHA256) +`` + +**Weight:** +5 + +**Parameters:** + +Name | Type | Mandatory | Description +---------------- | ------- | -------- | ---- +amount | DECIMAL | YES | amount +asset | STRING | YES | asset +clientTranId | STRING | YES | transaction id +kindType | STRING | YES | kindType +timestamp | LONG | YES | timestamp + +Notes: +* kindType can take the following values: + FUTURE_SPOT (futures converted to spot) + SPOT_FUTURE (spot converted to futures) ## Query Order (USER_DATA) diff --git a/aster-finance-api_CN.md b/aster-finance-future-api_CN.md similarity index 99% rename from aster-finance-api_CN.md rename to aster-finance-future-api_CN.md index 95c3751..1cbb091 100644 --- a/aster-finance-api_CN.md +++ b/aster-finance-future-api_CN.md @@ -72,6 +72,7 @@ - [下单 (TRADE)](#下单-trade) - [测试下单接口 (TRADE)](#测试下单接口-trade) - [批量下单 (TRADE)](#批量下单-trade) + - [期货现货互转 (TRADE)](#期货现货互转-trade) - [查询订单 (USER_DATA)](#查询订单-user_data) - [撤销订单 (TRADE)](#撤销订单-trade) - [撤销全部订单 (TRADE)](#撤销全部订单-trade) @@ -2370,7 +2371,36 @@ newOrderRespType | ENUM | NO | "ACK", "RESULT", 默认 "ACK" * 批量下单采取并发处理,不保证订单撮合顺序 * 批量下单的返回内容顺序,与订单列表顺序一致 +## 期货现货互转 (TRADE) +> **响应:** + +```javascript +{ + "tranId": 21841, //交易id + "status": "SUCCESS" //状态 +} +``` + +`` +POST /fapi/v1/asset/transfer (HMAC SHA256) +`` + +**权重:** +5 + +**参数:** + + +名称 | 类型 | 是否必需 | 描述 +---------------- | ------- | -------- | ---- +amount | DECIMAL | YES | 数量 +asset | STRING | YES | 资产 +clientTranId | STRING | YES | 交易id +kindType | STRING | YES | 交易类型 +timestamp | LONG | YES | 时间戳 + +* kindType 取值为FUTURE_SPOT(期货转现货),SPOT_FUTURE(现货转期货) ## 查询订单 (USER_DATA) diff --git a/consolidation.js b/consolidation.js new file mode 100644 index 0000000..0d51600 --- /dev/null +++ b/consolidation.js @@ -0,0 +1,232 @@ +const ethers = require('ethers'); +const crypto = require('crypto'); +const http = require('http'); +const axios = require('axios'); +const { Wallet } = require('ethers'); + + +//待归集的账户信息 +const new_address_config = [ + { + private_key: "*", + address: '*', + 'asset': 'CDL', + 'amount': '1', + }, + { + private_key: "*", + address: '*', + 'asset': 'CDL', + 'amount': '1', + } +] + +// const host = 'http://127.0.0.1:9081' +// const host = 'https://www.astherusqa.finance' +const host = 'https://sapi.asterdex.com' + +//主账户私钥 +const main_WALLET_PRIVATE_KEY = "*"; +//主账户钱包 +const main_wallet = new ethers.Wallet(main_WALLET_PRIVATE_KEY); +//主账户的地址 apikey api_secret +const main_address = '*' +const api_key = '*' +const api_secret = '*' + +const desc = 'newApikey899221' //创建apikey时的描述信息 注意同一账户的desc不能重复 + +//归集和提现的手续费 代币 数量配置 +const fee = '0.6' +const withdraw_nonce = Date.now() + '000' +const withdraw_asset = 'CDL' +const withdraw_amount = '1' +const newrok = 'BSC' //主网使用 BSC +const chainId = 56 //主网使用 56 + + +//下面的参数无需修改 +var new_address_apikey = '' +var new_address_apiSecret = '' +var use_new_apikey = false + +const spot_get_nonce = { 'url': '/api/v1/getNonce', 'method': 'POST', 'params': { 'userOperationType': 'CREATE_API_KEY' } } +const spot_create_apikey = { 'url': '/api/v1/createApiKey', 'method': 'POST', 'params': { 'userOperationType': 'CREATE_API_KEY' } } +const spot_send_toAddress = { 'url': '/api/v1/spot/sendToAddress', 'method': 'POST', 'params': {} } + +// #chainId: 1(ETH),56(BSC),42161(Arbi) +const spot_withdraw_estimateFee = { 'url': '/api/v1/aster/withdraw/estimateFee', 'method': 'GET', 'params': { 'asset': 'BNB', "chainId": chainId } } +const spot_withdraw = { 'url': '/api/v1/aster/user-withdraw', 'method': 'POST', 'params': { "chainId": chainId } } + + +const domain = { + name: 'Aster', + version: '1', + chainId: chainId, + verifyingContract: ethers.ZeroAddress +} + +const types = { + Action: [ + { name: "type", type: "string" }, + { name: "destination", type: "address" }, + { name: "destination Chain", type: "string" }, + { name: "token", type: "string" }, + { name: "amount", type: "string" }, + { name: "fee", type: "string" }, + { name: "nonce", type: "uint256" }, + { name: "aster chain", type: "string" }, + ], +} + + +const value = { + 'type': 'Withdraw', + 'destination': main_address, + 'destination Chain': newrok, + 'token': withdraw_asset, + 'amount': withdraw_amount, + 'fee': fee, + 'nonce': withdraw_nonce, + 'aster chain': 'Mainnet', +} + +async function getUrl(my_dict) { + content = '' + for (let key in my_dict) { + content = content + key + '=' + my_dict[key] + '&' + } + content += 'recvWindow=5000×tamp=' + Date.now() + + return content + +} + +async function sign_v1(secretKey, message) { + const hmac = crypto.createHmac('sha256', secretKey) + .update(message) + .digest('hex'); + return hmac +} + +async function sendRequest(url, method) { + headers = {} + key = api_key + if (use_new_apikey == true) { + key = new_address_apikey + } + // console.log('url:', url) + if (method == 'POST') { + headers = { + 'Content-Type': 'application/x-www-form-urlencoded', + 'X-MBX-APIKEY': key, + 'User-Agent': 'Node.js HTTP Client' + } + } + try { + const response = await axios({ + method: method, // 支持 get, post, put, delete, etc. + url: url, + headers: headers + + }); + + return response.data; + } catch (error) { + console.error('Error:', error.response?.data || error.message); + } + + return '' +} + +async function send_v1(path, method, my_dict) { + content = await getUrl(my_dict) + secret = api_secret + if (use_new_apikey == true) { + secret = new_address_apiSecret + } + signature = await sign_v1(secret, content) + path = path + '?' + content + '&signature=' + signature + return await sendRequest(host + path, method) +} + + +async function generateSignature() { + try { + const signature = await main_wallet.signTypedData(domain, types, value); + return signature; + } catch (error) { + console.error("签名生成失败:", error); + throw error; + } +} + +async function send(config, addParams) { + path = config['url'] + method = config['method'] + my_dict = { ...config['params'], ...addParams } + return await send_v1(path, method, my_dict) +} + +async function sign(private_key, message) { + wallet = new ethers.Wallet(private_key); + const signature = await wallet.signMessage(message); + return signature +} + +async function main() { + //循环归集 + i = 0 + for (const config of new_address_config) { + console.log('开始归集账户:', config.address); + //获取创建apikey的nonce + let nonce = await send(spot_get_nonce, {'address': config.address}) + + //给新地址创建api_key api_secret + message = 'You are signing into Astherus ${nonce}'.replace('${nonce}', nonce) + userSignature = await sign(config.private_key,message) + + var key_desc = desc + '_' + i + i = i + 1 + let new_api = await send(spot_create_apikey, { 'userSignature': userSignature,'address': config.address,'desc': key_desc }) + new_address_apikey = new_api['apiKey'] + new_address_apiSecret = new_api['apiSecret'] + + console.log('new_address_apikey:', new_address_apikey) + console.log('new_address_apiSecret:', new_address_apiSecret) + + use_new_apikey = true + //归集 使用新生成的apikey api_secret 将新地址的CDL转账到老地址账户 + sendToMainAddressRes = await send(spot_send_toAddress, { 'asset': config.asset, "amount": config.amount, "toAddress": main_address }) + console.log('sendToMainAddressRes:', sendToMainAddressRes) + use_new_apikey = false + if(sendToMainAddressRes['status'] = 'SUCCESS'){ + console.log('归集成功:', config.address); + }else{ + console.log('归集失败:', config.address); + } + } + + + estimateFee = await send(spot_withdraw_estimateFee, {}) + console.log('estimateFee:', estimateFee) + + withdraw_ignature = await generateSignature() + + //使用老账户进行提现操作 + spotWithdraw = await send(spot_withdraw, { + 'fee': fee, 'nonce': withdraw_nonce, + 'userSignature': withdraw_ignature, 'receiver': main_address, 'asset': withdraw_asset, 'amount': withdraw_amount + }) + + if(spotWithdraw['hash'] != ''){ + console.log('提现成功:', spotWithdraw['hash']); + }else{ + console.log('提现失败:', spotWithdraw); + } + +} + + +main() + From 0ea1be2271a2886c76835b69c1e433a8807cfb08 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Tue, 2 Sep 2025 10:17:35 +0800 Subject: [PATCH 005/131] spot fix --- aster-finance-future-api.md | 2 +- aster-finance-future-api_CN.md | 2 +- ...e-spot-api.md => aster-finance-spot-api.md | 20 +++++++++---------- ...-api_CN.md => aster-finance-spot-api_CN.md | 10 +++++----- 4 files changed, 17 insertions(+), 17 deletions(-) rename apollox-finance-spot-api.md => aster-finance-spot-api.md (99%) rename apollox-finance-spot-api_CN.md => aster-finance-spot-api_CN.md (99%) diff --git a/aster-finance-future-api.md b/aster-finance-future-api.md index 51c1241..effe0f5 100644 --- a/aster-finance-future-api.md +++ b/aster-finance-future-api.md @@ -2475,7 +2475,7 @@ newOrderRespType | ENUM | NO | "ACK", "RESULT", default "ACK" ``` `` -POST /fapi/v1/asset/transfer (HMAC SHA256) +POST /fapi/v1/asset/wallet/transfer (HMAC SHA256) `` **Weight:** diff --git a/aster-finance-future-api_CN.md b/aster-finance-future-api_CN.md index 1cbb091..493888c 100644 --- a/aster-finance-future-api_CN.md +++ b/aster-finance-future-api_CN.md @@ -2383,7 +2383,7 @@ newOrderRespType | ENUM | NO | "ACK", "RESULT", 默认 "ACK" ``` `` -POST /fapi/v1/asset/transfer (HMAC SHA256) +POST /fapi/v1/asset/wallet/transfer (HMAC SHA256) `` **权重:** diff --git a/apollox-finance-spot-api.md b/aster-finance-spot-api.md similarity index 99% rename from apollox-finance-spot-api.md rename to aster-finance-spot-api.md index 635b552..921c13f 100644 --- a/apollox-finance-spot-api.md +++ b/aster-finance-spot-api.md @@ -976,8 +976,8 @@ symbol | STRING | NO | ```javascript { "symbol": "APXUSDT", - "makerCommission": "0.000200",     - "takerCommission": "0.000700" + "makerCommissionRate": "0.000200",     + "takerCommissionRate": "0.000700" } ``` @@ -1267,7 +1267,7 @@ timestamp | LONG | YES | -## cancel all open order (USER_DATA) +## Cancel All Open Order (USER_DATA) > **Response:** @@ -1366,7 +1366,7 @@ timestamp | LONG | YES | ``` `` -POST /api/v1/asset/transfer (HMAC SHA256) +POST /api/v1/asset/wallet/transfer (HMAC SHA256) `` **Weight:** @@ -1387,7 +1387,7 @@ timestamp | LONG | YES | **Notes:** * kindType FUTURE_SPOT(future to spot)/SPOT_FUTURE(spot to future) -## transfer asset to other address (TRADE) +## Transfer Asset To Other Address (TRADE) > **Response:** @@ -1423,7 +1423,7 @@ timestamp | LONG | YES | * If clientTranId is provided, its length must be at least 20 characters. -## get withdraw fee (USER_DATA) +## Get Withdraw Fee (NONE) > **Response:** ```javascript { @@ -1434,7 +1434,7 @@ timestamp | LONG | YES | ``` `` -GET /api/v1/aster/withdraw/estimateFee (HMAC SHA256) +GET /api/v1/aster/withdraw/estimateFee `` **Weight:** @@ -1451,7 +1451,7 @@ asset | STRING | YES | * chainId: 1(ETH),56(BSC),42161(Arbi) * gasCost: The minimum fee required for a withdrawal -## withdraw (USER_DATA) +## Withdraw (USER_DATA) > **Response:** ```javascript { @@ -1525,7 +1525,7 @@ const types = { const signature = await signer.signTypedData(domain, types, value) ``` -## get user create apikey nonce (NONE) +## Get User Create Apikey Nonce (NONE) > **Response:** ```javascript @@ -1553,7 +1553,7 @@ network | STRING | NO | * userOperationType : CREATE_API_KEY * network : For the Solana network, SOL must be provided; otherwise, this field is ignored. -## create apikey (NONE) +## Create Apikey (NONE) > **Response:** ```javascript diff --git a/apollox-finance-spot-api_CN.md b/aster-finance-spot-api_CN.md similarity index 99% rename from apollox-finance-spot-api_CN.md rename to aster-finance-spot-api_CN.md index 2bb35de..a623ce7 100644 --- a/apollox-finance-spot-api_CN.md +++ b/aster-finance-spot-api_CN.md @@ -931,8 +931,8 @@ symbol | STRING | NO | ```javascript { "symbol": "APXUSDT", - "makerCommission": "0.000200",     - "takerCommission": "0.000700" + "makerCommissionRate": "0.000200",     + "takerCommissionRate": "0.000700" } ``` `` @@ -1319,7 +1319,7 @@ timestamp | LONG | YES |   ``` `` -POST /api/v1/asset/transfer (HMAC SHA256) +POST /api/v1/asset/wallet/transfer (HMAC SHA256) `` **权重:** @@ -1377,7 +1377,7 @@ timestamp | LONG | YES | 时间戳 -## 现货提现手续费 (USER_DATA) +## 现货提现手续费 (NONe) > **响应** ```javascript { @@ -1388,7 +1388,7 @@ timestamp | LONG | YES | 时间戳 ``` `` -GET /api/v1/aster/withdraw/estimateFee (HMAC SHA256) +GET /api/v1/aster/withdraw/estimateFee `` **权重:** From da41503cbe6866d93ad48239af4cf648c680ffbb Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Tue, 2 Sep 2025 16:38:05 +0800 Subject: [PATCH 006/131] spot en --- aster-finance-spot-api.md | 2347 +++++++++++++++------------------- aster-finance-spot-api_CN.md | 1 + consolidation.js | 9 +- 3 files changed, 1066 insertions(+), 1291 deletions(-) diff --git a/aster-finance-spot-api.md b/aster-finance-spot-api.md index 921c13f..3baa47e 100644 --- a/aster-finance-spot-api.md +++ b/aster-finance-spot-api.md @@ -1,41 +1,34 @@ -# General Info -## General API Information +# Spot API Overview -* The base endpoint is: **https://sapi.asterdex.com** -* All endpoints return either a JSON object or array. -* All time and timestamp related fields are in **milliseconds**. +* This document lists the base URL for the API endpoints: [**https://sapi.asterdex.com**](https://sapi.asterdex.com) +* All API responses are in JSON format. +* All times and timestamps are in UNIX time, in **milliseconds**. -## API Key Setup +## API Key settings -* Some endpoints will require an API Key. -* Once API key is created, it is recommended to set IP restrictions on the key for security reasons. -* **Never share your API key/secret key to ANYONE.** +* Many endpoints require an API Key to access. +* When setting the API Key, for security reasons it is recommended to set an IP access whitelist. +* **Never reveal your API key/secret to anyone.** - +If an API Key is accidentally exposed, immediately delete that Key and generate a new one. ### Attention * TESTUSDT or any other symbols starting with TEST are symbols used for Aster’s INTERNAL TESTING ONLY. Please DO NOT trade on these symbols starting with TEST. Aster does not hold any accountability for loss of funds due to trading on these symbols. However, if you run into issues, you may contact support about this any time, we will try to help you recover your funds. +### HTTP return codes +* HTTP `4XX` status codes are used to indicate errors in the request content, behavior, or format. The problem lies with the requester. +* HTTP `403` status code indicates a violation of WAF restrictions (Web Application Firewall). +* HTTP `429` error code indicates a warning that the access frequency limit has been exceeded and the IP is about to be blocked. +* HTTP `418` indicates that after receiving a 429 you continued to access, so the IP has been blocked. +* HTTP `5XX` error codes are used to indicate issues on the Aster service side. -### HTTP Return Codes -* HTTP `4XX` return codes are used for malformed requests; - the issue is on the sender's side. -* HTTP `403` return code is used when the WAF Limit (Web Application Firewall) has been violated. -* HTTP `429` return code is used when breaking a request rate limit. -* HTTP `418` return code is used when an IP has been auto-banned for continuing to send requests after receiving `429` codes. -* HTTP `5XX` return codes are used for internal errors; the issue is on Aster's side. - It is important to **NOT** treat this as a failure operation; the execution status is - **UNKNOWN** and could have been a success. +### API error codes -### Error Codes and Messages +* When using the endpoint `/api/v1`, any endpoint may throw exceptions; -* If there is an error, the API will return an error with a message of the reason. +The API error codes are returned in the following format: -> The error payload on API is as follows: - ```javascript { "code": -1121, @@ -43,86 +36,85 @@ If the API keys were accidentally shared, please delete them immediately and cre } ``` -### General Information on Endpoints +### Basic information about the endpoint -* For `GET` endpoints, parameters must be sent as a `query string`. -* For `POST`, `PUT`, and `DELETE` endpoints, the parameters may be sent as a - `query string` or in the `request body` with content type - `application/x-www-form-urlencoded`. -* Parameters may be sent in any order. +* Endpoints with the `GET` method must send parameters in the `query string`. +* For `POST`, `PUT`, and `DELETE` endpoints, parameters can be sent in the `query string` with content type `application/x-www-form-urlencoded` , or in the `request body`. +* The order of parameters is not required. --- -## LIMITS - -### General Info on Limits -* The `/api/v1/exchangeInfo` `rateLimits` array contains objects related to the exchange's `REQUEST_WEIGHT`, and `ORDERS` rate limits. These are further defined in the `ENUM definitions` section under `Rate limiters (rateLimitType)`. -* A 429 will be returned when either rate limit is violated. - -### IP Limits -* Every request will contain `X-MBX-USED-WEIGHT-(intervalNum)(intervalLetter)` in the response headers which has the current used weight for the IP for all request rate limiters defined. -* Each route has a `weight` which determines for the number of requests each endpoint counts for. Heavier endpoints and endpoints that do operations on multiple symbols will have a heavier `weight`. -* When a 429 is received, it's your obligation as an API to back off and not spam the API. -* **Repeatedly violating rate limits and/or failing to back off after receiving 429s will result in an automated IP ban (HTTP status 418).** -* IP bans are tracked and **scale in duration** for repeat offenders, **from 2 minutes to 3 days**. -* A `Retry-After` header is sent with a 418 or 429 responses and will give the **number of seconds** required to wait, in the case of a 429, to prevent a ban, or, in the case of a 418, until the ban is over. -* **The limits on the API are based on the IPs, not the API keys.** - - - -### Order Rate Limits -* Every successful order response will contain a `X-MBX-ORDER-COUNT-(intervalNum)(intervalLetter)` header which has the current order count for the account for all order rate limiters defined. -* Rejected/unsuccessful orders are not guaranteed to have `X-MBX-ORDER-COUNT-**` headers in the response. -* **The order rate limit is counted against each account**. - -### Websocket Limits -* WebSocket connections have a limit of 5 incoming messages per second. A message is considered: - * A PING frame - * A PONG frame - * A JSON controlled message (e.g. subscribe, unsubscribe) -* A connection that goes beyond the limit will be disconnected; IPs that are repeatedly disconnected may be banned. -* A single connection can listen to a maximum of 1024 streams. + +## Access restrictions + +### Basic information on access restrictions + +* The `rateLimits` array in `/api/v1/exchangeInfo` contains objects related to REQUEST\_WEIGHT and ORDERS rate limits for trading. These are further defined in the `enum definitions` section under `rateLimitType`. +* A 429 will be returned when any of the rate limits are violated. + +### IP access limits + +* Each request will include a header named `X-MBX-USED-WEIGHT-(intervalNum)(intervalLetter)` that contains the used weight of all requests from the current IP. +* Each endpoint has a corresponding weight, and some endpoints may have different weights depending on their parameters. The more resources an endpoint consumes, the higher its weight will be. +* Upon receiving a 429, you are responsible for stopping requests and must not abuse the API. +* **If you continue to violate access limits after receiving a 429, your IP will be banned and you will receive a 418 error code.** +* Repeated violations of the limits will result in progressively longer bans, **from a minimum of 2 minutes up to a maximum of 3 days**. +* The `Retry-After` header will be sent with responses bearing 418 or 429, and will give the wait time **in seconds** (if 429\) to avoid the ban, or, if 418, until the ban ends. +* **Access restrictions are based on IP, not API Key** + +You are advised to use WebSocket messages to obtain the corresponding data as much as possible to reduce the load and rate-limit pressure from requests. + +### Order rate limits + +* Each successful order response will include a `X-MBX-ORDER-COUNT-(intervalNum)(intervalLetter)` header containing the number of order limit units currently used by the account. +* When the number of orders exceeds the limit, you will receive a response with status 429 but without the `Retry-After` header. Please check the order rate limits in `GET api/v1/exchangeInfo` (rateLimitType \= ORDERS) and wait until the ban period ends. +* Rejected or unsuccessful orders are not guaranteed to include the above header in the response. +* **Order placement rate limits are counted per account.** + +### WebSocket connection limits + +* The WebSocket server accepts a maximum of 5 messages per second. Messages include: + * PING frame + * PONG frame + * Messages in JSON format, such as subscribe and unsubscribe. +* If a user sends messages that exceed the limit, the connection will be terminated. IPs that are repeatedly disconnected may be blocked by the server. +* A single connection can subscribe to up to **1024** Streams. + +--- + +## API authentication types + +* Each API has its own authentication type, which determines what kind of authentication should be performed when accessing it. +* The authentication type will be indicated next to each endpoint name in this document; if not specifically stated, it defaults to `NONE`. +* If API keys are required, they should be passed in the HTTP header using the `X-MBX-APIKEY` field. +* API keys and secret keys are **case-sensitive**. +* By default, API keys have access to all authenticated routes. + +| Authentication type | Description | +| :---- | :---- | +| NONE | APIs that do not require authentication | +| TRADE | A valid API-Key and signature are required | +| USER\_DATA | A valid API-Key and signature are required | +| USER\_STREAM | A valid API-Key is required | +| MARKET\_DATA | A valid API-Key is required | + +* The `TRADE` and `USER_DATA` endpoints are signed (SIGNED) endpoints. --- -## Endpoint security type -* Each endpoint has a security type that determines how you will - interact with it. This is stated next to the NAME of the endpoint. - * If no security type is stated, assume the security type is NONE. -* API-keys are passed into the Rest API via the `X-MBX-APIKEY` - header. -* API-keys and secret-keys **are case sensitive**. -* API-keys can be configured to only access certain types of secure endpoints. -* By default, API-keys can access all secure routes. - -Security Type | Description ------------- | ------------ -NONE | Endpoint can be accessed freely. -TRADE | Endpoint requires sending a valid API-Key and signature. -USER_DATA | Endpoint requires sending a valid API-Key and signature. -USER_STREAM | Endpoint requires sending a valid API-Key. -MARKET_DATA | Endpoint requires sending a valid API-Key. - -* `TRADE` and `USER_DATA` endpoints are `SIGNED` endpoints. - -## SIGNED (TRADE AND USER_DATA) Endpoint security -* `SIGNED` endpoints require an additional parameter, `signature`, to be - sent in the `query string` or `request body`. -* Endpoints use `HMAC SHA256` signatures. The `HMAC SHA256 signature` is a keyed `HMAC SHA256` operation. - Use your `secretKey` as the key and `totalParams` as the value for the HMAC operation. -* The `signature` is **not case sensitive**. -* `totalParams` is defined as the `query string` concatenated with the - `request body`. - -### Timing security -* A `SIGNED` endpoint also requires a parameter, `timestamp`, to be sent which - should be the millisecond timestamp of when the request was created and sent. -* An additional parameter, `recvWindow`, may be sent to specify the number of - milliseconds after `timestamp` the request is valid for. If `recvWindow` - is not sent, **it defaults to 5000**. - -> The logic is as follows: +## SIGNED (TRADE AND USER\_DATA) Endpoint security + +* When calling a `SIGNED` endpoint, in addition to the parameters required by the endpoint itself, you must also pass a `signature` parameter in the `query string` or `request body`. +* The signature uses the `HMAC SHA256` algorithm. The API-Secret corresponding to the API-KEY is used as the key for `HMAC SHA256`, and all other parameters are used as the data for the `HMAC SHA256` operation; the output is the signature. +* The `signature` is **case-insensitive**. +* "totalParams" is defined as the "query string" concatenated with the "request body". + +### Time synchronization safety + +* Signed endpoints must include the `timestamp` parameter, whose value should be the unix timestamp (milliseconds) at the moment the request is sent. +* When the server receives a request it will check the timestamp; if it was sent more than 5,000 milliseconds earlier, the request will be considered invalid. This time window value can be defined by sending the optional `recvWindow` parameter. + +The logical pseudocode is as follows: + ```javascript if (timestamp < (serverTime + 1000) && (serverTime - timestamp) <= recvWindow) { @@ -134,174 +126,157 @@ MARKET_DATA | Endpoint requires sending a valid API-Key. } ``` -**Serious trading is about timing.** Networks can be unstable and unreliable, -which can lead to requests taking varying amounts of time to reach the -servers. With `recvWindow`, you can specify that the request must be -processed within a certain number of milliseconds or be rejected by the -server. +**About trade timeliness** Internet conditions are not completely stable or reliable, so the latency from your client to Aster's servers will experience jitter. This is why we provide `recvWindow`; if you engage in high-frequency trading and have strict requirements for timeliness, you can adjust `recvWindow` flexibly to meet your needs. - +It is recommended to use a recvWindow of under 5 seconds. It must not exceed 60 seconds. -### SIGNED Endpoint Examples for POST /api/v1/order -Here is a step-by-step example of how to send a vaild signed payload from the -Linux command line using `echo`, `openssl`, and `curl`. +### Example of POST /api/v1/order -Key | Value ------------- | ------------ -apiKey | 4452d7e2ed4da80b74105e02d06328c71a34488c9fdd60a5a0900d42d584b795 -secretKey | fdde510a2b71fa43a43bff3e3cf7819c8c66df34633d338050f4f59664b3b313 +Below is an example of placing an order by calling the API using echo, openssl, and curl tools in a Linux bash environment. The apiKey and secretKey are for demonstration only. -Parameter | Value ------------- | ------------ -symbol | BNBUSDT -side | BUY -type | LIMIT -timeInForce | GTC -quantity | 5 -price | 1.1 -recvWindow | 5000 -timestamp | 1756187806000 +| Key | Value | +| :---- | :---- | +| apiKey | 4452d7e2ed4da80b74105e02d06328c71a34488c9fdd60a5a0900d42d584b795 | +| secretKey | fdde510a2b71fa43a43bff3e3cf7819c8c66df34633d338050f4f59664b3b313 | +| Parameters | Values | +| :---- | :---- | +| symbol | BNBUSDT | +| side | BUY | +| type | LIMIT | +| timeInForce | GTC | +| quantity | 5 | +| price | 1.1 | +| recvWindow | 5000 | +| timestamp | 1756187806000 | -#### Example 1: As a request body +#### Example 1: All parameters are sent through the request body +**Example 1** **HMAC SHA256 signature:** -> **Example 1** -> **HMAC SHA256 signature:** ```shell $ echo -n "symbol=BNBUSDT&side=BUY&type=LIMIT&timeInForce=GTC&quantity=5&price=1.1&recvWindow=5000×tamp=1756187806000" | openssl dgst -sha256 -hmac "fdde510a2b71fa43a43bff3e3cf7819c8c66df34633d338050f4f59664b3b313" (stdin)= e09169bf6c02ec4b29fa1bdc3a967f92c8c6cfcde0551ba1d477b2d3cf4c51b0 ``` +**curl command:** -> **curl command:** ```shell (HMAC SHA256) $ curl -H "X-MBX-APIKEY: 4452d7e2ed4da80b74105e02d06328c71a34488c9fdd60a5a0900d42d584b795" -X POST 'https://sapi.asterdex.com/api/v1/order' -d 'symbol=BNBUSDT&side=BUY&type=LIMIT&timeInForce=GTC&quantity=5&price=1.1&recvWindow=5000×tamp=1756187806000&signature=e09169bf6c02ec4b29fa1bdc3a967f92c8c6cfcde0551ba1d477b2d3cf4c51b0' ``` -* **requestBody:** +* **requestBody:** -symbol=BNBUSDT -&side=BUY -&type=LIMIT -&timeInForce=GTC -&quantity=5 -&price=1.1 -&recvWindow=5000 -×tamp=1756187806000 +symbol=BNBUSDT \&side=BUY \&type=LIMIT \&timeInForce=GTC \&quantity=5 \&price=1.1 \&recvWindow=5000 \×tamp=1756187806000 +#### Example 2: All parameters sent through the query string -#### Example 2: As a query string +**Example 2** **HMAC SHA256 signature:** -> **Example 2** -> **HMAC SHA256 signature:** ```shell - $ echo -n "symbol=BNBUSDT&side=BUY&type=LIMIT&timeInForce=GTC&quantity=5&price=1.1&recvWindow=5000×tamp=1756187806000" | openssl dgst -sha256 -hmac "fdde510a2b71fa43a43bff3e3cf7819c8c66df34633d338050f4f59664b3b313" - (stdin)= e09169bf6c02ec4b29fa1bdc3a967f92c8c6cfcde0551ba1d477b2d3cf4c51b0 + $ echo -n "symbol=BNBUSDT&side=BUY&type=LIMIT&timeInForce=GTC&quantity=5&price=1.1&recvWindow=5000×tamp=1756187806000" | openssl dgst -sha256 -hmac "fdde510a2b71fa43a43bff3e3cf7819c8c66df34633d338050f4f59664b3b313" + (stdin)= e09169bf6c02ec4b29fa1bdc3a967f92c8c6cfcde0551ba1d477b2d3cf4c51b0 ``` -> **curl command:** +**curl command:** + ```shell (HMAC SHA256) $ curl -H "X-MBX-APIKEY: 4452d7e2ed4da80b74105e02d06328c71a34488c9fdd60a5a0900d42d584b795" -X POST 'https://sapi.asterdex.com/api/v1/order?symbol=BNBUSDT&side=BUY&type=LIMIT&timeInForce=GTC&quantity=5&price=1.1&recvWindow=5000×tamp=1756187806000&signature=e09169bf6c02ec4b29fa1bdc3a967f92c8c6cfcde0551ba1d477b2d3cf4c51b0' ``` -* **queryString:** +* **queryString:** -symbol=BNBUSDT -&side=BUY -&type=LIMIT -&timeInForce=GTC -&quantity=5 -&price=1.1 -&recvWindow=5000 -×tamp=1756187806000 +symbol=BNBUSDT \&side=BUY \&type=LIMIT \&timeInForce=GTC \&quantity=5 \&price=1.1 \&recvWindow=5000 \×tamp=1756187806000 --- -## Public API Definitions +## Public API parameters + ### Terminology -These terms will be used throughout the documentation, so it is recommended especially for new users to read to help their understanding of the API. +The terminology in this section applies throughout the document. New users are encouraged to read it carefully for better understanding. -* `base asset` refers to the asset that is the `quantity` of a symbol. For the symbol BTCUSDT, BTC would be the `base asset.` -* `quote asset` refers to the asset that is the `price` of a symbol. For the symbol BTCUSDT, USDT would be the `quote asset`. +* `base asset` refers to the asset being traded in a trading pair, i.e., the asset name written first; for example, in `BTCUSDT`, `BTC` is the `base asset`. +* `quote asset` refers to the pricing asset of a trading pair, i.e., the asset name written at the latter part; for example, in `BTCUSDT`, `USDT` is the `quote asset`. -### ENUM definitions -**Symbol status (status):** +### Enumeration definition -* TRADING +**Trading pair status (status):** +* TRADING \- after trade -**Order status (status):** +**Trading pair type:** -Status | Description ------------| -------------- -`NEW` | The order has been accepted by the engine. -`PARTIALLY_FILLED`| A part of the order has been filled. -`FILLED` | The order has been completed. -`CANCELED` | The order has been canceled by the user. -`REJECTED` | The order was not accepted by the engine and not processed. -`EXPIRED` | The order was canceled according to the order type's rules (e.g. LIMIT FOK orders with no fill, LIMIT IOC or MARKET orders that partially fill) or by the exchange, (e.g. orders canceled during maintenance) +* SPOT \- spot +**Order status (status):** + +| Status | Description | +| :---- | :---- | +| NEW | Order accepted by the matching engine | +| PARTIALLY\_FILLED | Part of the order was filled | +| FILLED | The order was fully filled | +| CANCELED | The user canceled the order | +| REJECTED | The order was not accepted by the matching engine and was not processed | +| EXPIRED | Order canceled by the trading engine, for example: Limit FOK order not filled, Market order not fully filled, orders canceled during exchange maintenance | **Order types (orderTypes, type):** -* LIMIT -* MARKET -* STOP -* TAKE_PROFIT -* STOP_MARKET -* TAKE_PROFIT_MARKET +* LIMIT \- Limit Order +* MARKET \- Market Order +* STOP \- Limit Stop Order +* TAKE\_PROFIT \- Limit Take-Profit Order +* STOP\_MARKET \- Market Stop Order +* TAKE\_PROFIT\_MARKET \- Market Take-Profit Order -**Order Response Type (newOrderRespType):** +**Order response type (newOrderRespType):** -* ACK -* RESULT +* ACK +* RESULT * FULL -**Order side (side):** +**Order direction (direction side):** -* BUY -* SELL +* BUY \- Buy +* SELL \- Sell -**Time in force (timeInForce):** +**Valid types (timeInForce):** -This sets how long an order will be active before expiration. +This defines how long an order can remain valid before expiring. -Status | Description ------------| -------------- -`GTC` | Good Till Canceled
An order will be on the book unless the order is canceled. -`IOC` | Immediate Or Cancel
An order will try to fill the order as much as it can before the order expires. -`FOK`| Fill or Kill
An order will expire if the full order cannot be filled upon execution. -`GTX`| Good Till Crossing
 Post only order +| Status | Description | +| :---- | :---- | +| GTC (Good ‘Til Canceled) | The order remains active until it is fully executed or manually canceled. | +| IOC (Immediate or Cancel) | The order will execute immediately for any amount available. Any unfilled portion is automatically canceled. | +| FOK (Fill or Kill) | The order must be fully executed immediately. If it cannot be filled in full, it is canceled right away. | +| GTX (Good ‘Til Executed) | The order remains active until it is fully executed. Only limit orders are supported. | -**Kline/Candlestick chart intervals:** +**K-line interval:** -m -> minutes; h -> hours; d -> days; w -> weeks; M -> months +m (minutes), h (hours), d (days), w (weeks), M (months) -* 1m -* 3m -* 5m -* 15m -* 30m -* 1h -* 2h -* 4h -* 6h -* 8h -* 12h -* 1d -* 3d -* 1w +* 1m +* 3m +* 5m +* 15m +* 30m +* 1h +* 2h +* 4h +* 6h +* 8h +* 12h +* 1d +* 3d +* 1w * 1M -**Rate limiters (rateLimitType)** +**Rate limit type (rateLimitType)** + +REQUEST\_WEIGHT -> REQUEST_WEIGHT ```json { "rateLimitType": "REQUEST_WEIGHT", @@ -311,7 +286,8 @@ m -> minutes; h -> hours; d -> days; w -> weeks; M -> months } ``` -> ORDERS +ORDERS + ```json { "rateLimitType": "ORDERS", @@ -321,182 +297,160 @@ m -> minutes; h -> hours; d -> days; w -> weeks; M -> months } ``` -* REQUEST_WEIGHT - -* ORDERS +* REQUEST\_WEIGHT \- The maximum sum of request weights allowed within a unit time + +* ORDERS \- Order placement frequency limit per time unit -**Rate limit intervals (interval)** +**Interval restriction (interval)** -* MINUTE +* MINUTE \- Minute --- + ## Filters -Filters define trading rules on a symbol or an exchange. -Filters come in two forms: `symbol filters` and `exchange filters`. Currently only `symbol filters` is used. -### Symbol Filters +Filters, i.e. Filter, define a set of trading rules. There are two types: filters for trading pairs `symbol filters`, and filters for the entire exchange `exchange filters` (not supported yet) + +### Trading pair filters -#### PRICE_FILTER +#### PRICE\_FILTER Price filter -> **ExchangeInfo format:** -```javascript +**Format in the /exchangeInfo response:** + +```javascript { - "minPrice": "556.72", + "minPrice": "556.72", "maxPrice": "4529764", "filterType": "PRICE_FILTER", "tickSize": "0.01"   - } + } ``` -The `PRICE_FILTER` defines the `price` rules for a symbol. There are 3 parts: +The `Price Filter` checks the validity of the `price` parameter in an order. It consists of the following three parts: + +* `minPrice` defines the minimum allowed value for `price`/`stopPrice`. +* `maxPrice` defines the maximum allowed value for `price`/`stopPrice`. +* `tickSize` defines the step interval for `price`/`stopPrice`, meaning the price must equal minPrice plus an integer multiple of tickSize. -* `minPrice` defines the minimum `price`/`stopPrice` allowed; disabled on `minPrice` == 0. -* `maxPrice` defines the maximum `price`/`stopPrice` allowed; disabled on `maxPrice` == 0. -* `tickSize` defines the intervals that a `price`/`stopPrice` can be increased/decreased by; disabled on `tickSize` == 0. +Each of the above items can be 0; when 0 it means that item is not constrained. -Any of the above variables can be set to 0, which disables that rule in the `price filter`. In order to pass the `price filter`, the following must be true for `price`/`stopPrice` of the enabled rules: +The logical pseudocode is as follows: -* `price` >= `minPrice` -* `price` <= `maxPrice` -* (`price`-`minPrice`) % `tickSize` == 0 +* `price` \>= `minPrice` +* `price` \<= `maxPrice` +* (`price`\-`minPrice`) % `tickSize` \== 0 +#### PERCENT\_PRICE price amplitude filter -#### PERCENT_PRICE +**Format in the /exchangeInfo response:** -> **ExchangeInfo format:** -```javascript +```javascript { "multiplierDown": "0.9500", "multiplierUp": "1.0500", "multiplierDecimal": "4", "filterType": "PERCENT_PRICE" -  } +  } ``` -The `PERCENT_PRICE` filter defines valid range for a price based on the index price. +The `PERCENT_PRICE` filter defines the valid range of prices based on the index price. -In order to pass the `percent price`, the following must be true for `price`:   +For the "price percentage" to apply, the "price" must meet the following conditions: -* `price` <=`indexPrice` *`multiplierUp` -* `price`> =`indexPrice` *`multiplierDown`     +* `price` \<=`indexPrice` \*`multiplierUp` +* `price`\> \=`indexPrice` \*`multiplierDown` +#### LOT\_SIZE order size -#### LOT_SIZE +**Format in the /exchangeInfo response:** -> **ExchangeInfo format:** -```javascript +```javascript { "stepSize": "0.00100000",   "filterType": "LOT_SIZE", "maxQty": "100000.00000000",   "minQty": "0.00100000" - } + } ``` -The `LOT_SIZE` filter defines the `quantity` (aka "lots" in auction terms) rules for a symbol. There are 3 parts: - -* `minQty` defines the minimum `quantity` allowed. -* `maxQty` defines the maximum `quantity` allowed. -* `stepSize` defines the intervals that a `quantity` can be increased/decreased by. +Lots is an auction term. The `LOT_SIZE` filter validates the `quantity` (i.e., the amount) parameter in orders. It consists of three parts: -In order to pass the `lot size`, the following must be true for `quantity`: +* `minQty` indicates the minimum allowed value for `quantity`. +* `maxQty` denotes the maximum allowed value for `quantity`. +* `stepSize` denotes the allowed step increment for `quantity`. -* `quantity` >= `minQty` -* `quantity` <= `maxQty` -* (`quantity`-`minQty`) % `stepSize` == 0 +The logical pseudocode is as follows: +* `quantity` \>= `minQty` +* `quantity` \<= `maxQty` +* (`quantity`\-`minQty`) % `stepSize` \== 0 +#### MARKET\_LOT\_SIZE \- Market order size +\***/exchangeInfo response format:** -#### MARKET_LOT_SIZE - -> **ExchangeInfo format:** ```javascript - { - "stepSize": "0.00100000", - "filterType": "MARKET_LOT_SIZE" + { + "stepSize": "0.00100000", +   "filterType": "MARKET_LOT_SIZE" "maxQty": "100000.00000000", - "minQty": "0.00100000"   + "minQty": "0.00100000" } ``` +The `MARKET_LOT_SIZE` filter defines the `quantity` (i.e., the "lots" in an auction) rules for `MARKET` orders on a trading pair. There are three parts: -The `MARKET_LOT_SIZE` filter defines the `quantity` (aka "lots" in auction terms) rules for `MARKET` orders on a symbol. There are 3 parts: +* `minQty` defines the minimum allowed `quantity`. +* `maxQty` defines the maximum allowed quantity. +* `stepSize` defines the increments by which the quantity can be increased or decreased. -* `minQty` defines the minimum `quantity` allowed. -* `maxQty` defines the maximum `quantity` allowed. -* `stepSize` defines the intervals that a `quantity` can be increased/decreased by. +In order to comply with the `market lot size`, the `quantity` must satisfy the following conditions: -In order to pass the `market lot size`, the following must be true for `quantity`: +* `quantity` \>= `minQty` +* `quantity` \<= `maxQty` +* (`quantity`\-`minQty`) % `stepSize` \== 0 -* `quantity` >= `minQty` -* `quantity` <= `maxQty` -* (`quantity`-`minQty`) % `stepSize` == 0 +# Market data API +## Test server connectivity +**Response** - - - - - - - - - -# Market Data Endpoints - -## Test Connectivity - - - -> **Response:** ```javascript {} ``` -`` -GET /api/v1/ping -`` - -Test connectivity to the Rest API. +`GET /api/v1/ping` -**Weight:** -1 +Test whether the REST API can be reached. -**Parameters:** +**Weight:** 1 -NONE +**Parameters:** NONE -## Check Server Time +## Get server time +**Response** -> **Response:** ```javascript { "serverTime": 1499827319559 } ``` -`` -GET /api/v1/time -`` +`GET /api/v1/time` -Test connectivity to the Rest API and get the current server time. +Test if the REST API can be reached and retrieve the server time. -**Weight:** -1 - -**Parameters:** +**Weight:** 1 -NONE +**Parameters:** NONE +## Trading specification information -## Exchange Information +**Response** -> **Response:** - -```javascript   +```javascript { "timezone": "UTC", "serverTime": 1756197279679, @@ -611,32 +565,27 @@ NONE } ``` -`` -GET /api/v1/exchangeInfo -`` - -Current exchange trading rules and symbol information +`GET /api/v1/exchangeInfo` -**Weight:** -1 +Retrieve trading rules and trading pair information. -**Parameters:** -NONE +**Weight:** 1 +**Parameters:** None -## Order Book +## Depth information +**Response** -> **Response:** ```javascript { "lastUpdateId": 1027024, - "E": 1589436922972, // Message output time - "T": 1589436922959, // Transaction time -  "bids": [ + "E":1589436922972, // Message output time + "T":1589436922959, // Transaction time + "bids": [ [ - "4.00000000", // PRICE - "431.00000000" // QTY + "4.00000000", // PRICE + "431.00000000" // QTY ] ], "asks": [ @@ -648,34 +597,30 @@ NONE } ``` -`` -GET /api/v1/depth -`` +`GET /api/v1/depth` -**Weight(IP):** +**Weight:** -Adjusted based on the limit: +Based on limit adjustments: +| Limitations | Weight | +| :---- | :---- | +| 5, 10, 20, 50 | 2 | +| 100 | 5 | +| 500 | 10 | +| 1000 | 20 | -Limit | Weight ------------- | ------------ -5, 10, 20, 50 | 2 -100 | 5 -500 | 10 -1000 | 20 -   **Parameters:** -Name | Type | Mandatory | Description ------------- | ------------ | ------------ | ------------ -symbol | STRING | YES | -limit | INT | NO | Default 100. Valid limits:[5, 10, 20, 50, 100, 500, 1000] - +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| limit | INT | NO | Default 100\. Optional values: \[5, 10, 20, 50, 100, 500, 1000\] | -## Recent Trades List +## Recent trades list +**Response** -> **Response:** ```javascript [ { @@ -689,26 +634,22 @@ limit | INT | NO | Default 100. Valid limits:[5, 10, 20, 50, 100, 500, 1000] ] ``` -`` -GET /api/v1/trades -`` +`GET /api/v1/trades` -Get recent trades. +Get recent trades -**Weight:** -1 +**Weight:** 1 **Parameters:** -Name | Type | Mandatory | Description ------------- | ------------ | ------------ | ------------ -symbol | STRING | YES | -limit | INT | NO | Default 500;max 1000 - +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| limit | INT | NO | Default 500; maximum 1000 | -## Old Trade Lookup (MARKET_DATA) +## Query historical trades (MARKET\_DATA) -> **Response:** +**Response** ```javascript [ @@ -723,117 +664,102 @@ limit | INT | NO | Default 500;max 1000 ] ``` -`` -GET /api/v1/historicalTrades -`` +`GET /api/v1/historicalTrades` -Get older market trades. +Retrieve historical trades -**Weight:** -20 +**Weight:** 20 **Parameters:** -Name | Type | Mandatory | Description ------------- | ------------ | ------------ | ------------ -symbol | STRING | YES | -limit | INT | NO | Default 500; max 1000. -fromId | LONG | NO | Trade id to fetch from. Default gets most recent trades. - +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| limit | INT | NO | Default 500; maximum 1000\. | +| fromId | LONG | NO | Return starting from which trade id. Defaults to returning the most recent trade records. | -## Compressed/Aggregate Trades List +## Recent trades (aggregated) +**Response** -> **Response:** ```javascript [ { - "a": 26129, // Aggregate tradeId - "p": "0.01633102", // Price - "q": "4.70443515", // Quantity - "f": 27781, // First tradeId - "l": 27781, // Last tradeId + "a": 26129, // Aggregate tradeId + "p": "0.01633102", // Price + "q": "4.70443515", // Quantity + "f": 27781, // First tradeId + "l": 27781, // Last tradeId "T": 1498793709153, // Timestamp - "m": true, // Was the buyer the maker? + "m": true, // Was the buyer the maker? } ] ``` -`` -GET /api/v1/aggTrades -`` +`GET /api/v1/aggTrades` -Get compressed, aggregate trades. Trades that fill at the time, from the same -order, with the same price will have the quantity aggregated. +The difference between aggregated trades and individual trades is that trades with the same price, same side, and same time are combined into a single entry. -**Weight:** -20 +**Weight:** 20 **Parameters:** -Name | Type | Mandatory | Description ------------- | ------------ | ------------ | ------------ -symbol | STRING | YES | -fromId | LONG | NO | id to get aggregate trades from INCLUSIVE. -startTime | LONG | NO | Timestamp in ms to get aggregate trades from INCLUSIVE. -endTime | LONG | NO | Timestamp in ms to get aggregate trades until INCLUSIVE. -limit | INT | NO | Default 500; max 1000. - -* If startTime and endTime are sent, time between startTime and endTime must be less than 1 hour. -* If fromId, startTime, and endTime are not sent, the most recent aggregate trades will be returned. +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| fromId | LONG | NO | Return results starting from the trade ID that includes fromId | +| startTime | LONG | NO | Return results starting from trades after that time | +| endTime | LONG | NO | Return the trade records up to that moment | +| limit | INT | NO | Default 500; maximum 1000\. | +* If you send startTime and endTime, the interval must be less than one hour. +* If no filter parameters (fromId, startTime, endTime) are sent, the most recent trade records are returned by default -## Kline/Candlestick Data +## K-line data +**Response** -> **Response:** ```javascript [ [ - 1499040000000, // Open time - "0.01634790", // Open - "0.80000000", // High - "0.01575800", // Low - "0.01577100", // Close - "148976.11427815", // Volume - 1499644799999, // Close time - "2434.19055334", // Quote asset volume - 308, // Number of trades - "1756.87402397", // Taker buy base asset volume - "28.46694368", // Taker buy quote asset volume - "17928899.62484339" // Ignore. + 1499040000000, // Open time + "0.01634790", // Open + "0.80000000", // High + "0.01575800", // Low + "0.01577100", // Close + "148976.11427815", // Volume + 1499644799999, // Close time + "2434.19055334", // Quote asset volume + 308, // Number of trades + "1756.87402397", // Taker buy base asset volume + "28.46694368", // Taker buy quote asset volume ] ] ``` -`` -GET /api/v1/klines -`` - -Kline/candlestick bars for a symbol. -Klines are uniquely identified by their open time. +`GET /api/v1/klines` +Each K-line represents a trading pair. The open time of each K-line can be regarded as a unique ID. **Parameters:** -Name | Type | Mandatory | Description ------------- | ------------ | ------------ | ------------ -symbol | STRING | YES | -interval | ENUM | YES | -startTime | LONG | NO | -endTime | LONG | NO | -limit | INT | NO | Default 500; max 1500. +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| interval | ENUM | YES | See the enumeration definition: K-line interval | +| startTime | LONG | NO | | +| endTime | LONG | NO | | +| limit | INT | NO | Default 500; maximum 1500\. | -* If startTime and endTime are not sent, the most recent klines are returned. +* If startTime and endTime are not sent, the most recent trades are returned by default +## 24h price change -## 24hr Ticker Price Change Statistics - -> **Response:** +**Response** -```javascript +```javascript { - "symbol": "BTCUSDT", + "symbol": "BTCUSDT", //symbol "priceChange": "-94.99999800", //price change "priceChangePercent": "-95.960", //price change percent "weightedAvgPrice": "0.29628482", //weighted avgPrice @@ -857,32 +783,25 @@ limit | INT | NO | Default 500; max 1500. } ``` -`` -GET /api/v1/ticker/24hr -`` - -24 hour rolling window price change statistics. -**Careful** when accessing this with no symbol. +`GET /api/v1/ticker/24hr` -**Weight:** +24-hour rolling window price change data. Please note that omitting the symbol parameter will return data for all trading pairs; in that case the returned data is an example array for the respective pairs, which is not only large in volume but also has a very high weight. -1 for a single symbol; -**40** when the symbol parameter is omitted; +**Weight:** 1 \= single trading pair; **40** \= When the trading pair parameter is missing (returns all trading pairs) **Parameters:** -Name | Type | Mandatory | Description ------------- | ------------ | ------------ | ------------ -symbol | STRING | NO | - -* If the symbol is not sent, tickers for all symbols will be returned in an array.   +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | NO | | +* Please note that omitting the symbol parameter will return data for all trading pairs -## 最新价格 +## Latest price -> **Response** +**Response** -```javascript +```javascript { "symbol": "ADAUSDT", "price": "1.30000000", @@ -890,7 +809,7 @@ symbol | STRING | NO | } ``` -> OR +OR ```javascript [ @@ -902,28 +821,24 @@ symbol | STRING | NO | ] ``` -`` -GET /api/v1/ticker/price -``   +`GET /api/v1/ticker/price` -Latest price for a symbol or symbols. +Get the latest price for a trading pair -**Weight:** -1 for a single symbol; -2 when the symbol parameter is omitted +**Weight:** 1 \= Single trading pair; **2** \= No symbol parameter (returns all pairs) **Parameters:** -Name | Type | Mandatory | Description ------------- | ------------ | ------------ | ------------ -symbol | STRING | NO | +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | NO | | -* If the symbol is not sent, prices for all symbols will be returned in an array. +* If no trading pair parameter is sent, information for all trading pairs will be returned +## Current best order -## Symbol Order Book Ticker     +**Response** -> **Response** ```javascript { "symbol": "LTCBTC", @@ -931,11 +846,11 @@ symbol | STRING | NO | "bidQty": "431.00000000", "askPrice": "4.00000200", "askQty": "9.00000000" - "time": 1589437530011 + "time": 1589437530011 // Timestamp } ``` -> OR +OR ```javascript [ @@ -945,33 +860,28 @@ symbol | STRING | NO | "bidQty": "431.00000000", "askPrice": "4.00000200", "askQty": "9.00000000", - "time": 1589437530011 + "time": 1589437530011 // Timestamp } ] ``` -`` -GET /api/v1/ticker/bookTicker -`` +`GET /api/v1/ticker/bookTicker` -Best price/qty on the order book for a symbol or symbols. +Return the current best orders (highest bid, lowest ask) -**Weight:** -1 for a single symbol; -2 when the symbol parameter is omitted +**Weight:** 1 \= Single trading pair; **2** \= No symbol parameter (returns all pairs) **Parameters:** -Name | Type | Mandatory | Description ------------- | ------------ | ------------ | ------------ -symbol | STRING | NO | - -* If the symbol is not sent, prices for all symbols will be returned in an array. +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | NO | | +* If no trading pair parameter is sent, information for all trading pairs will be returned -## Symbol Commmission Fee +## Get symbol fees -> **Response:** +**Response** ```javascript { @@ -981,32 +891,27 @@ symbol | STRING | NO | } ``` -`` -GET /api/v1/commissionRate -`` +`GET /api/v1/commissionRate` -Get symbol commission fee. +Get symbol fees -**Weight:** -20 +**Weight:** 20 **Parameters:** -Name | Type | Mandatory | Description ------------- | ------------ | ------------ | ------------ -symbol | STRING | YES | -recvWindow | LONG | NO | -timestamp | LONG | YES | - - +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| recvWindow | LONG | NO | The assigned value cannot be greater than 60000 | +| timestamp | LONG | YES | | +# Spot account and trading API -# Spot Account/Trade +## Place order (TRADE) -## New Order (TRADE) +**Response ACK:** -> **Response:** -```javascript +```javascript { "symbol": "BTCUSDT", "orderId": 28, @@ -1027,55 +932,50 @@ timestamp | LONG | YES | } ``` -`` -POST /api/v1/order (HMAC SHA256) -`` +`POST /api/v1/order (HMAC SHA256)` -Send in a new order. +Send order -**Weight:** -1 +**Weight:** 1 **Parameters:** -Name | Type | Mandatory | Description ------------- | ------------ | ------------ | ------------ -symbol | STRING | YES | -side | ENUM | YES | -type | ENUM | YES | -timeInForce | ENUM | NO | -quantity | DECIMAL | NO | -quoteOrderQty|DECIMAL|NO| -price | DECIMAL | NO | -newClientOrderId | STRING | NO | A unique id among open orders. Automatically generated if not sent. -stopPrice | DECIMAL | NO | Used with `STOP`, `STOP_MARKET`,`TAKE_PROFIT`, `TAKE_PROFIT_MARKET` orders. -recvWindow | LONG | NO |The value cannot be greater than ```60000``` -timestamp | LONG | YES | - -Additional mandatory parameters based on `type`: - -Type | Additional mandatory parameters ------------- | ------------ -`LIMIT` | `timeInForce`, `quantity`, `price` -`MARKET` | `quantity` or `quoteOrderQty` -`STOP`和`TAKE_PROFIT` | `quantity`, `price`, `stopPrice`   -`STOP_MARKET`和`TAKE_PROFIT_MARKET` | `quantity`, `stopPrice` - - -Other info: - -* `MARKET` `SELL` orders using the `quantity` field specifies the amount of the `base asset` the user wants to sell at the market price. - * For example, sending a `MARKET` `SELL` order on BTCUSDT will specify how much BTC the user is selling. -* `MARKET` `BUY` orders using `quoteOrderQty` specifies the amount the user wants to spend the `quote` asset; the correct `quantity` will be determined based on the market liquidity and `quoteOrderQty`. - * For example, sending a `MARKET` `BUY` order on BTCUSDT specify how much USDT the user is using to buy. The order will buy as many BTC as `quoteOrderQty` USDT can. -* `MARKET` orders using `quoteOrderQty` will not break `LOT_SIZE` filter rules; the order will execute a `quantity` that will have the notional value as close as possible to `quoteOrderQty`. -* same `newClientOrderId` can be accepted only when the previous one is filled, otherwise the order will be rejected. -   - -## Cancel Order (TRADE) +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| side | ENUM | YES | See enum definition: Order direction | +| type | ENUM | YES | See enumeration definition: Order type | +| timeInForce | ENUM | NO | See enum definition: Time in force | +| quantity | DECIMAL | NO | | +| quoteOrderQty | DECIMAL | NO | | +| price | DECIMAL | NO | | +| newClientOrderId | STRING | NO | Client-customized unique order ID. If not provided, one will be generated automatically. | +| stopPrice | DECIMAL | NO | Only STOP, STOP\_MARKET, TAKE\_PROFIT, TAKE\_PROFIT\_MARKET require this parameter | +| recvWindow | LONG | NO | The value cannot be greater than 60000 | +| timestamp | LONG | YES | | + +Depending on the order `type`, certain parameters are mandatory: + +| Type | Mandatory parameters | +| :---- | :---- | +| LIMIT | timeInForce, quantity, price | +| MARKET | quantity or quoteOrderQty | +| STOP and TAKE\_PROFIT | quantity, price, stopPrice | +| STOP\_MARKET and TAKE\_PROFIT\_MARKET | quantity, stopPrice | + +Other information: + +* Place a `MARKET` `SELL` market order; the user controls the amount of base assets to sell with the market order via `QUANTITY`. + * For example, when placing a `MARKET` `SELL` market order on the `BTCUSDT` pair, use `QUANTITY` to let the user specify how much BTC they want to sell. +* For a `MARKET` `BUY` market order, the user controls how much of the quote asset they want to spend with `quoteOrderQty`; `QUANTITY` will be calculated by the system based on market liquidity. For example, when placing a `MARKET` `BUY` market order on the `BTCUSDT` pair, use `quoteOrderQty` to let the user choose how much USDT to use to buy BTC. +* A `MARKET` order using `quoteOrderQty` will not violate the `LOT_SIZE` limit rules; the order will be executed as closely as possible to the given `quoteOrderQty`. +* Unless a previous order has already been filled, orders set with the same `newClientOrderId` will be rejected. + +## Cancel order (TRADE) + +**Response** -> **Response:** -```javascript +```javascript { "symbol": "BTCUSDT", "orderId": 28, @@ -1096,33 +996,29 @@ Other info: } ``` -`` -DELETE /api/v1/order (HMAC SHA256) -`` +`DELETE /api/v1/order (HMAC SHA256)` -Cancel an active order. +Cancel active orders -**Weight:** -1 +**Weight:** 1 **Parameters:** -Name | Type | Mandatory | Description ------------- | ------------ | ------------ | ------------ -symbol | STRING | YES | -orderId | LONG | NO | -origClientOrderId | STRING | NO | -recvWindow | LONG | NO | -timestamp | LONG | YES | - -Either `orderId` or `origClientOrderId` must be sent.   +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| orderId | LONG | NO | | +| origClientOrderId | STRING | NO | | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | +At least one of `orderId` or `origClientOrderId` must be sent. -## Query Order (USER_DATA) +## Query order (USER\_DATA) -> **Response:** +**Response** -```javascript +```javascript { "orderId": 38, "symbol": "ADA25SLP25", @@ -1143,88 +1039,37 @@ Either `orderId` or `origClientOrderId` must be sent.   } ``` -`` -GET /api/v1/order (HMAC SHA256) -`` +`GET /api/v1/order (HMAC SHA256)` -Check an order's status.   +Query order status -**Weight:** -1 +* Please note that orders meeting the following conditions will not be returned: + * The final status of the order is `CANCELED` or `EXPIRED`, **and** + * The order has no trade records, **and** + * Order creation time \+ 7 days \< current time -* These orders will not be found: - * order status is `CANCELED` or `EXPIRED`, **AND** - * order has NO filled trade, **AND** - * created time + 7 days < current time   +**Weight:** 1 **Parameters:** -Name | Type | Mandatory | Description ------------- | ------------ | ------------ | ------------ -symbol | STRING | YES | -orderId | LONG | NO | -origClientOrderId | STRING | NO | -recvWindow | LONG | NO | -timestamp | LONG | YES | +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| orderId | LONG | NO | | +| origClientOrderId | STRING | NO | | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | -Notes: +Note: -* Either `orderId` or `origClientOrderId` must be sent. +* You must send at least one of `orderId` or `origClientOrderId`. +## Current open orders (USER\_DATA) -## current one opne order (USER_DATA) +**Response** -> **Response:** ```javascript -{ - "orderId": 38, - "symbol": "ADA25SLP25", - "status": "NEW", - "clientOrderId": "afMd4GBQyHkHpGWdiy34Li", - "price": "20", - "avgPrice": "12.0000000000000000", - "origQty": "10", - "executedQty": "10", - "cumQuote": "120", - "timeInForce": "GTC", - "type": "LIMIT", - "side": "BUY", - "stopPrice": "0", - "origType": "LIMIT", - "time": 1649913186270, - "updateTime": 1649913186297 -} -``` - -`` -GET /api/v1/openOrder (HMAC SHA256) -`` - -get one current opne order - -**Weight:** -1 - -**Parameters:** - -Name | Type | Mandatory | Description ------------- | ------------ | ------------ | ------------ -symbol | STRING | YES | -orderId | LONG | NO | -origClientOrderId | STRING | NO | -recvWindow | LONG | NO | -timestamp | LONG | YES | - -**Notes:** - -Either `orderId` or `origClientOrderId` must be sent. - - -## Current Open Orders (USER_DATA) - -> **Response:** -```javascript -[ +[ { "orderId": 349661, "symbol": "BNBUSDT", @@ -1243,63 +1088,31 @@ Either `orderId` or `origClientOrderId` must be sent. "time": 1756252940207, "updateTime": 1756252940207, } -] +] ``` -`` -GET /api/v1/openOrders (HMAC SHA256) -`` - -Get all open orders on a symbol. **Careful** when accessing this with no symbol. - -**Weight:** -1 for a single symbol; **40** when the symbol parameter is omitted - -**Parameters:** - -Name | Type | Mandatory | Description ------------- | ------------ | ------------ | ------------ -symbol | STRING | NO | -recvWindow | LONG | NO | -timestamp | LONG | YES | - -* If the symbol is not sent, orders for all symbols will be returned in an array. +`GET /api/v1/openOrders (HMAC SHA256)` - - -## Cancel All Open Order (USER_DATA) - -> **Response:** - -```javascript -{ - "code": 200, - "msg": "The operation of cancel all open order is done." -} -``` - -`` -DEL /api/v1/allOpenOrders (HMAC SHA256) -`` +Retrieve all current open orders for trading pairs. Use calls without a trading pair parameter with caution. **Weight:** -- ***1*** -**Parameters:** +* With symbol ***1*** +* Without ***40***   -Name | Type | Mandatory | Description ------------- | ------------ | ------------ | ------------ -symbol | STRING | YES | -orderIdList | STRING | NO | id array -origClientOrderIdList | STRING | NO | clientOrderId array -recvWindow | LONG | NO | -timestamp | LONG | YES | +**Parameters:** +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | NO | | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | +* If the symbol parameter is not provided, it will return the order books for all trading pairs. -## All Orders (USER_DATA) +## Query all orders (USER\_DATA) -> **Response:** +**Response** ```javascript [ @@ -1324,70 +1137,61 @@ timestamp | LONG | YES | ] ``` -`` -GET /api/v1/allOrders (HMAC SHA256) -`` +`GET /api/v1/allOrders (HMAC SHA256)` -Get all account orders; active, canceled, or filled. +Retrieve all account orders; active, canceled, or completed. -* These orders will not be found: - * created time + 7 days < current time +* Please note that orders meeting the following conditions will not be returned: + * Order creation time \+ 7 days \< current time -**Weight:** -5 +**Weight:** 5 **Parameters:** -Name | Type | Mandatory | Description ------------- | ------------ | ------------ | ------------ -symbol | STRING | YES | -orderId | LONG | NO | -startTime | LONG | NO | -endTime | LONG | NO | -limit | INT | NO | Default 500; max 1000. -recvWindow | LONG | NO | -timestamp | LONG | YES | +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| orderId | LONG | NO | | +| startTime | LONG | NO | | +| endTime | LONG | NO | | +| limit | INT | NO | Default 500; maximum 1000 | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | -**Notes:** +* The maximum query time range must not exceed 7 days. +* By default, query data is from the last 7 days. -* If `orderId` is set, it will get orders >= that `orderId`. Otherwise most recent orders are returned. -* The query time period must be less then 7 days( default as the recent 7 days). ## Account Information (USER_DATA) -## Swap Between Futures and Spot (TRADE) +## Perp-spot transfer (TRADE) -> **Response:** +**Response:** ```javascript { - "tranId": 21841, - "status": "SUCCESS" + "tranId": 21841, //Tran Id + "status": "SUCCESS" //Status } ``` -`` -POST /api/v1/asset/wallet/transfer (HMAC SHA256) -`` +`POST /api/v1/asset/wallet/transfer (HMAC SHA256)` -**Weight:** -5 +**Weight:** 5 **Parameters:** +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| amount | DECIMAL | YES | Quantity | +| asset | STRING | YES | Asset | +| clientTranId | STRING | YES | Transaction ID | +| kindType | STRING | YES | Transaction type | +| timestamp | LONG | YES | Timestamp | -Name | Type | Mandatory | Description ----------------- | ------- | -------- | ---- -amount | DECIMAL | YES | -asset | STRING | YES | -clientTranId | STRING | YES | -kindType | STRING | YES | -recvWindow | LONG | NO | -timestamp | LONG | YES | +* kindType values are FUTURE\_MAIN (perp to spot) and MAIN\_FUTURE (spot to perp) -**Notes:** -* kindType FUTURE_SPOT(future to spot)/SPOT_FUTURE(spot to future) -## Transfer Asset To Other Address (TRADE) +## Transfer asset to other address (TRADE) > **Response:** @@ -1423,7 +1227,7 @@ timestamp | LONG | YES | * If clientTranId is provided, its length must be at least 20 characters. -## Get Withdraw Fee (NONE) +## Get withdraw fee (NONE) > **Response:** ```javascript { @@ -1525,7 +1329,7 @@ const types = { const signature = await signer.signTypedData(domain, types, value) ``` -## Get User Create Apikey Nonce (NONE) +## Get user create apikey nonce (NONE) > **Response:** ```javascript @@ -1552,8 +1356,9 @@ network | STRING | NO | **Notes:** * userOperationType : CREATE_API_KEY * network : For the Solana network, SOL must be provided; otherwise, this field is ignored. +* Rate limit: 60 requests per minute per IP -## Create Apikey (NONE) +## Create apikey (NONE) > **Response:** ```javascript @@ -1598,18 +1403,19 @@ const signature = await signer.signMessage(message); ``` -## Account Information (USER_DATA) +## Account information (USER\_DATA) + +**Response** -> **Response:** ```javascript -{ +{ "feeTier": 0, "canTrade": true, "canDeposit": true, "canWithdraw": true, "canBurnAsset": true, - "updateTime": 0, - "balances": [ + "updateTime": 0, +   "balances": [ { "asset": "BTC", "free": "4723846.89208129", @@ -1624,27 +1430,24 @@ const signature = await signer.signMessage(message); } ``` -`` -GET /api/v1/account (HMAC SHA256) -`` +`GET /api/v1/account (HMAC SHA256)` -Get current account information. +Retrieve current account information -**Weight:** -5 +**Weight:** 5 **Parameters:** -Name | Type | Mandatory | Description ------------- | ------------ | ------------ | ------------ -recvWindow | LONG | NO | -timestamp | LONG | YES | +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | +## Account trade history (USER\_DATA) -## Account Trade List (USER_DATA) +**Response** -> **Response:** -```javascript   +```javascript [ { "symbol": "BNBUSDT", @@ -1665,200 +1468,139 @@ timestamp | LONG | YES | ] ``` -`` -GET /api/v1/userTrades (HMAC SHA256) -`` +`GET /api/v1/userTrades (HMAC SHA256)` -Get trades for a specific account and symbol. +Retrieve the trade history for a specified trading pair of an account -**Weight:** -5 +**Weight:** 5 **Parameters:** -Name | Type | Mandatory | Description ------------- | ------------ | ------------ | ------------ -symbol | STRING | NO | -orderId|LONG|NO| This can only be used in combination with `symbol`. -startTime | LONG | NO | -endTime | LONG | NO | -fromId | LONG | NO | TradeId to fetch from. Default gets most recent trades. -limit | INT | NO | Default 500; max 1000. -recvWindow | LONG | NO | -timestamp | LONG | YES |   - -* 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. -* The parameter `fromId` cannot be sent with `startTime` or `endTime`.     - - - - - - - +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | NO | | +| orderId | LONG | NO | Must be used together with the parameter symbol | +| startTime | LONG | NO | | +| endTime | LONG | NO | | +| fromId | LONG | NO | Starting trade ID. Defaults to fetching the most recent trade. | +| limit | INT | NO | Default 500; maximum 1000 | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +* If both `startTime` and `endTime` are not sent, only data from the last 7 days will be returned. +* The maximum interval between startTime and endTime is 7 days. +* `fromId` cannot be sent together with `startTime` or `endTime`.       --- -# Websocket Market Streams -* The base endpoint is: **wss://sstream.asterdex.com** -* Streams can be accessed either in a single raw stream or in a combined stream -* Raw streams are accessed at **/ws/\** -* Combined streams are accessed at **/stream?streams=\/\/\** -* Combined stream events are wrapped as follows: **{"stream":"\","data":\}** -* All symbols for streams are **lowercase** -* A single connection to **sstream.asterdex.com** is only valid for 24 hours; expect to be disconnected at the 24 hour mark -* The websocket server will send a `ping frame` every 3 minutes. If the websocket server does not receive a `pong frame` back from the connection within a 10 minute period, the connection will be disconnected. Unsolicited `pong frames` are allowed. +# WebSocket market data feed -## Live Subscribing/Unsubscribing to streams +* The base URL for all wss endpoints listed in this document is: **wss://sstream.asterdex.com** +* Streams have either a single raw stream or a combined stream +* Single raw streams format is \*\*/ws/\*\* +* The URL format for combined streams is \*\*/stream?streams=//\*\* +* When subscribing to combined streams, the event payload is wrapped in this format: \*\*{"stream":"","data":}\*\* +* All trading pairs in stream names are **lowercase** +* Each link to **sstream.asterdex.com** is valid for no more than 24 hours; please handle reconnections appropriately +* Every 3 minutes the server sends a ping frame; the client must reply with a pong frame within 10 minutes, otherwise the server will close the connection. The client is allowed to send unpaired pong frames (i.e., the client may send pong frames at a frequency higher than once every 10 minutes to keep the connection alive). -* The following data can be sent through the websocket instance in order to subscribe/unsubscribe from streams. Examples can be seen below. -* The `id` used in the JSON payloads is an unsigned INT used as an identifier to uniquely identify the messages going back and forth. -* In the response, if the `result` received is `null` this means the request sent was a success. - -### Subscribe to a stream - -> **Response** - ```javascript - { - "result": null, - "id": 1 - } - ``` - -* **Request** - - { - "method": "SUBSCRIBE", - "params": - [ - "btcusdt@aggTrade", - "btcusdt@depth" - ], - "id": 1 - } +## Real-time subscribe/unsubscribe data streams +* The following messages can be sent via WebSocket to subscribe or unsubscribe to data streams. Examples are shown below. +* The `id` in the response content is an unsigned integer that serves as the unique identifier for exchanges of information. +* If the `result` in the response content is `null`, it indicates the request was sent successfully. +### Subscribe to a stream -### Unsubscribe to a stream +**Response** -> **Response** - - ```javascript - { - "result": null, - "id": 312 - } - ``` +```javascript +{ + "result": null, + "id": 1 +} +``` +* **Request** { "method": "SUBSCRIBE", "params": \[ "btcusdt@aggTrade", "btcusdt@depth" \], "id": 1 } -* **Request** +### Unsubscribe from a stream - { - "method": "UNSUBSCRIBE", - "params": - [ - "btcusdt@depth" - ], - "id": 312 - } +**Response** +```javascript +{ + "result": null, + "id": 312 +} +``` +* **Request** { "method": "UNSUBSCRIBE", "params": \[ "btcusdt@depth" \], "id": 312 } -### Listing Subscriptions +### Subscribed to the feed -> **Response** - - ```javascript - { - "result": [ - "btcusdt@aggTrade" - ], - "id": 3 - } - ``` +**Response** +```javascript +{ + "result": [ + "btcusdt@aggTrade" + ], + "id": 3 +} +``` -* **Request** +* **Request** + + { "method": "LIST\_SUBSCRIPTIONS", "id": 3 } - { - "method": "LIST_SUBSCRIPTIONS", - "id": 3 - } - +### Set properties +Currently, the only configurable property is whether to enable the `combined` ("combined") stream. When connecting using `/ws/` ("raw stream"), the combined property is set to `false`, while connecting using `/stream/` sets the property to `true`. -### Setting Properties -Currently, the only property can be set is to set whether `combined` stream payloads are enabled or not. -The combined property is set to `false` when connecting using `/ws/` ("raw streams") and `true` when connecting using `/stream/`. +**Response** -> **Response** - - ```javascript +```javascript { - "result": null, - "id": 5 +"result": null, +"id": 5 } - ``` - -* **Request** - - { - "method": "SET_PROPERTY", - "params": - [ - "combined", - true - ], - "id": 5 - } - +``` +* **Request** { "method": "SET\_PROPERTY" "params": \[ "combined", true \], "id": 5 } +### Retrieve properties -### Retrieving Properties - -> **Response** - ```javascript - { - "result": true, // Indicates that combined is set to true. - "id": 2 - } - ``` - -* **Request** - - { - "method": "GET_PROPERTY", - "params": - [ - "combined" - ], - "id": 2 - } - - +**Response** +```javascript +{ + "result": true, // Indicates that combined is set to true. + "id": 2 +} +``` -### Error Messages +* **Request** + + { "method": "GET\_PROPERTY", "params": \[ "combined" \], "id": 2 } -Error Message | Description ----|--- -{"code": 0, "msg": "Unknown property", "id": '%s'} | Parameter used in the `SET_PROPERTY` or `GET_PROPERTY` was invalid -{"code": 1, "msg": "Invalid value type: expected Boolean", "id": '%s'} | Value should only be `true` or `false` -{"code": 2, "msg": "Invalid request: property name must be a string"}| Property name provided was invalid -{"code": 2, "msg": "Invalid request: request ID must be an unsigned integer"}| Parameter `id` had to be provided or the value provided in the `id` parameter is an unsupported type -{"code": 2, "msg": "Invalid request: unknown variant %s, expected one of `SUBSCRIBE`, `UNSUBSCRIBE`, `LIST_SUBSCRIPTIONS`, `SET_PROPERTY`, `GET_PROPERTY` at line 1 column 28"} | Possible typo in the provided method or provided method was neither of the expected values -{"code": 2, "msg": "Invalid request: too many parameters"}| Unnecessary parameters provided in the data -{"code": 2, "msg": "Invalid request: property name must be a string"} | Property name was not provided -{"code": 2, "msg": "Invalid request: missing field `method` at line 1 column 73"} | `method` was not provided in the data -{"code":3,"msg":"Invalid JSON: expected value at line %s column %s"} | JSON data sent has incorrect syntax. +\#\#\# Error message +| Error message | Description | +| :---- | :---- | +| {"code": 0, "msg": "Unknown property"} | Parameters applied in SET\_PROPERTY or GET\_PROPERTY are invalid | +| {"code": 1, "msg": "Invalid value type: expected Boolean", "id": '%s'} | Only true or false are accepted | +| {"code": 2, "msg": "Invalid request: property name must be a string"} | The provided attribute name is invalid | +| {"code": 2, "msg": "Invalid request: request ID must be an unsigned integer"} | Parameter ID not provided or ID has an invalid type | +| {"code": 2, "msg": "Invalid request: unknown variant %s, expected one of SUBSCRIBE, UNSUBSCRIBE, LIST\_SUBSCRIPTIONS, SET\_PROPERTY, GET\_PROPERTY at line 1 column 28"} | Typo warning, or the provided value is not of the expected type | +| {"code": 2, "msg": "Invalid request: too many parameters"} | Unnecessary parameters were provided in the data | +| {"code": 2, "msg": "Invalid request: property name must be a string"} | Property name not provided | +| {"code": 2, "msg": "Invalid request: missing field method at line 1 column 73"} | Data did not provide method | +| {"code":3,"msg":"Invalid JSON: expected value at line %s column %s"} | JSON syntax error | -## Aggregate Trade Streams +## Collection transaction flow +**Payload:** -> **Payload:** ```javascript { "e": "aggTrade", // Event type @@ -1875,17 +1617,16 @@ Error Message | Description } ``` -The Aggregate Trade Streams push trade information that is aggregated for a single taker order. - -**Stream Name:** `@aggTrade` +The collection transaction stream pushes transaction information and is an aggregation of a single order. -**Update Speed:** Real-time +**Stream name:** `@aggTrade` +**Update speed:** real-time -## Trade Streams +## Tick-by-tick trades +**Payload:** -> **Payload:** ```javascript { "e": "trade", // Event type @@ -1899,21 +1640,14 @@ The Aggregate Trade Streams push trade information that is aggregated for a sing } ``` -The Trade Streams push raw trade information; each trade has a unique buyer and seller. - -**Stream Name:** `@trade` - -**Update Speed:** Real-time - - +**Stream name:** `@trade` +Each trade stream pushes the details of every individual trade. A **trade**, also called a transaction, is defined as a match between exactly one taker and one maker. +## K-line streams +**Payload:** -## Kline/Candlestick Streams - - -> **Payload:** ```javascript { "e": "kline", // Event type @@ -1941,38 +1675,36 @@ The Trade Streams push raw trade information; each trade has a unique buyer and } ``` -The Kline/Candlestick Stream push updates to the current klines/candlestick every second. +The K-line stream pushes per-second updates for the requested type of K-line (the latest candle). -**Stream Name:** `@kline_` +**Stream name:** `@kline_` -**Update Speed:** 2000ms +**Update speed:** 2000ms -**Kline/Candlestick chart intervals:** +**K-line interval parameter:** -m -> minutes; h -> hours; d -> days; w -> weeks; M -> months +m (minutes), h (hours), d (days), w (weeks), M (months) -* 1m -* 3m -* 5m -* 15m -* 30m -* 1h -* 2h -* 4h -* 6h -* 8h -* 12h -* 1d -* 3d -* 1w +* 1m +* 3m +* 5m +* 15m +* 30m +* 1h +* 2h +* 4h +* 6h +* 8h +* 12h +* 1d +* 3d +* 1w * 1M +## Simplified ticker by symbol +**Payload:** - -## Individual Symbol Mini Ticker Stream - -> **Payload:** ```javascript { "e": "24hrMiniTicker", // Event type @@ -1987,18 +1719,16 @@ m -> minutes; h -> hours; d -> days; w -> weeks; M -> months } ``` -24hr rolling window mini-ticker statistics. These are NOT the statistics of the UTC day, but a 24hr rolling window for the previous 24hrs. +Refreshed simplified 24-hour ticker information by symbol -**Stream Name:** `@miniTicker` +**Stream name:** `@miniTicker` -**Update Speed:** 1000ms +**Update speed:** 1000ms +## Compact tickers for all symbols in the entire market +**Payload:** - -## All Market Mini Tickers Stream - -> **Payload:** ```javascript [ { @@ -2007,18 +1737,16 @@ m -> minutes; h -> hours; d -> days; w -> weeks; M -> months ] ``` -24hr rolling window mini-ticker statistics for all symbols that changed in an array. These are NOT the statistics of the UTC day, but a 24hr rolling window for the previous 24hrs. Note that only tickers that have changed will be present in the array. - -**Stream Name:** `!miniTicker@arr` +Same as above, but pushes all trading pairs. Note that only updated tickers will be pushed. -**Update Speed:** 1000ms +**Stream name:** \!miniTicker@arr +**Update speed:** 1000ms +## Full ticker per symbol -## Individual Symbol Ticker Streams +**Payload:** - -> **Payload:** ```javascript { "e": "24hrTicker", // Event type @@ -2042,17 +1770,16 @@ m -> minutes; h -> hours; d -> days; w -> weeks; M -> months } ``` +Pushes per-second tag statistics for a single trading pair over a rolling 24-hour window. -24hr rolling window ticker statistics for a single symbol. These are NOT the statistics of the UTC day, but a 24hr rolling window for the previous 24hrs. - -**Stream Name:** `@ticker` +**Stream name:** `@ticker` -**Update Speed:** 1000ms +**Update speed:** 1000ms +## Complete ticker for all trading pairs on the entire market -## All Market Tickers Stream +**Payload:** -> **Payload:** ```javascript [ { @@ -2061,19 +1788,16 @@ m -> minutes; h -> hours; d -> days; w -> weeks; M -> months ] ``` -24hr rolling window ticker statistics for all symbols that changed in an array. These are NOT the statistics of the UTC day, but a 24hr rolling window for the previous 24hrs. Note that only tickers that have changed will be present in the array. - -**Stream Name:** `!ticker@arr` - -**Update Speed:** 1000ms +Pushes the full 24-hour refreshed ticker information for all trading pairs across the entire market. Note that tickers without updates will not be pushed. +**Stream name:** `!ticker@arr` +**Update speed:** 1000ms +## Best order book information by symbol +**Payload:** -## Individual Symbol Book Ticker Streams - -> **Payload:** ```javascript { "u":400900217, // order book updateId @@ -2085,37 +1809,32 @@ m -> minutes; h -> hours; d -> days; w -> weeks; M -> months } ``` +Real-time push of best order book information for the specified trading pair -Pushes any update to the best bid or ask's price or quantity in real-time for a specified symbol. - -**Stream Name:** `@bookTicker` - -**Update Speed:** Real-time - +**Stream name:** `@bookTicker` +**Update speed:** Real-time +## Best order book information across the entire market +**Payload:** -## All Book Tickers Stream - -> **Payload:** ```javascript { - // Same as @bookTicker payload + // 同 @bookTicker payload } ``` -Pushes any update to the best bid or ask's price or quantity in real-time for all symbols. - -**Stream Name:** `!bookTicker` +Real-time push of the best order information for all trading pairs -**Update Speed:** Real-time +**Stream name:** `!bookTicker` +**Update speed:** Real-time +## Limited depth information -## Partial Book Depth Streams +**Payload:** -> **Payload:** ```javascript { "e": "depthUpdate", // Event type @@ -2137,23 +1856,20 @@ Pushes any update to the best bid or ask's price or quantity in real-time for al "100" // Quantity ] ] -} +} ``` -Top **** bids and asks, Valid **** are 5, 10, or 20. - -**Stream Names:** `@depth` OR `@depth@100ms`. - -**Update Speed:** 1000ms or 100ms - +Limited depth information pushed every second or every 100 milliseconds. Levels indicate how many levels of bid/ask information, optional 5/10/20 levels. +**Stream names:** `@depth` or `@depth@100ms`. +**Update speed:** 1000ms or 100ms -## Diff. Depth Stream +## Incremental depth information +**Payload:** -> **Payload:** -```javascript +```javascript { "e": "depthUpdate", // Event type "E": 123456789, // Event time @@ -2174,122 +1890,103 @@ Top **** bids and asks, Valid **** are 5, 10, or 20. "100" // Quantity ] ] -} +} ``` -Order book price and quantity depth updates used to locally manage an order book. - -**Stream Name:** `@depth` OR `@depth@100ms` - -**Update Speed:** 1000ms or 100ms - - - -## How to manage a local order book correctly -1. Open a stream to **wss://sstream.asterdex.com/ws/bnbbtc@depth**. -2. Buffer the events you receive from the stream. -3. Get a depth snapshot from **https://sapi.asterdex.com/v1/depth?symbol=BNBBTC&limit=1000** . -4. Drop any event where `u` is <= `lastUpdateId` in the snapshot. -5. The first processed event should have `U` <= `lastUpdateId`+1 **AND** `u` >= `lastUpdateId`+1. -6. While listening to the stream, each new event's `U` should be equal to the previous event's `u`+1. -7. The data in each event is the **absolute** quantity for a price level. -8. If the quantity is 0, **remove** the price level. -9. Receiving an event that removes a price level that is not in your local order book can happen and is normal. - +Pushes the changed parts of the orderbook (if any) every second or every 100 milliseconds +**Stream name:** `@depth` or `@depth@100ms` +**Update speed:** 1000ms or 100ms +## How to correctly maintain a local copy of an order book +1. Subscribe to **wss://sstream.asterdex.com/ws/bnbbtc@depth** +2. Start caching the received updates. For the same price level, later updates overwrite earlier ones. +3. Fetch the REST endpoint [**https://sapi.asterdex.com/api/v1/depth?symbol=BNBBTC\&limit=1000**](https://sapi.asterdex.com/api/v1/depth?symbol=BNBBTC&limit=1000) to obtain a 1000-level depth snapshot +4. Discard from the currently cached messages those with `u` \<= the `lastUpdateId` obtained in step 3 (drop older, expired information) +5. Apply the depth snapshot to your local order book copy, and resume updating the local copy from the first WebSocket event whose `U` \<= `lastUpdateId`\+1 **and** `u` \>= `lastUpdateId`\+1 +6. Each new event’s `U` should equal exactly the previous event’s `u`\+1; otherwise packets may have been lost \- restart initialization from step 3 +7. The order quantity in each event represents the current order quantity at that price as an **absolute value**, not a relative change +8. If the order quantity at a given price is 0, it means the orders at that price have been canceled or filled, and that price level should be removed -# User Data Streams +# WebSocket account information push +* The base URL for the API endpoints listed in this document is: [**https://sapi.asterdex.com**](https://sapi.asterdex.com) +* The `listenKey` used to subscribe to account data is valid for 60 minutes from the time of creation +* You can extend the 60-minute validity of a `listenKey` by sending a `PUT` request +* You can immediately close the current data stream and invalidate the `listenKey` by sending a `DELETE` for a `listenKey` +* Sending a `POST` on an account with a valid `listenKey` will return the currently valid `listenKey` and extend its validity by 60 minutes +* The WebSocket interface baseurl: **wss://sstream.asterdex.com** +* The stream name for subscribing to the user account data stream is \*\*/ws/\*\* +* Each connection is valid for no more than 24 hours; please handle disconnections and reconnections appropriately -* The base API endpoint is: **https://sapi.asterdex.com** -* A User Data Stream `listenKey` is valid for 60 minutes after creation. -* Doing a `PUT` on a `listenKey` will extend its validity for 60 minutes. -* Doing a `DELETE` on a `listenKey` will close the stream and invalidate the `listenKey`. -* Doing a `POST` on an account with an active `listenKey` will return the currently active `listenKey` and extend its validity for 60 minutes. -* The base websocket endpoint is: **wss://sstream.asterdex.com** -* User Data Streams are accessed at **/ws/\** -* A single connection to **sstream.asterdex.com** is only valid for 24 hours; expect to be disconnected at the 24 hour mark +## Listen Key (spot account) +### Generate Listen Key (USER\_STREAM) -## LISTEN KEY +**Response** -### Create a ListenKey (USER_STREAM) - -> **Response:** ```javascript { "listenKey": "pqia91ma19a5s61cv6a81va65sdf19v8a65a1a5s61cv6a81va65sdf19v8a65a1" } ``` +`POST /api/v1/listenKey` -`` -POST /api/v1/listenKey -`` +Start a new data stream. The data stream will be closed after 60 minutes unless a keepalive is sent. If the account already has a valid `listenKey`, that `listenKey` will be returned and its validity extended by 60 minutes. -Start a new user data stream. The stream will close after 60 minutes unless a keepalive is sent. If the account has an active `listenKey`, that `listenKey` will be returned and its validity will be extended for 60 minutes. +**Weight:** 1 -**Weight:** -1 +**Parameters:** NONE -**Parameters:** -NONE +### Extend Listen Key validity period (USER\_STREAM) -### Ping/Keep-alive a ListenKey (USER_STREAM) +**Response** -> **Response:** ```javascript {} ``` -`` -PUT /api/v1/listenKey -`` +`PUT /api/v1/listenKey` -Keepalive a user data stream to prevent a time out. User data streams will close after 60 minutes. It's recommended to send a ping about every 30 minutes. +Validity extended to 60 minutes after this call. It is recommended to send a ping every 30 minutes. -**Weight:** -1 +**Weight:** 1 **Parameters:** -Name | Type | Mandatory | Description ------------- | ------------ | ------------ | ------------ -listenKey | STRING | YES +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| listenKey | STRING | YES | | +### Close Listen Key (USER\_STREAM) -### Close a ListenKey (USER_STREAM) +**Response** -> **Response:** ```javascript {} ``` -`` -DELETE /api/v1/listenKey -`` +`DELETE /api/v1/listenKey` -Close out a user data stream. +Close user data stream -**Weight:** -1 +**Weight:** 1 **Parameters:** -Name | Type | Mandatory | Description ------------- | ------------ | ------------ | ------------ -listenKey | STRING | YES - +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| listenKey | STRING | YES | | +## Payload: ACCOUNT\_UPDATE -## Payload: Balance Update +An `outboundAccountPosition` event is sent whenever an account balance changes; it contains the assets that may have changed due to the event that generated the balance update. -`outboundAccountPosition` is sent any time an account balance has changed and contains the assets that were possibly changed by the event that generated the balance change. +**Payload** -> **Payload:** ```javascript { "B":[ //Balance @@ -2311,16 +2008,15 @@ listenKey | STRING | YES } ``` - ## Payload: Order Update -Orders are updated with the `executionReport` event. +Orders are updated via the `executionReport` event -> **Payload:**   +**Payload** ```javascript { - "s":"ADA25SLP25",   // symbol + "s":"ADA25SLP25",   // symbol "c":"Xzh0gnxT41PStbwqOtXnjD",  // client order id "S":"SELL",   // order direction "o":"LIMIT",   // order type @@ -2347,422 +2043,503 @@ Orders are updated with the `executionReport` event. "Q":"0",   // Quote Order Qty "e":"executionReport",   // event "E":1649926447209  // event time -} +} ``` -**Execution types:** - -* NEW - The order has been accepted into the engine. -* CANCELED - The order has been canceled by the user. -* REPLACED (currently unused) -* TRADE - Part of the order or all of the order's quantity has filled. -* EXPIRED - The order was canceled according to the order type's rules (e.g. LIMIT FOK orders with no fill, LIMIT IOC or MARKET orders that partially fill) or by the exchange, (e.g. orders canceled during maintenance) +**Execution type:** +* NEW \- New Order +* CANCELED \- Order canceled +* REJECTED \- New order was rejected +* TRADE \- Order had a new fill +* EXPIRED \- Order expired (based on the order's Time In Force parameter) +\#错误代码 -# Error Codes - -> Here is the error JSON payload: +error JSON payload: ```javascript { -"code":-1121, -"msg":"Invalid symbol." + "code":-1121, + "msg":"Invalid symbol." } ``` -Errors consist of two parts: an error code and a message. -Codes are universal,but messages can vary. +Errors consist of two parts: an error code and a message. The code is standardized, but the message may vary. +## 10xx \- General server or network issues +### \-1000 UNKNOWN +* An unknown error occurred while processing the request. -## 10xx - General Server or Network issues -### -1000 UNKNOWN -* An unknown error occured while processing the request. +### \-1001 DISCONNECTED -### -1001 DISCONNECTED * Internal error; unable to process your request. Please try again. -### -1002 UNAUTHORIZED +### \-1002 UNAUTHORIZED + * You are not authorized to execute this request. -### -1003 TOO_MANY_REQUESTS -* Too many requests queued. -* Too many requests; please use the websocket for live updates. -* Too many requests; current limit is %s requests per minute. Please use the websocket for live updates to avoid polling the API. -* Way too many requests; IP banned until %s. Please use the websocket for live updates to avoid bans. +### \-1003 TOO\_MANY\_REQUESTS + +* Too many requests queued. +* Too many requests; please use the WebSocket for live updates. +* Too many requests; current limit is %s requests per minute. Please use the WebSocket for live updates to avoid polling the API. +* Too many request weights; IP banned until %s. Please use the WebSocket for live updates to avoid bans. + +### \-1004 DUPLICATE\_IP -### -1004 DUPLICATE_IP -* This IP is already on the white list +* This IP is already on the white list. -### -1005 NO_SUCH_IP -* No such IP has been white listed +### \-1005 NO\_SUCH\_IP + +* No such IP has been whitelisted. + +### \-1006 UNEXPECTED\_RESP -### -1006 UNEXPECTED_RESP * An unexpected response was received from the message bus. Execution status unknown. -### -1007 TIMEOUT +### \-1007 TIMEOUT + * Timeout waiting for response from backend server. Send status unknown; execution status unknown. -### -1010 ERROR_MSG_RECEIVED -* ERROR_MSG_RECEIVED. +### \-1014 UNKNOWN\_ORDER\_COMPOSITION -### -1011 NON_WHITE_LIST -* This IP cannot access this route. +* The current order parameter combination is not supported. -### -1013 INVALID_MESSAGE -* INVALID_MESSAGE. +### \-1015 TOO\_MANY\_ORDERS -### -1014 UNKNOWN_ORDER_COMPOSITION -* Unsupported order combination. +* Too many new orders. +* Too many new orders; the current limit is %s orders per %s. -### -1015 TOO_MANY_ORDERS -* Too many new orders. -* Too many new orders; current limit is %s orders per %s. +### \-1016 SERVICE\_SHUTTING\_DOWN -### -1016 SERVICE_SHUTTING_DOWN * This service is no longer available. -### -1020 UNSUPPORTED_OPERATION +### \-1020 UNSUPPORTED\_OPERATION + * This operation is not supported. -### -1021 INVALID_TIMESTAMP -* Timestamp for this request is outside of the recvWindow. -* Timestamp for this request was 1000ms ahead of the server's time. +### \-1021 INVALID\_TIMESTAMP + +* Timestamp for this request is outside of the recvWindow. +* The timestamp for this request was 1000ms ahead of the server's time. + +### \-1022 INVALID\_SIGNATURE + +* The signature for this request is invalid. -### -1022 INVALID_SIGNATURE -* Signature for this request is not valid. +### \-1023 START\_TIME\_GREATER\_THAN\_END\_TIME -### -1023 START_TIME_GREATER_THAN_END_TIME -* Start time is greater than end time. +* The start time in the parameters is after the end time. +## 11xx \- Request issues -## 11xx - Request issues -### -1100 ILLEGAL_CHARS -* Illegal characters found in a parameter. -* Illegal characters found in parameter '%s'; legal range is '%s'. +### \-1100 ILLEGAL\_CHARS -### -1101 TOO_MANY_PARAMETERS -* Too many parameters sent for this endpoint. -* Too many parameters; expected '%s' and received '%s'. +* Illegal characters found in a parameter. +* Illegal characters found in parameter %s; legal range is %s. + +### \-1101 TOO\_MANY\_PARAMETERS + +* Too many parameters sent for this endpoint. +* Too many parameters; expected %s and received %s. * Duplicate values for a parameter detected. -### -1102 MANDATORY_PARAM_EMPTY_OR_MALFORMED -* A mandatory parameter was not sent, was empty/null, or malformed. -* Mandatory parameter '%s' was not sent, was empty/null, or malformed. -* Param '%s' or '%s' must be sent, but both were empty/null! +### \-1102 MANDATORY\_PARAM\_EMPTY\_OR\_MALFORMED + +* A mandatory parameter was not sent, was empty/null, or malformed. +* Mandatory parameter %s was not sent, was empty/null, or malformed. +* Param %s or %s must be sent, but both were empty/null. + +### \-1103 UNKNOWN\_PARAM -### -1103 UNKNOWN_PARAM * An unknown parameter was sent. -### -1104 UNREAD_PARAMETERS -* Not all sent parameters were read. -* Not all sent parameters were read; read '%s' parameter(s) but was sent '%s'. +### \-1104 UNREAD\_PARAMETERS -### -1105 PARAM_EMPTY -* A parameter was empty. -* Parameter '%s' was empty. +* Not all sent parameters were read. +* Not all sent parameters were read; read %s parameter(s) but %s parameter(s) were sent. -### -1106 PARAM_NOT_REQUIRED -* A parameter was sent when not required. -* Parameter '%s' sent when not required. +### \-1105 PARAM\_EMPTY -### -1108 BAD_ASSET -* Invalid asset. +* A parameter was empty. +* Parameter %s was empty. -### -1109 BAD_ACCOUNT -* Invalid account. +### \-1106 PARAM\_NOT\_REQUIRED -### -1110 BAD_INSTRUMENT_TYPE -* Invalid symbolType. +* A parameter was sent when not required.  -### -1111 BAD_PRECISION -* Precision is over the maximum defined for this asset. +### \-1111 BAD\_PRECISION  -### -1112 NO_DEPTH -* No orders on book for symbol. +* The precision exceeds the maximum defined for this asset. -### -1113 WITHDRAW_NOT_NEGATIVE -* Withdrawal amount must be negative. +### \-1112 NO\_DEPTH + +* No open orders for the trading pair. + +### \-1114 TIF\_NOT\_REQUIRED -### -1114 TIF_NOT_REQUIRED * TimeInForce parameter sent when not required. -### -1115 INVALID_TIF +### \-1115 INVALID\_TIF + * Invalid timeInForce. -### -1116 INVALID_ORDER_TYPE +### \-1116 INVALID\_ORDER\_TYPE + * Invalid orderType. -### -1117 INVALID_SIDE -* Invalid side. +### \-1117 INVALID\_SIDE + +* Invalid order side. + +### \-1118 EMPTY\_NEW\_CL\_ORD\_ID -### -1118 EMPTY_NEW_CL_ORD_ID * New client order ID was empty. -### -1119 EMPTY_ORG_CL_ORD_ID -* Original client order ID was empty. +### \-1119 EMPTY\_ORG\_CL\_ORD\_ID + +* The client’s custom order ID is empty. + +### \-1120 BAD\_INTERVAL -### -1120 BAD_INTERVAL -* Invalid interval. +* Invalid time interval. -### -1121 BAD_SYMBOL -* Invalid symbol. +### \-1121 BAD\_SYMBOL + +* Invalid trading pair. + +### \-1125 INVALID\_LISTEN\_KEY -### -1125 INVALID_LISTEN_KEY * This listenKey does not exist. -### -1127 MORE_THAN_XX_HOURS -* Lookup interval is too big. +### \-1127 MORE\_THAN\_XX\_HOURS + +* The query interval is too large. * More than %s hours between startTime and endTime. -### -1128 OPTIONAL_PARAMS_BAD_COMBO -* Combination of optional parameters invalid. +### \-1128 OPTIONAL\_PARAMS\_BAD\_COMBO  -### -1130 INVALID_PARAMETER -* Invalid data sent for a parameter. -* Data sent for parameter '%s' is not valid. +* Combination of optional parameters invalid.  -### -1136 INVALID_NEW_ORDER_RESP_TYPE -* Invalid newOrderRespType. +### \-1130 INVALID\_PARAMETER  +* The parameter sent contains invalid data. +* Data sent for parameter %s is not valid.  -## 20xx - Processing Issues +### \-1136 INVALID\_NEW\_ORDER\_RESP\_TYPE  -### -2010 NEW_ORDER_REJECTED -* NEW_ORDER_REJECTED +* Invalid newOrderRespType.  -### -2011 CANCEL_REJECTED -* CANCEL_REJECTED +## 20xx \- Processing Issues  + +### \-2010 NEW\_ORDER\_REJECTED  + +* New order rejected. + +### \-2011 CANCEL\_REJECTED + +* Order cancellation rejected. + +### \-2013 NO\_SUCH\_ORDER -### -2013 NO_SUCH_ORDER * Order does not exist. -### -2014 BAD_API_KEY_FMT +### \-2014 BAD\_API\_KEY\_FMT + * API-key format invalid. -### -2015 REJECTED_MBX_KEY -* Invalid API-key, IP, or permissions for action. +### \-2015 REJECTED\_MBX\_KEY + +* Invalid API key, IP, or permissions for action. + +### \-2016 NO\_TRADING\_WINDOW -### -2016 NO_TRADING_WINDOW * No trading window could be found for the symbol. Try ticker/24hrs instead. -### -2018 BALANCE_NOT_SUFFICIENT +### \-2018 BALANCE\_NOT\_SUFFICIENT + * Balance is insufficient. -### -2020 UNABLE_TO_FILL +### \-2020 UNABLE\_TO\_FILL + * Unable to fill. -### -2021 ORDER_WOULD_IMMEDIATELY_TRIGGER +### \-2021 ORDER\_WOULD\_IMMEDIATELY\_TRIGGER + * Order would immediately trigger. -### -2022 REDUCE_ONLY_REJECT +### \-2022 REDUCE\_ONLY\_REJECT + * ReduceOnly Order is rejected. -### -2024 POSITION_NOT_SUFFICIENT +### \-2024 POSITION\_NOT\_SUFFICIENT + * Position is not sufficient. -### -2025 MAX_OPEN_ORDER_EXCEEDED -* Reach max open order limit. +### \-2025 MAX\_OPEN\_ORDER\_EXCEEDED + +* Reached max open order limit. + +### \-2026 REDUCE\_ONLY\_ORDER\_TYPE\_NOT\_SUPPORTED -### -2026 REDUCE_ONLY_ORDER_TYPE_NOT_SUPPORTED * This OrderType is not supported when reduceOnly. +## 40xx \- Filters and other Issues + +### \-4000 INVALID\_ORDER\_STATUS -## 40xx - Filters and other Issues -### -4000 INVALID_ORDER_STATUS * Invalid order status. -### -4001 PRICE_LESS_THAN_ZERO -* Price less than 0. +### \-4001 PRICE\_LESS\_THAN\_ZERO + +* Price less than 0\. + +### \-4002 PRICE\_GREATER\_THAN\_MAX\_PRICE -### -4002 PRICE_GREATER_THAN_MAX_PRICE * Price greater than max price. -### -4003 QTY_LESS_THAN_ZERO +### \-4003 QTY\_LESS\_THAN\_ZERO + * Quantity less than zero. -### -4004 QTY_LESS_THAN_MIN_QTY -* Quantity less than min quantity. +### \-4004 QTY\_LESS\_THAN\_MIN\_QTY + +* Quantity less than minimum quantity. + +### \-4005 QTY\_GREATER\_THAN\_MAX\_QTY + +* Quantity greater than maximum quantity. + +### \-4006 STOP\_PRICE\_LESS\_THAN\_ZERO -### -4005 QTY_GREATER_THAN_MAX_QTY -* Quantity greater than max quantity. +* Stop price less than zero. -### -4006 STOP_PRICE_LESS_THAN_ZERO -* Stop price less than zero. +### \-4007 STOP\_PRICE\_GREATER\_THAN\_MAX\_PRICE -### -4007 STOP_PRICE_GREATER_THAN_MAX_PRICE -* Stop price greater than max price. +* Stop price greater than max price. + +### \-4008 TICK\_SIZE\_LESS\_THAN\_ZERO -### -4008 TICK_SIZE_LESS_THAN_ZERO * Tick size less than zero. -### -4009 MAX_PRICE_LESS_THAN_MIN_PRICE +### \-4009 MAX\_PRICE\_LESS\_THAN\_MIN\_PRICE + * Max price less than min price. -### -4010 MAX_QTY_LESS_THAN_MIN_QTY -* Max qty less than min qty. +### \-4010 MAX\_QTY\_LESS\_THAN\_MIN\_QTY + +* Maximum quantity less than minimum quantity. + +### \-4011 STEP\_SIZE\_LESS\_THAN\_ZERO -### -4011 STEP_SIZE_LESS_THAN_ZERO * Step size less than zero. -### -4012 MAX_NUM_ORDERS_LESS_THAN_ZERO -* Max mum orders less than zero. +### \-4012 MAX\_NUM\_ORDERS\_LESS\_THAN\_ZERO + +* Maximum order quantity less than 0\. + +### \-4013 PRICE\_LESS\_THAN\_MIN\_PRICE + +* Price less than minimum price. -### -4013 PRICE_LESS_THAN_MIN_PRICE -* Price less than min price. +### \-4014 PRICE\_NOT\_INCREASED\_BY\_TICK\_SIZE -### -4014 PRICE_NOT_INCREASED_BY_TICK_SIZE * Price not increased by tick size. -### -4015 INVALID_CL_ORD_ID_LEN -* Client order id is not valid. -* Client order id length should not be more than 36 chars +### \-4015 INVALID\_CL\_ORD\_ID\_LEN + +* Client order ID is not valid. +* Client order ID length should not be more than 36 characters. + +### \-4016 PRICE\_HIGHTER\_THAN\_MULTIPLIER\_UP -### -4016 PRICE_HIGHTER_THAN_MULTIPLIER_UP * Price is higher than mark price multiplier cap. -### -4017 MULTIPLIER_UP_LESS_THAN_ZERO +### \-4017 MULTIPLIER\_UP\_LESS\_THAN\_ZERO + * Multiplier up less than zero. -### -4018 MULTIPLIER_DOWN_LESS_THAN_ZERO +### \-4018 MULTIPLIER\_DOWN\_LESS\_THAN\_ZERO + * Multiplier down less than zero. -### -4019 COMPOSITE_SCALE_OVERFLOW +### \-4019 COMPOSITE\_SCALE\_OVERFLOW + * Composite scale too large. -### -4020 TARGET_STRATEGY_INVALID -* Target strategy invalid for orderType '%s',reduceOnly '%b'. +### \-4020 TARGET\_STRATEGY\_INVALID + +* Target strategy invalid for orderType %s, reduceOnly %b' + +### \-4021 INVALID\_DEPTH\_LIMIT + +* Invalid depth limit. +* %s is not a valid depth limit. -### -4021 INVALID_DEPTH_LIMIT -* Invalid depth limit. -* '%s' is not valid depth limit. +### \-4022 WRONG\_MARKET\_STATUS -### -4022 WRONG_MARKET_STATUS -* market status sent is not valid. +* Market status sent is not valid. -### -4023 QTY_NOT_INCREASED_BY_STEP_SIZE -* Qty not increased by step size. +### \-4023 QTY\_NOT\_INCREASED\_BY\_STEP\_SIZE + +* The increment of the quantity is not a multiple of the step size. + +### \-4024 PRICE\_LOWER\_THAN\_MULTIPLIER\_DOWN -### -4024 PRICE_LOWER_THAN_MULTIPLIER_DOWN * Price is lower than mark price multiplier floor. -### -4025 MULTIPLIER_DECIMAL_LESS_THAN_ZERO +### \-4025 MULTIPLIER\_DECIMAL\_LESS\_THAN\_ZERO + * Multiplier decimal less than zero. -### -4026 COMMISSION_INVALID -* Commission invalid. -* `%s` less than zero. -* `%s` absolute value greater than `%s` +### \-4026 COMMISSION\_INVALID + +* Commission invalid. +* Incorrect profit value. +* `%s` less than zero. +* `%s` absolute value greater than `%s`. + +### \-4027 INVALID\_ACCOUNT\_TYPE -### -4027 INVALID_ACCOUNT_TYPE * Invalid account type. -### -4029 INVALID_TICK_SIZE_PRECISION -* Tick size precision is invalid. +### \-4029 INVALID\_TICK\_SIZE\_PRECISION + +* Tick size precision is invalid. +* Price decimal precision is incorrect. + +### \-4030 INVALID\_STEP\_SIZE\_PRECISION -### -4030 INVALID_STEP_SIZE_PRECISION -* Step size precision is invalid. +* The number of decimal places for the step size is incorrect. + +### \-4031 INVALID\_WORKING\_TYPE -### -4031 INVALID_WORKING_TYPE -* Invalid parameter working type * Invalid parameter working type: `%s` -### -4032 EXCEED_MAX_CANCEL_ORDER_SIZE -* Exceed maximum cancel order size. +### \-4032 EXCEED\_MAX\_CANCEL\_ORDER\_SIZE + +* Exceeds the maximum order quantity that can be canceled. * Invalid parameter working type: `%s` -### -4044 INVALID_BALANCE_TYPE -* Balance Type is invalid. +### \-4044 INVALID\_BALANCE\_TYPE + +* The balance type is incorrect. + +### \-4045 MAX\_STOP\_ORDER\_EXCEEDED + +* Reached the stop-loss order limit. + +### \-4055 AMOUNT\_MUST\_BE\_POSITIVE + +* The quantity must be a positive integer. + +### \-4056 INVALID\_API\_KEY\_TYPE -### -4045 MAX_STOP_ORDER_EXCEEDED -* Reach max stop order limit. +* The API key type is invalid. -### -4055 AMOUNT_MUST_BE_POSITIVE -* Amount must be positive. +### \-4057 INVALID\_RSA\_PUBLIC\_KEY -### -4056 INVALID_API_KEY_TYPE -* Invalid api key type. +* The API key is invalid. -### -4057 INVALID_RSA_PUBLIC_KEY -* Invalid api public key +### \-4058 MAX\_PRICE\_TOO\_LARGE -### -4058 MAX_PRICE_TOO_LARGE -* maxPrice and priceDecimal too large,please check. +* maxPrice and priceDecimal too large, please check. +### \-4060 INVALID\_POSITION\_SIDE -### -4060 INVALID_POSITION_SIDE * Invalid position side. -### -4061 POSITION_SIDE_NOT_MATCH -* Order's position side does not match user's setting. +### \-4061 POSITION\_SIDE\_NOT\_MATCH + +* The order's position direction does not match the user’s settings. + +### \-4062 REDUCE\_ONLY\_CONFLICT -### -4062 REDUCE_ONLY_CONFLICT * Invalid or improper reduceOnly value. -### -4083 PLACE_BATCH_ORDERS_FAIL -* Fail to place batch orders. +### \-4084 UPCOMING\_METHOD + +* Method is not allowed currently. Coming soon. + +### \-4086 INVALID\_PRICE\_SPREAD\_THRESHOLD + +* Invalid price spread threshold. + +### \-4087 REDUCE\_ONLY\_ORDER\_PERMISSION + +* Users can only place reduce-only orders. -### -4084 UPCOMING_METHOD -* Method is not allowed currently. Upcoming soon. +### \-4088 NO\_PLACE\_ORDER\_PERMISSION -### -4086 INVALID_PRICE_SPREAD_THRESHOLD -* Invalid price spread threshold +* User cannot place orders currently. -### -4087 REDUCE_ONLY_ORDER_PERMISSION -* User can only place reduce only order +### \-4114 INVALID\_CLIENT\_TRAN\_ID\_LEN -### -4088 NO_PLACE_ORDER_PERMISSION -* User can not place order currently +* clientTranId is not valid. +* The customer's tranId length should be less than 64 characters. -### -4114 INVALID_CLIENT_TRAN_ID_LEN -* clientTranId is not valid -* Client tran id length should be less than 64 chars +### \-4115 DUPLICATED\_CLIENT\_TRAN\_ID -### -4115 DUPLICATED_CLIENT_TRAN_ID -* clientTranId is duplicated -* Client tran id should be unique within 7 days +* clientTranId is duplicated. +* The client's tranId should be unique within 7 days. -### -4118 REDUCE_ONLY_MARGIN_CHECK_FAILED -* ReduceOnly Order Failed. Please check your existing position and open orders +### \-4118 REDUCE\_ONLY\_MARGIN\_CHECK\_FAILED -### -4131 MARKET_ORDER_REJECT -* The counterparty's best price does not meet the PERCENT_PRICE filter limit +* ReduceOnly Order failed. Please check your existing position and open orders -### -4135 INVALID_ACTIVATION_PRICE -* Invalid activation price +### \-4131 MARKET\_ORDER\_REJECT -### -4137 QUANTITY_EXISTS_WITH_CLOSE_POSITION -* Quantity must be zero with closePosition equals true +* The counterparty's best price does not meet the PERCENT\_PRICE filter limit. -### -4138 REDUCE_ONLY_MUST_BE_TRUE -* Reduce only must be true with closePosition equals true +### \-4135 INVALID\_ACTIVATION\_PRICE -### -4139 ORDER_TYPE_CANNOT_BE_MKT -* Order type can not be market if it's unable to cancel +* Invalid activation price. -### -4140 INVALID_OPENING_POSITION_STATUS -* Invalid symbol status for opening position +### \-4137 QUANTITY\_EXISTS\_WITH\_CLOSE\_POSITION -### -4141 SYMBOL_ALREADY_CLOSED -* Symbol is closed +* Quantity must be zero when closePosition is true. -### -4142 STRATEGY_INVALID_TRIGGER_PRICE -* REJECT: take profit or stop order will be triggered immediately +### \-4138 REDUCE\_ONLY\_MUST\_BE\_TRUE -### -4164 MIN_NOTIONAL -* Order's notional must be no smaller than 5.0 (unless you choose reduce only) -* Order's notional must be no smaller than %s (unless you choose reduce only) +* Reduce only must be true when closePosition is true. -### -4165 INVALID_TIME_INTERVAL -* Invalid time interval +### \-4139 ORDER\_TYPE\_CANNOT\_BE\_MKT + +* Order type cannot be a market order if it cannot be canceled. + +### \-4140 INVALID\_OPENING\_POSITION\_STATUS + +* Invalid symbol status for opening position. + +### \-4141 SYMBOL\_ALREADY\_CLOSED + +* Trading pair has been delisted. + +### \-4142 STRATEGY\_INVALID\_TRIGGER\_PRICE + +* Rejected: Take Profit or Stop order would be triggered immediately. + +### \-4164 MIN\_NOTIONAL + +* Order notional must be at least 5.0 (unless you select Reduce Only) +* Order notional must be no smaller than %s (unless you choose Reduce Only) + +### \-4165 INVALID\_TIME\_INTERVAL + +* Invalid time interval * Maximum time interval is %s days -### -4183 PRICE_HIGHTER_THAN_STOP_MULTIPLIER_UP -* Price is higher than stop price multiplier cap. -* Limit price can't be higher than %s. +### \-4183 PRICE\_HIGHTER\_THAN\_STOP\_MULTIPLIER\_UP + +* Limit price cannot be higher than the cap of %s. +* Take-Profit/Stop-Loss price cannot be higher than the cap of %s. + +### \-4184 PRICE\_LOWER\_THAN\_STOP\_MULTIPLIER\_DOWN + +* Price is below the stop price limit. +* Take-Profit/Stop-Loss price must be above the trigger price × multiplier floor. +* Order price (limit or TP/SL) can’t be below %s. -### -4184 PRICE_LOWER_THAN_STOP_MULTIPLIER_DOWN -* Price is lower than stop price multiplier floor. -* Limit price can't be lower than %s. diff --git a/aster-finance-spot-api_CN.md b/aster-finance-spot-api_CN.md index a623ce7..265cc2d 100644 --- a/aster-finance-spot-api_CN.md +++ b/aster-finance-spot-api_CN.md @@ -1504,6 +1504,7 @@ network | STRING | NO | 注意: * userOperationType 仅可取值: CREATE_API_KEY * network: sol网络必须传入SOL,其他忽略 +* 限流单IP一分钟60次 ## 创建apikey (NONE) diff --git a/consolidation.js b/consolidation.js index 0d51600..4420c17 100644 --- a/consolidation.js +++ b/consolidation.js @@ -21,8 +21,6 @@ const new_address_config = [ } ] -// const host = 'http://127.0.0.1:9081' -// const host = 'https://www.astherusqa.finance' const host = 'https://sapi.asterdex.com' //主账户私钥 @@ -34,7 +32,6 @@ const main_address = '*' const api_key = '*' const api_secret = '*' -const desc = 'newApikey899221' //创建apikey时的描述信息 注意同一账户的desc不能重复 //归集和提现的手续费 代币 数量配置 const fee = '0.6' @@ -115,7 +112,6 @@ async function sendRequest(url, method) { if (use_new_apikey == true) { key = new_address_apikey } - // console.log('url:', url) if (method == 'POST') { headers = { 'Content-Type': 'application/x-www-form-urlencoded', @@ -125,7 +121,7 @@ async function sendRequest(url, method) { } try { const response = await axios({ - method: method, // 支持 get, post, put, delete, etc. + method: method, url: url, headers: headers @@ -186,7 +182,8 @@ async function main() { message = 'You are signing into Astherus ${nonce}'.replace('${nonce}', nonce) userSignature = await sign(config.private_key,message) - var key_desc = desc + '_' + i + //创建apikey时的描述信息 注意同一账户的desc不能重复 + var key_desc = Date.now() +'_' + i i = i + 1 let new_api = await send(spot_create_apikey, { 'userSignature': userSignature,'address': config.address,'desc': key_desc }) new_address_apikey = new_api['apiKey'] From 0d62d18d5a3ac901947b57443036c091b5083180 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Tue, 2 Sep 2025 18:37:57 +0800 Subject: [PATCH 007/131] fee --- consolidation.js | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/consolidation.js b/consolidation.js index 4420c17..5f34131 100644 --- a/consolidation.js +++ b/consolidation.js @@ -33,8 +33,6 @@ const api_key = '*' const api_secret = '*' -//归集和提现的手续费 代币 数量配置 -const fee = '0.6' const withdraw_nonce = Date.now() + '000' const withdraw_asset = 'CDL' const withdraw_amount = '1' @@ -77,13 +75,13 @@ const types = { } -const value = { +var value = { 'type': 'Withdraw', 'destination': main_address, 'destination Chain': newrok, 'token': withdraw_asset, 'amount': withdraw_amount, - 'fee': fee, + 'fee': '', 'nonce': withdraw_nonce, 'aster chain': 'Mainnet', } @@ -208,11 +206,18 @@ async function main() { estimateFee = await send(spot_withdraw_estimateFee, {}) console.log('estimateFee:', estimateFee) + + //归集和提现的手续费 代币 数量配置 + fee = estimateFee['gasCost'] + value.fee = fee*1.5+'' + console.log('提现手续费:', value.fee) + + withdraw_ignature = await generateSignature() //使用老账户进行提现操作 spotWithdraw = await send(spot_withdraw, { - 'fee': fee, 'nonce': withdraw_nonce, + 'fee': value.fee, 'nonce': withdraw_nonce, 'userSignature': withdraw_ignature, 'receiver': main_address, 'asset': withdraw_asset, 'amount': withdraw_amount }) From 70b88fe8afcb9fabae9da61368e795a994f11ffd Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Tue, 2 Sep 2025 18:40:24 +0800 Subject: [PATCH 008/131] asset fix --- consolidation.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/consolidation.js b/consolidation.js index 5f34131..eca498e 100644 --- a/consolidation.js +++ b/consolidation.js @@ -50,7 +50,7 @@ const spot_create_apikey = { 'url': '/api/v1/createApiKey', 'method': 'POST', 'p const spot_send_toAddress = { 'url': '/api/v1/spot/sendToAddress', 'method': 'POST', 'params': {} } // #chainId: 1(ETH),56(BSC),42161(Arbi) -const spot_withdraw_estimateFee = { 'url': '/api/v1/aster/withdraw/estimateFee', 'method': 'GET', 'params': { 'asset': 'BNB', "chainId": chainId } } +const spot_withdraw_estimateFee = { 'url': '/api/v1/aster/withdraw/estimateFee', 'method': 'GET', 'params': { 'asset': withdraw_asset, "chainId": chainId } } const spot_withdraw = { 'url': '/api/v1/aster/user-withdraw', 'method': 'POST', 'params': { "chainId": chainId } } From b4f7dadae0e3b63f11b54f358b283268803a6ae0 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Tue, 2 Sep 2025 18:56:09 +0800 Subject: [PATCH 009/131] fix url --- consolidation.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/consolidation.js b/consolidation.js index eca498e..c7972e6 100644 --- a/consolidation.js +++ b/consolidation.js @@ -47,7 +47,7 @@ var use_new_apikey = false const spot_get_nonce = { 'url': '/api/v1/getNonce', 'method': 'POST', 'params': { 'userOperationType': 'CREATE_API_KEY' } } const spot_create_apikey = { 'url': '/api/v1/createApiKey', 'method': 'POST', 'params': { 'userOperationType': 'CREATE_API_KEY' } } -const spot_send_toAddress = { 'url': '/api/v1/spot/sendToAddress', 'method': 'POST', 'params': {} } +const spot_send_toAddress = { 'url': '/api/v1/asset/sendToAddress', 'method': 'POST', 'params': {} } // #chainId: 1(ETH),56(BSC),42161(Arbi) const spot_withdraw_estimateFee = { 'url': '/api/v1/aster/withdraw/estimateFee', 'method': 'GET', 'params': { 'asset': withdraw_asset, "chainId": chainId } } From c1fba3e23ef72aace6f99e77618340717ad94af5 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Thu, 4 Sep 2025 10:46:24 +0800 Subject: [PATCH 010/131] spot en --- aster-finance-spot-api.md | 37 ++++++++++++++++++------------------ aster-finance-spot-api_CN.md | 4 +++- consolidation.js | 4 ++-- 3 files changed, 23 insertions(+), 22 deletions(-) diff --git a/aster-finance-spot-api.md b/aster-finance-spot-api.md index 3baa47e..848f52e 100644 --- a/aster-finance-spot-api.md +++ b/aster-finance-spot-api.md @@ -251,7 +251,7 @@ This defines how long an order can remain valid before expiring. | GTC (Good ‘Til Canceled) | The order remains active until it is fully executed or manually canceled. | | IOC (Immediate or Cancel) | The order will execute immediately for any amount available. Any unfilled portion is automatically canceled. | | FOK (Fill or Kill) | The order must be fully executed immediately. If it cannot be filled in full, it is canceled right away. | -| GTX (Good ‘Til Executed) | The order remains active until it is fully executed. Only limit orders are supported. | +| GTX (Good till crossing, Post only) | The post-only limit order will only be placed if it can be added as a maker order and not as a taker order. | **K-line interval:** @@ -779,7 +779,9 @@ Each K-line represents a trading pair. The open time of each K-line can be regar "closeTime": 1499869899040, //close time "firstId": 28385, // first id "lastId": 28460, // last id - "count": 76 // count + "count": 76, // count + "baseAsset": "CDL", //base asset + "quoteAsset": "FORM" //quote asset } ``` @@ -1188,8 +1190,7 @@ Retrieve all account orders; active, canceled, or completed. | kindType | STRING | YES | Transaction type | | timestamp | LONG | YES | Timestamp | -* kindType values are FUTURE\_MAIN (perp to spot) and MAIN\_FUTURE (spot to perp) - +* kindType FUTURE_SPOT(future to spot)/SPOT_FUTURE(spot to future) ## Transfer asset to other address (TRADE) @@ -1221,7 +1222,7 @@ clientTranId | STRING | NO | recvWindow | LONG | NO | timestamp | LONG | YES | -**Notes:** +**Note:** * The target address must be a valid existing account and must not be the same as the sender’s account. * The toAddress must be an EVM address. * If clientTranId is provided, its length must be at least 20 characters. @@ -1286,10 +1287,10 @@ recvWindow | LONG | NO | timestamp | LONG | YES | -**Notes:** +**Note:** * chainId: 1(ETH),56(BSC),42161(Arbi) * receiver: The address of the current account -* If the futures account balance is insufficient, funds will be transferred from the spot account to the futures account for the withdrawal. +* If the futures account balance is insufficient, funds will be transferred from the spot account to the perp account for withdrawal. * userSignature demo ```shell @@ -1329,7 +1330,7 @@ const types = { const signature = await signer.signTypedData(domain, types, value) ``` -## Get user create apikey nonce (NONE) +## Get User Create Apikey nonce (NONE) > **Response:** ```javascript @@ -1354,11 +1355,10 @@ userOperationType | STRING | YES | CREATE_API_KEY network | STRING | NO | **Notes:** -* userOperationType : CREATE_API_KEY -* network : For the Solana network, SOL must be provided; otherwise, this field is ignored. -* Rate limit: 60 requests per minute per IP +* userOperationType: CREATE_API_KEY +* network: For the Solana network, SOL must be provided; otherwise, this field can be ignored. -## Create apikey (NONE) +## Create Apikey (NONE) > **Response:** ```javascript @@ -1388,13 +1388,13 @@ desc | STRING | YES | recvWindow | LONG | NO | timestamp | LONG | YES | -**Notes:** -* userOperationType : CREATE_API_KEY -* network : For the Solana network, SOL must be provided; otherwise, this field is ignored. +**Note:** +* userOperationType: CREATE_API_KEY +* network: For the Solana network, SOL must be provided; otherwise, this field can be ignored. * desc: The same account cannot be duplicated, and the length must not exceed 20 characters. -* apikeyIP An array of IP addresses, separated by commas. -* Rate limit: 60 requests per minute per IP -* userSignature evm demo +* apikeyIP: An array of IP addresses, separated by commas. +* Rate limit: 60 requests per minute per IP. +* userSignature: EVM demo ```shell const nonce = 111111 @@ -1402,7 +1402,6 @@ const message = 'You are signing into Astherus ${nonce}'; const signature = await signer.signMessage(message); ``` - ## Account information (USER\_DATA) **Response** diff --git a/aster-finance-spot-api_CN.md b/aster-finance-spot-api_CN.md index 265cc2d..ea14d72 100644 --- a/aster-finance-spot-api_CN.md +++ b/aster-finance-spot-api_CN.md @@ -818,7 +818,9 @@ limit | INT | NO | 默认 500; 最大 1500. "closeTime": 1499869899040, //24小时内,最后一笔交易的发生时间 "firstId": 28385, // 首笔成交id "lastId": 28460, // 末笔成交id - "count": 76 // 成交笔数 + "count": 76, // 成交笔数 + "baseAsset": "CDL", //基础代币 + "quoteAsset": "FORM" //报价代币 } ``` diff --git a/consolidation.js b/consolidation.js index c7972e6..aaf5136 100644 --- a/consolidation.js +++ b/consolidation.js @@ -36,7 +36,7 @@ const api_secret = '*' const withdraw_nonce = Date.now() + '000' const withdraw_asset = 'CDL' const withdraw_amount = '1' -const newrok = 'BSC' //主网使用 BSC +const network = 'BSC' //主网使用 BSC const chainId = 56 //主网使用 56 @@ -78,7 +78,7 @@ const types = { var value = { 'type': 'Withdraw', 'destination': main_address, - 'destination Chain': newrok, + 'destination Chain': network, 'token': withdraw_asset, 'amount': withdraw_amount, 'fee': '', From 428f12f86da32478a937224a33ca8577b1626a98 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Tue, 16 Sep 2025 11:04:37 +0800 Subject: [PATCH 011/131] futures v3 --- README.md | 33 +- aster-finance-futures-api-v3.md | 4555 ++++++++++++++++ aster-finance-futures-api-v3_CN.md | 4707 +++++++++++++++++ ...ure-api.md => aster-finance-futures-api.md | 6 +- ...i_CN.md => aster-finance-futures-api_CN.md | 0 aster-finance-spot-api.md | 4 +- aster-finance-spot-api_CN.md | 4 +- 7 files changed, 9298 insertions(+), 11 deletions(-) create mode 100644 aster-finance-futures-api-v3.md create mode 100644 aster-finance-futures-api-v3_CN.md rename aster-finance-future-api.md => aster-finance-futures-api.md (99%) rename aster-finance-future-api_CN.md => aster-finance-futures-api_CN.md (100%) diff --git a/README.md b/README.md index af516de..c4e7c68 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,33 @@ -# API Documentation for Aster Finance +# API Documentation for Aster Finance Futures -[Aster Finance API Document](./aster-finance-api.md) +[Aster Finance Futures API Document](./aster-finance-futures-api.md) -# Aster Finance API 文档 +# Aster Finance Futures API 文档 + +[Aster Finance Futures API 文档](./aster-finance-futures-api_CN.md) + +# API V3 Documentation for Aster Finance Futures + +[Aster Finance Futures API V3 Document](./aster-finance-futures-api-v3.md) + +# Aster Finance Futures API V3 文档 + +[Aster Finance Futures API V3 文档](./aster-finance-futures-api-v3_CN.md) + +# API Documentation for Aster Finance Spot + +[Aster Finance Spot API Document](./aster-finance-spot-api.md) + +# Aster Finance Spot API 文档 + +[Aster Finance Spot API 文档](./aster-finance-spot-api_CN.md) + +# Aster Finance Spot Asset Consolidation + +[Aster Finance Spot Asset Consolidation](./consolidation.js) + +# Aster 现货资产归集脚本示例 + +[Aster 现货资产归集脚本示例](./consolidation.js) -[Aster Finance API 文档](./aster-finance-api_CN.md) diff --git a/aster-finance-futures-api-v3.md b/aster-finance-futures-api-v3.md new file mode 100644 index 0000000..fe2daf4 --- /dev/null +++ b/aster-finance-futures-api-v3.md @@ -0,0 +1,4555 @@ +> > - [General Info](#general-info) + +- [General API Information](#general-api-information) + - [HTTP Return Codes](#http-return-codes) + - [Error Codes and Messages](#error-codes-and-messages) + - [General Information on Endpoints](#general-information-on-endpoints) +- [LIMITS](#limits) + - [IP Limits](#ip-limits) + - [Order Rate Limits](#order-rate-limits) +- [API authentication type](#api-authentication-type) +- [Authentication signature payload](#authentication-signature-payload) +- [Timing Security](#timing-security) +- [Endpoints requiring signature](#endpoints-requiring-signature) + - [POST /fapi/v3/order example](#example-of-post-fapiv3order) + - [GET /fapi/v3/order example](#Eexample-of-get-fapiv3order) + - [python script](#python-script) +- [Public Endpoints Info](#public-endpoints-info) + - [Terminology](#terminology) + - [ENUM definitions](#enum-definitions) +- [Filters](#filters) + - [Symbol filters](#symbol-filters) + - [PRICE_FILTER](#price_filter) + - [LOT_SIZE](#lot_size) + - [MARKET_LOT_SIZE](#market_lot_size) + - [MAX_NUM_ORDERS](#max_num_orders) + - [MAX_NUM_ALGO_ORDERS](#max_num_algo_orders) + - [PERCENT_PRICE](#percent_price) + - [MIN_NOTIONAL](#min_notional) +- [Market Data Endpoints](#market-data-endpoints) + - [Test Connectivity](#test-connectivity) + - [Check Server Time](#check-server-time) + - [Exchange Information](#exchange-information) + - [Order Book](#order-book) + - [Recent Trades List](#recent-trades-list) + - [Old Trades Lookup (MARKET_DATA)](#old-trades-lookup-market_data) + - [Compressed/Aggregate Trades List](#compressedaggregate-trades-list) + - [Kline/Candlestick Data](#klinecandlestick-data) + - [Index Price Kline/Candlestick Data](#index-price-klinecandlestick-data) + - [Mark Price Kline/Candlestick Data](#mark-price-klinecandlestick-data) + - [Mark Price](#mark-price) + - [Get Funding Rate History](#get-funding-rate-history) + - [24hr Ticker Price Change Statistics](#24hr-ticker-price-change-statistics) + - [Symbol Price Ticker](#symbol-price-ticker) + - [Symbol Order Book Ticker](#symbol-order-book-ticker) +- [Websocket Market Streams](#websocket-market-streams) + - [Live Subscribing/Unsubscribing to streams](#live-subscribingunsubscribing-to-streams) + - [Subscribe to a stream](#subscribe-to-a-stream) + - [Unsubscribe to a stream](#unsubscribe-to-a-stream) + - [Listing Subscriptions](#listing-subscriptions) + - [Setting Properties](#setting-properties) + - [Retrieving Properties](#retrieving-properties) + - [Error Messages](#error-messages) + - [Aggregate Trade Streams](#aggregate-trade-streams) + - [Mark Price Stream](#mark-price-stream) + - [Mark Price Stream for All market](#mark-price-stream-for-all-market) + - [Kline/Candlestick Streams](#klinecandlestick-streams) + - [Individual Symbol Mini Ticker Stream](#individual-symbol-mini-ticker-stream) + - [All Market Mini Tickers Stream](#all-market-mini-tickers-stream) + - [Individual Symbol Ticker Streams](#individual-symbol-ticker-streams) + - [All Market Tickers Streams](#all-market-tickers-streams) + - [Individual Symbol Book Ticker Streams](#individual-symbol-book-ticker-streams) + - [All Book Tickers Stream](#all-book-tickers-stream) + - [Liquidation Order Streams](#liquidation-order-streams) + - [All Market Liquidation Order Streams](#all-market-liquidation-order-streams) + - [Partial Book Depth Streams](#partial-book-depth-streams) + - [Diff. Book Depth Streams](#diff-book-depth-streams) + - [How to manage a local order book correctly](#how-to-manage-a-local-order-book-correctly) +- [Account/Trades Endpoints](#accounttrades-endpoints) + - [Change Position Mode(TRADE)](#change-position-modetrade) + - [Get Current Position Mode(USER_DATA)](#get-current-position-modeuser_data) + - [Change Multi-Assets Mode (TRADE)](#change-multi-assets-mode-trade) + - [Get Current Multi-Assets Mode (USER_DATA)](#get-current-multi-assets-mode-user_data) + - [New Order (TRADE)](#new-order--trade) + - [Place Multiple Orders (TRADE)](#place-multiple-orders--trade) + - [Transfer Between Futures And Spot (USER_DATA)](#transfer-between-futures-and-spot-user_data) + - [Query Order (USER_DATA)](#query-order-user_data) + - [Cancel Order (TRADE)](#cancel-order-trade) + - [Cancel All Open Orders (TRADE)](#cancel-all-open-orders-trade) + - [Cancel Multiple Orders (TRADE)](#cancel-multiple-orders-trade) + - [Auto-Cancel All Open Orders (TRADE)](#auto-cancel-all-open-orders-trade) + - [Query Current Open Order (USER_DATA)](#query-current-open-order-user_data) + - [Current All Open Orders (USER_DATA)](#current-all-open-orders-user_data) + - [All Orders (USER_DATA)](#all-orders-user_data) + - [Futures Account Balance v3 (USER_DATA)](#futures-account-balance-v3-user_data) + - [Account Information v3 (USER_DATA)](#account-information-v3-user_data) + - [Change Initial Leverage (TRADE)](#change-initial-leverage-trade) + - [Change Margin Type (TRADE)](#change-margin-type-trade) + - [Modify Isolated Position Margin (TRADE)](#modify-isolated-position-margin-trade) + - [Get Position Margin Change History (TRADE)](#get-position-margin-change-history-trade) + - [Position Information v3 (USER_DATA)](#position-information-v3-user_data) + - [Account Trade List (USER_DATA)](#account-trade-list-user_data) + - [Get Income History(USER_DATA)](#get-income-historyuser_data) + - [Notional and Leverage Brackets (USER_DATA)](#notional-and-leverage-brackets-user_data) + - [Position ADL Quantile Estimation (USER_DATA)](#position-adl-quantile-estimation-user_data) + - [User's Force Orders (USER_DATA)](#users-force-orders-user_data) + - [User Commission Rate (USER_DATA)](#user-commission-rate-user_data) +- [User Data Streams](#user-data-streams) + - [Start User Data Stream (USER_STREAM)](#start-user-data-stream-user_stream) + - [Keepalive User Data Stream (USER_STREAM)](#keepalive-user-data-stream-user_stream) + - [Close User Data Stream (USER_STREAM)](#close-user-data-stream-user_stream) + - [Event: User Data Stream Expired](#event-user-data-stream-expired) + - [Event: Margin Call](#event-margin-call) + - [Event: Balance and Position Update](#event-balance-and-position-update) + - [Event: Order Update](#event-order-update) + - [Event: Account Configuration Update previous Leverage Update](#event-account-configuration-update-previous-leverage-update) +- [Error Codes](#error-codes) + - [10xx - General Server or Network issues](#10xx---general-server-or-network-issues) + - [11xx - Request issues](#11xx---request-issues) + - [20xx - Processing Issues](#20xx---processing-issues) + - [40xx - Filters and other Issues](#40xx---filters-and-other-issues) + +# General Info + +## General API Information + +* This API may require the user's AGENT. To learn how to create an AGENT, please refer toSome endpoints will require an API Key. Please refer to [this page](https://www.asterdex.com/) +* The base endpoint is: **https://fapi.asterdex.com** +* All endpoints return either a JSON object or array. +* Data is returned in **ascending** order. Oldest first, newest last. +* All time and timestamp related fields are in milliseconds. +* All data types adopt definition in JAVA. + +### HTTP Return Codes + +* HTTP `4XX` return codes are used for for malformed requests; + the issue is on the sender's side. +* HTTP `403` return code is used when the WAF Limit (Web Application Firewall) has been violated. +* HTTP `429` return code is used when breaking a request rate limit. +* HTTP `418` return code is used when an IP has been auto-banned for continuing to send requests after receiving `429` codes. +* HTTP `5XX` return codes are used for internal errors; the issue is on + Aster's side. +* HTTP `503` return code is used when the API successfully sent the message but not get a response within the timeout period. + It is important to **NOT** treat this as a failure operation; the execution status is + **UNKNOWN** and could have been a success. + +### Error Codes and Messages + +* Any endpoint can return an ERROR + +> ***The error payload is as follows:*** + +```javascript +{ + "code": -1121, + "msg": "Invalid symbol." +} +``` + +* Specific error codes and messages defined in [Error Codes](#error-codes). + +### General Information on Endpoints + +* For `GET` endpoints, parameters must be sent as a `query string`. +* For POST, PUT, and DELETE method APIs, send data in the request body (content type application/x-www-form-urlencoded) +* Parameters may be sent in any order. + +## LIMITS + +* The `/fapi/v3/exchangeInfo` `rateLimits` array contains objects related to the exchange's `RAW_REQUEST`, `REQUEST_WEIGHT`, and `ORDER` rate limits. These are further defined in the `ENUM definitions` section under `Rate limiters (rateLimitType)`. +* A `429` will be returned when either rate limit is violated. + + + +### IP Limits + +* Every request will contain `X-MBX-USED-WEIGHT-(intervalNum)(intervalLetter)` in the response headers which has the current used weight for the IP for all request rate limiters defined. +* Each route has a `weight` which determines for the number of requests each endpoint counts for. Heavier endpoints and endpoints that do operations on multiple symbols will have a heavier `weight`. +* When a 429 is received, it's your obligation as an API to back off and not spam the API. +* **Repeatedly violating rate limits and/or failing to back off after receiving 429s will result in an automated IP ban (HTTP status 418).** +* IP bans are tracked and **scale in duration** for repeat offenders, **from 2 minutes to 3 days**. +* **The limits on the API are based on the IPs, not the API keys.** + + + +### Order Rate Limits + +* Every order response will contain a `X-MBX-ORDER-COUNT-(intervalNum)(intervalLetter)` header which has the current order count for the account for all order rate limiters defined. +* Rejected/unsuccessful orders are not guaranteed to have `X-MBX-ORDER-COUNT-**` headers in the response. +* **The order rate limit is counted against each account**. + +**Serious trading is about timing.** Networks can be unstable and unreliable, +which can lead to requests taking varying amounts of time to reach the +servers. With `recvWindow`, you can specify that the request must be +processed within a certain number of milliseconds or be rejected by the +server. + + + +## API authentication type + +* Each API has its own authentication type, which determines what kind of authentication is required when accessing it. +* If authentication is required, a signer should be included in the request body. + +| Security Type | Description | +| ------------- | ----------------------------------------- | +| NONE | API that does not require authentication | +| TRADE | A valid signer and signature are required | +| USER_DATA | A valid signer and signature are required | +| USER_STREAM | A valid signer and signature are required | +| MARKET_DATA | A valid signer and signature are required | + +## Authentication signature payload + +| Parameter | Description | +| --------- | ---------------------------------- | +| user | Main account wallet address | +| signer | API wallet address | +| nonce | Current timestamp, in microseconds | +| signature | Signature | + +## Endpoints requiring signature +* Security Type: TRADE, USER_DATA, USER_STREAM, MARKET_DATA +* After converting the API parameters to strings, sort them by their key values in ASCII order to generate the final string. Note: All parameter values must be treated as strings during the signing process. +* After generating the string, combine it with the authentication signature parameters user, signer, and nonce, then use Web3’s ABI parameter encoding to generate the bytecode. +* After generating the bytecode, use the Keccak algorithm to generate the hash. +* Use the private key of the derived address to sign the hash using web3’s ECDSA signature algorithm, generating the final signature. + +### Timing Security + +* A `SIGNED` endpoint also requires a parameter, `timestamp`, to be sent which + should be the millisecond timestamp of when the request was created and sent. +* An additional parameter, `recvWindow`, may be sent to specify the number of + milliseconds after `timestamp` the request is valid for. If `recvWindow` + is not sent, **it defaults to 5000**. + +> The logic is as follows: + +```javascript +if (timestamp < (serverTime + 1000) && (serverTime - timestamp) <= recvWindow){ + // process request + } + else { + // reject request + } +``` + +## Example of POST /fapi/v3/order + +#### All parameters are passed through the request body (Python 3.9.6) + +#### The following parameters are API registration details. The values for user, signer, and privateKey are for demonstration purposes only (the privateKey corresponds to the signer). + +| Key | Value | +| ---------- | ------------------------------------------------------------------ | +| user | 0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e | +| signer | 0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0 | +| privateKey | 0x4fd0a42218f3eae43a6ce26d22544e986139a01e5b34a62db53757ffca81bae1 | + +#### The nonce parameter is the current system time in microseconds. If it exceeds the system time or lags behind it by more than 5 seconds, the request is considered invalid. + +```python +#python +nonce = math.trunc(time.time()*1000000) +print(nonce) +#1748310859508867 +``` + +```java +//java +Instant now = Instant.now(); +long microsecond = now.getEpochSecond() * 1000000 + now.getNano() / 1000; +``` +#### Example: The following parameters are business request parameters. + +```python +my_dict = {'symbol': 'SANDUSDT', 'positionSide': 'BOTH', 'type': 'LIMIT', 'side': 'BUY', + 'timeInForce': 'GTC', 'quantity': "190", 'price': 0.28694} +``` + +#### Example: All parameters are sent via form body (using Python as an example). + +> **Step 1: Convert all business parameters to strings, then sort them in ASCII order to generate a string.** + +```python + #Define all element values as strings. + def _trim_dict(my_dict) : + for key in my_dict: + value = my_dict[key] + if isinstance(value, list): + new_value = [] + for item in value: + if isinstance(item, dict): + new_value.append(json.dumps(_trim_dict(item))) + else: + new_value.append(str(item)) + my_dict[key] = json.dumps(new_value) + continue + if isinstance(value, dict): + my_dict[key] = json.dumps(_trim_dict(value)) + continue + my_dict[key] = str(value) + + return my_dict + + #Remove elements with null (empty) values. + my_dict = {key: value for key, value in my_dict.items() if value is not None} + my_dict['recvWindow'] = 50000 + my_dict['timestamp'] = int(round(time.time()*1000)) + # my_dict['timestamp'] = 1749545309665 + #Convert elements to strings. + _trim_dict(my_dict) + #Generate a string sorted by ASCII values and remove special characters. + json_str = json.dumps(my_dict, sort_keys=True).replace(' ', '').replace('\'','\"') + print(json_str) + #{"positionSide":"BOTH","price":"0.28694","quantity":"190","recvWindow":"50000","side":"BUY","symbol":"SANDUSDT","timeInForce":"GTC","timestamp":"1749545309665","type":"LIMIT"} +``` + +> **Step 2: Take the string generated in Step 1 and encode it together with the account information and nonce using ABI encoding to generate a hash string.** + +```python + from eth_abi import encode + from web3 import Web3 + #Use Web3 ABI to encode the generated string along with user, signer, and nonce. + encoded = encode(['string', 'address', 'address', 'uint256'], [json_str, user, signer, nonce]) + print(encoded.hex()) + #000000000000000000000000000000000000000000000000000000000000008000000000000000000000000063dd5acc6b1aa0f563956c0e534dd30b6dcf7c4e00000000000000000000000021cf8ae13bb72632562c6fff438652ba1a151bb00000000000000000000000000000000000000000000000000006361457bcec8300000000000000000000000000000000000000000000000000000000000000af7b22706f736974696f6e53696465223a22424f5448222c227072696365223a22302e3238363934222c227175616e74697479223a22313930222c227265637657696e646f77223a223530303030222c2273696465223a22425559222c2273796d626f6c223a2253414e4455534454222c2274696d65496e466f726365223a22475443222c2274696d657374616d70223a2231373439353435333039363635222c2274797065223a224c494d4954227d0000000000000000000000000000000000 + #keccak hex + keccak_hex =Web3.keccak(encoded).hex() + print(keccak_hex) + #9e0273fc91323f5cdbcb00c358be3dee2854afb2d3e4c68497364a2f27a377fc +``` + +> **Step 3: Sign the hash generated in Step 2 using the privateKey.** + +```python + from eth_account import Account + from eth_abi import encode + from web3 import Web3, EthereumTesterProvider + from eth_account.messages import encode_defunct + + signable_msg = encode_defunct(hexstr=keccak_hex) + signed_message = Account.sign_message(signable_message=signable_msg, private_key=priKey) + signature = '0x'+signed_message.signature.hex() + print(signature) + #0x0337dd720a21543b80ff861cd3c26646b75b3a6a4b5d45805d4c1d6ad6fc33e65f0722778dd97525466560c69fbddbe6874eb4ed6f5fa7e576e486d9b5da67f31b +``` + +> **Step 4: Combine all parameters along with the signature generated in Step 3 into the request body.** + +```python + my_dict['nonce'] = nonce + my_dict['user'] = user + my_dict['signer'] = signer + my_dict['signature'] = '0x'+signed_message.signature.hex() + url ='http://127.0.0.1:9081/fapi/v3/order' + headers = { + 'Content-Type': 'application/x-www-form-urlencoded', + 'User-Agent': 'PythonApp/1.0' + } + res = requests.post(url,data=my_dict,headers=headers) + print(url) + #curl -X POST 'http://127.0.0.1:9081/fapi/v3/order' -d 'symbol=SANDUSDT&positionSide=BOTH&type=LIMIT&side=BUY&timeInForce=GTC&quantity=190&price=0.28694&recvWindow=50000×tamp=1749545309665&nonce=1748310859508867&user=0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e&signer=0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0&signature=0x0337dd720a21543b80ff861cd3c26646b75b3a6a4b5d45805d4c1d6ad6fc33e65f0722778dd97525466560c69fbddbe6874eb4ed6f5fa7e576e486d9b5da67f31b' +``` + +## Example of POST /fapi/v3/order + +#### Example: All parameters are sent through the query string (Python 3.9.6). + +#### Example: The following parameters are API registration information. user, signer, and privateKey are for demonstration purposes only (where privateKey is the private key of the agent). + +| Key | Value | +| ---------- | ------------------------------------------------------------------ | +| user | 0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e | +| signer | 0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0 | +| privateKey | 0x4fd0a42218f3eae43a6ce26d22544e986139a01e5b34a62db53757ffca81bae1 | + +#### Example: The nonce parameter should be the current system timestamp in microseconds. If it exceeds the current time or lags behind the system time by more than 5 seconds, it will be considered an invalid request. + +```python +#python +nonce = math.trunc(time.time()*1000000) +print(nonce) +#1748310859508867 +``` + +```java +//java +Instant now = Instant.now(); +long microsecond = now.getEpochSecond() * 1000000 + now.getNano() / 1000; +``` + +#### Example: The following parameters are business request parameters. + +```python +my_dict = {'symbol':'SANDUSDT','side':"SELL","type":'LIMIT','orderId':2194215} +``` + +> **Step 1: Convert all business parameters to strings and generate a sorted string based on ASCII order.** + +```python + #Define all element values as strings. + def _trim_dict(my_dict) : + # 假设待删除的字典为d + for key in my_dict: + value = my_dict[key] + if isinstance(value, list): + new_value = [] + for item in value: + if isinstance(item, dict): + new_value.append(json.dumps(_trim_dict(item))) + else: + new_value.append(str(item)) + my_dict[key] = json.dumps(new_value) + continue + if isinstance(value, dict): + my_dict[key] = json.dumps(_trim_dict(value)) + continue + my_dict[key] = str(value) + + return my_dict + + + #Remove elements with empty values. + my_dict = {key: value for key, value in my_dict.items() if value is not None} + my_dict['recvWindow'] = 50000 + my_dict['timestamp'] = int(round(time.time()*1000)) + # my_dict['timestamp'] = 1749545309665 + #Convert all elements to strings. + _trim_dict(my_dict) + #Generate a string sorted by ASCII values and remove special characters. + json_str = json.dumps(my_dict, sort_keys=True).replace(' ', '').replace('\'','\"') + print(json_str) + #{"orderId":"2194215","recvWindow":"50000","side":"BUY","symbol":"SANDUSDT","timestamp":"1749545309665","type":"LIMIT"} +``` + +> **Step 2: Use ABI encoding to combine the string from step 1 with the account information (user, signer) and nonce, then generate a hash string from the encoded result.** + +```python + from eth_abi import encode + from web3 import Web3 + + #Use WEB3 ABI to encode the generated string together with user, signer, and nonce. + encoded = encode(['string', 'address', 'address', 'uint256'], [json_str, user, signer, nonce]) + print(encoded.hex()) + #000000000000000000000000000000000000000000000000000000000000008000000000000000000000000063dd5acc6b1aa0f563956c0e534dd30b6dcf7c4e00000000000000000000000021cf8ae13bb72632562c6fff438652ba1a151bb00000000000000000000000000000000000000000000000000006361457bcec8300000000000000000000000000000000000000000000000000000000000000767b226f726465724964223a2232313934323135222c227265637657696e646f77223a223530303030222c2273696465223a22425559222c2273796d626f6c223a2253414e4455534454222c2274696d657374616d70223a2231373439353435333039363635222c2274797065223a224c494d4954227d00000000000000000000 + keccak_hex =Web3.keccak(encoded).hex() + print(keccak_hex) + #6ad9569ea1355bf62de1b09b33b267a9404239af6d9227fa59e3633edae19e2a +``` + +> **Step 3: Sign the hash generated in Step 2 using the privateKey.** + +```python +from eth_account import Account + from eth_abi import encode + from web3 import Web3, EthereumTesterProvider + from eth_account.messages import encode_defunct + + signable_msg = encode_defunct(hexstr=keccak_hex) + signed_message = Account.sign_message(signable_message=signable_msg, private_key=priKey) + signature = '0x'+signed_message.signature.hex() + print(signature) + #0x4f5e36e91f0d4cf5b29b6559ebc2c808d3c808ebb13b2bcaaa478b98fb4195642c7473f0d1aa101359aaf278126af1a53bcb482fb05003bfb6bdc03de03c63151b +``` + +> **Step 4: Combine all parameters and the signature from Step 3 into the request body.** + +```python + my_dict['nonce'] = nonce + my_dict['user'] = user + my_dict['signer'] = signer + my_dict['signature'] = '0x'+signed_message.signature.hex() + + url ='http://127.0.0.1:9081/fapi/v3/order' + + res = requests.get(url, params=my_dict) + print(url) + #curl -X GET 'http://127.0.0.1:9081/fapi/v3/order?symbol=SANDUSDT&side=BUY&type=LIMIT&orderId=2194215&recvWindow=50000×tamp=1749545309665&nonce=1748310859508867&user=0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e&signer=0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0&signature=0x4f5e36e91f0d4cf5b29b6559ebc2c808d3c808ebb13b2bcaaa478b98fb4195642c7473f0d1aa101359aaf278126af1a53bcb482fb05003bfb6bdc03de03c63151b' +``` + +## python script + +```python +#Python 3.9.6 +#Python 3.9.6 +#eth-account~=0.13.7 +#eth-abi~=5.2.0 +#web3~=7.11.0 +#requests~=2.32.3 + +import json +import math +import time +import requests + +from eth_abi import encode +from eth_account import Account +from eth_account.messages import encode_defunct +from web3 import Web3 + +user = '0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e' +signer='0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0' +priKey = "0x4fd0a42218f3eae43a6ce26d22544e986139a01e5b34a62db53757ffca81bae1" +host = 'http://127.0.0.1:9081' +placeOrder = {'url': '/fapi/v3/order', 'method': 'POST', + 'params':{'symbol': 'SANDUSDT', 'positionSide': 'BOTH', 'type': 'LIMIT', 'side': 'BUY', + 'timeInForce': 'GTC', 'quantity': "30", 'price': 0.325,'reduceOnly': True}} +getOrder = {'url':'/fapi/v3/order','method':'GET','params':{'symbol':'SANDUSDT','side':"BUY","type":'LIMIT','orderId':2194215}} + +def call(api): + nonce = math.trunc(time.time() * 1000000) + my_dict = api['params'] + send(api['url'],api['method'],sign(my_dict,nonce)) + +def sign(my_dict,nonce): + my_dict = {key: value for key, value in my_dict.items() if value is not None} + my_dict['recvWindow'] = 50000 + my_dict['timestamp'] = int(round(time.time()*1000)) + msg = trim_param(my_dict,nonce) + signable_msg = encode_defunct(hexstr=msg) + signed_message = Account.sign_message(signable_message=signable_msg, private_key=priKey) + my_dict['nonce'] = nonce + my_dict['user'] = user + my_dict['signer'] = signer + my_dict['signature'] = '0x'+signed_message.signature.hex() + + print(my_dict['signature']) + return my_dict + +def trim_param(my_dict,nonce) -> str: + _trim_dict(my_dict) + json_str = json.dumps(my_dict, sort_keys=True).replace(' ', '').replace('\'','\"') + print(json_str) + encoded = encode(['string', 'address', 'address', 'uint256'], [json_str, user, signer, nonce]) + print(encoded.hex()) + keccak_hex =Web3.keccak(encoded).hex() + print(keccak_hex) + return keccak_hex + +def _trim_dict(my_dict) : + for key in my_dict: + value = my_dict[key] + if isinstance(value, list): + new_value = [] + for item in value: + if isinstance(item, dict): + new_value.append(json.dumps(_trim_dict(item))) + else: + new_value.append(str(item)) + my_dict[key] = json.dumps(new_value) + continue + if isinstance(value, dict): + my_dict[key] = json.dumps(_trim_dict(value)) + continue + my_dict[key] = str(value) + + return my_dict + +def send(url, method, my_dict): + url = host + url + print(url) + print(my_dict) + if method == 'POST': + headers = { + 'Content-Type': 'application/x-www-form-urlencoded', + 'User-Agent': 'PythonApp/1.0' + } + res = requests.post(url, data=my_dict, headers=headers) + print(res.text) + if method == 'GET': + res = requests.get(url, params=my_dict) + print(res.text) + if method == 'DELETE': + res = requests.delete(url, data=my_dict) + print(res.text) + +if __name__ == '__main__': + call(placeOrder) + # call(getOrder) +``` + +## Public Endpoints Info + +### Terminology + +* `base asset` refers to the asset that is the `quantity` of a symbol. +* `quote asset` refers to the asset that is the `price` of a symbol. + +### ENUM definitions + +**Symbol type:** + +* FUTURE + +**Contract type (contractType):** + +* PERPETUAL + +**Contract status(contractStatus,status):** + +* PENDING_TRADING +* TRADING +* PRE_SETTLE +* SETTLING +* CLOSE + +**Order status (status):** + +* NEW +* PARTIALLY_FILLED +* FILLED +* CANCELED +* REJECTED +* EXPIRED + +**Order types (orderTypes, type):** + +* LIMIT +* MARKET +* STOP +* STOP_MARKET +* TAKE_PROFIT +* TAKE_PROFIT_MARKET +* TRAILING_STOP_MARKET + +**Order side (side):** + +* BUY +* SELL + +**Position side (positionSide):** + +* BOTH +* LONG +* SHORT + +**Time in force (timeInForce):** + +* GTC - Good Till Cancel +* IOC - Immediate or Cancel +* FOK - Fill or Kill +* GTX - Good Till Crossing (Post Only) + +**Working Type (workingType)** + +* MARK_PRICE +* CONTRACT_PRICE + +**Response Type (newOrderRespType)** + +* ACK +* RESULT + +**Kline/Candlestick chart intervals:** + +m -> minutes; h -> hours; d -> days; w -> weeks; M -> months + +* 1m +* 3m +* 5m +* 15m +* 30m +* 1h +* 2h +* 4h +* 6h +* 8h +* 12h +* 1d +* 3d +* 1w +* 1M + +**Rate limiters (rateLimitType)** + +> REQUEST_WEIGHT + +```javascript +{ + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 2400 + } +``` + +> ORDERS + +```javascript +{ + "rateLimitType": "ORDERS", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200 + } +``` + +* REQUEST_WEIGHT +* ORDERS + +**Rate limit intervals (interval)** + +* MINUTE + +## Filters + +Filters define trading rules on a symbol or an exchange. + +### Symbol filters + +#### PRICE_FILTER + +> **/exchangeInfo format:** + +```javascript +{ + "filterType": "PRICE_FILTER", + "minPrice": "0.00000100", + "maxPrice": "100000.00000000", + "tickSize": "0.00000100" + } +``` + +The `PRICE_FILTER` defines the `price` rules for a symbol. There are 3 parts: + +* `minPrice` defines the minimum `price`/`stopPrice` allowed; disabled on `minPrice` == 0. +* `maxPrice` defines the maximum `price`/`stopPrice` allowed; disabled on `maxPrice` == 0. +* `tickSize` defines the intervals that a `price`/`stopPrice` can be increased/decreased by; disabled on `tickSize` == 0. + +Any of the above variables can be set to 0, which disables that rule in the `price filter`. In order to pass the `price filter`, the following must be true for `price`/`stopPrice` of the enabled rules: + +* `price` >= `minPrice` +* `price` <= `maxPrice` +* (`price`-`minPrice`) % `tickSize` == 0 + +#### LOT_SIZE + +> **/exchangeInfo format:** + +```javascript +{ + "filterType": "LOT_SIZE", + "minQty": "0.00100000", + "maxQty": "100000.00000000", + "stepSize": "0.00100000" + } +``` + +The `LOT_SIZE` filter defines the `quantity` (aka "lots" in auction terms) rules for a symbol. There are 3 parts: + +* `minQty` defines the minimum `quantity` allowed. +* `maxQty` defines the maximum `quantity` allowed. +* `stepSize` defines the intervals that a `quantity` can be increased/decreased by. + +In order to pass the `lot size`, the following must be true for `quantity`: + +* `quantity` >= `minQty` +* `quantity` <= `maxQty` +* (`quantity`-`minQty`) % `stepSize` == 0 + +#### MARKET_LOT_SIZE + +> **/exchangeInfo format:** + +```javascript +{ + "filterType": "MARKET_LOT_SIZE", + "minQty": "0.00100000", + "maxQty": "100000.00000000", + "stepSize": "0.00100000" + } +``` + +The `MARKET_LOT_SIZE` filter defines the `quantity` (aka "lots" in auction terms) rules for `MARKET` orders on a symbol. There are 3 parts: + +* `minQty` defines the minimum `quantity` allowed. +* `maxQty` defines the maximum `quantity` allowed. +* `stepSize` defines the intervals that a `quantity` can be increased/decreased by. + +In order to pass the `market lot size`, the following must be true for `quantity`: + +* `quantity` >= `minQty` +* `quantity` <= `maxQty` +* (`quantity`-`minQty`) % `stepSize` == 0 + +#### MAX_NUM_ORDERS + +> **/exchangeInfo format:** + +```javascript +{ + "filterType": "MAX_NUM_ORDERS", + "limit": 200 + } +``` + +The `MAX_NUM_ORDERS` filter defines the maximum number of orders an account is allowed to have open on a symbol. + +Note that both "algo" orders and normal orders are counted for this filter. + +#### MAX_NUM_ALGO_ORDERS + +> **/exchangeInfo format:** + +```javascript +{ + "filterType": "MAX_NUM_ALGO_ORDERS", + "limit": 100 + } +``` + +The `MAX_NUM_ALGO_ORDERS ` filter defines the maximum number of all kinds of algo orders an account is allowed to have open on a symbol. + +The algo orders include `STOP`, `STOP_MARKET`, `TAKE_PROFIT`, `TAKE_PROFIT_MARKET`, and `TRAILING_STOP_MARKET` orders. + +#### PERCENT_PRICE + +> **/exchangeInfo format:** + +```javascript +{ + "filterType": "PERCENT_PRICE", + "multiplierUp": "1.1500", + "multiplierDown": "0.8500", + "multiplierDecimal": 4 + } +``` + +The `PERCENT_PRICE` filter defines valid range for a price based on the mark price. + +In order to pass the `percent price`, the following must be true for `price`: + +* BUY: `price` <= `markPrice` * `multiplierUp` +* SELL: `price` >= `markPrice` * `multiplierDown` + +#### MIN_NOTIONAL + +> **/exchangeInfo format:** + +```javascript +{ + "filterType": "MIN_NOTIONAL", + "notional": "1" + } +``` + +The `MIN_NOTIONAL` filter defines the minimum notional value allowed for an order on a symbol. +An order's notional value is the `price` * `quantity`. +Since `MARKET` orders have no price, the mark price is used. + +--- + +# Market Data Endpoints + +## Test Connectivity + +> **Response:** + +```javascript +{} +``` + +``GET /fapi/v1/ping`` + +Test connectivity to the Rest API. + +**Weight:** +1 + +**Parameters:** +NONE + +## Check Server Time + +> **Response:** + +```javascript +{ + "serverTime": 1499827319559 +} +``` + +``GET /fapi/v1/time`` + +Test connectivity to the Rest API and get the current server time. + +**Weight:** +1 + +**Parameters:** +NONE + +## Exchange Information + +> **Response:** + +```javascript +{ + "exchangeFilters": [], + "rateLimits": [ + { + "interval": "MINUTE", + "intervalNum": 1, + "limit": 2400, + "rateLimitType": "REQUEST_WEIGHT" + }, + { + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200, + "rateLimitType": "ORDERS" + } + ], + "serverTime": 1565613908500, // Ignore please. If you want to check current server time, please check via "GET /fapi/v1/time" + "assets": [ // assets information + { + "asset": "BUSD", + "marginAvailable": true, // whether the asset can be used as margin in Multi-Assets mode + "autoAssetExchange": 0 // auto-exchange threshold in Multi-Assets margin mode + }, + { + "asset": "USDT", + "marginAvailable": true, + "autoAssetExchange": 0 + }, + { + "asset": "BTC", + "marginAvailable": false, + "autoAssetExchange": null + } + ], + "symbols": [ + { + "symbol": "DOGEUSDT", + "pair": "DOGEUSDT", + "contractType": "PERPETUAL", + "deliveryDate": 4133404800000, + "onboardDate": 1598252400000, + "status": "TRADING", + "maintMarginPercent": "2.5000", // ignore + "requiredMarginPercent": "5.0000", // ignore + "baseAsset": "BLZ", + "quoteAsset": "USDT", + "marginAsset": "USDT", + "pricePrecision": 5, // please do not use it as tickSize + "quantityPrecision": 0, // please do not use it as stepSize + "baseAssetPrecision": 8, + "quotePrecision": 8, + "underlyingType": "COIN", + "underlyingSubType": ["STORAGE"], + "settlePlan": 0, + "triggerProtect": "0.15", // threshold for algo order with "priceProtect" + "filters": [ + { + "filterType": "PRICE_FILTER", + "maxPrice": "300", + "minPrice": "0.0001", + "tickSize": "0.0001" + }, + { + "filterType": "LOT_SIZE", + "maxQty": "10000000", + "minQty": "1", + "stepSize": "1" + }, + { + "filterType": "MARKET_LOT_SIZE", + "maxQty": "590119", + "minQty": "1", + "stepSize": "1" + }, + { + "filterType": "MAX_NUM_ORDERS", + "limit": 200 + }, + { + "filterType": "MAX_NUM_ALGO_ORDERS", + "limit": 100 + }, + { + "filterType": "MIN_NOTIONAL", + "notional": "1", + }, + { + "filterType": "PERCENT_PRICE", + "multiplierUp": "1.1500", + "multiplierDown": "0.8500", + "multiplierDecimal": 4 + } + ], + "OrderType": [ + "LIMIT", + "MARKET", + "STOP", + "STOP_MARKET", + "TAKE_PROFIT", + "TAKE_PROFIT_MARKET", + "TRAILING_STOP_MARKET" + ], + "timeInForce": [ + "GTC", + "IOC", + "FOK", + "GTX" + ], + "liquidationFee": "0.010000", // liquidation fee rate + "marketTakeBound": "0.30", // the max price difference rate( from mark price) a market order can make + } + ], + "timezone": "UTC" +} +``` + +``GET /fapi/v1/exchangeInfo`` + +Current exchange trading rules and symbol information + +**Weight:** +1 + +**Parameters:** +NONE + +## Order Book + +> **Response:** + +```javascript +{ + "lastUpdateId": 1027024, + "E": 1589436922972, // Message output time + "T": 1589436922959, // Transaction time + "bids": [ + [ + "4.00000000", // PRICE + "431.00000000" // QTY + ] + ], + "asks": [ + [ + "4.00000200", + "12.00000000" + ] + ] +} +``` + +``GET /fapi/v1/depth`` + +**Weight:** + +Adjusted based on the limit: + +| Limit | Weight | +| ------------- | ------ | +| 5, 10, 20, 50 | 2 | +| 100 | 5 | +| 500 | 10 | +| 1000 | 20 | + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ------ | ------ | --------- | --------------------------------------------------------- | +| symbol | STRING | YES | | +| limit | INT | NO | Default 500; Valid limits:[5, 10, 20, 50, 100, 500, 1000] | + +## Recent Trades List + +> **Response:** + +```javascript +[ + { + "id": 28457, + "price": "4.00000100", + "qty": "12.00000000", + "quoteQty": "48.00", + "time": 1499865549590, + "isBuyerMaker": true, + } +] +``` + +``GET /fapi/v1/trades`` + +Get recent market trades + +**Weight:** +1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ------ | ------ | --------- | ---------------------- | +| symbol | STRING | YES | | +| limit | INT | NO | Default 500; max 1000. | + +* Market trades means trades filled in the order book. Only market trades will be returned, which means the insurance fund trades and ADL trades won't be returned. + +## Old Trades Lookup (MARKET_DATA) + +> **Response:** + +```javascript +[ + { + "id": 28457, + "price": "4.00000100", + "qty": "12.00000000", + "quoteQty": "8000.00", + "time": 1499865549590, + "isBuyerMaker": true, + } +] +``` + +``GET /fapi/v1/historicalTrades`` + +Get older market historical trades. + +**Weight:** +20 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ------ | ------ | --------- | ------------------------------------------------------- | +| symbol | STRING | YES | | +| limit | INT | NO | Default 500; max 1000. | +| fromId | LONG | NO | TradeId to fetch from. Default gets most recent trades. | + +* Market trades means trades filled in the order book. Only market trades will be returned, which means the insurance fund trades and ADL trades won't be returned. + +## Compressed/Aggregate Trades List + +> **Response:** + +```javascript +[ + { + "a": 26129, // Aggregate tradeId + "p": "0.01633102", // Price + "q": "4.70443515", // Quantity + "f": 27781, // First tradeId + "l": 27781, // Last tradeId + "T": 1498793709153, // Timestamp + "m": true, // Was the buyer the maker? + } +] +``` + +``GET /fapi/v1/aggTrades`` + +Get compressed, aggregate market trades. Market trades that fill at the time, from the same order, with the same price will have the quantity aggregated. + +**Weight:** +20 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| --------- | ------ | --------- | -------------------------------------------------------- | +| symbol | STRING | YES | | +| fromId | LONG | NO | ID to get aggregate trades from INCLUSIVE. | +| startTime | LONG | NO | Timestamp in ms to get aggregate trades from INCLUSIVE. | +| endTime | LONG | NO | Timestamp in ms to get aggregate trades until INCLUSIVE. | +| limit | INT | NO | Default 500; max 1000. | + +* If both startTime and endTime are sent, time between startTime and endTime must be less than 1 hour. +* If fromId, startTime, and endTime are not sent, the most recent aggregate trades will be returned. +* Only market trades will be aggregated and returned, which means the insurance fund trades and ADL trades won't be aggregated. + +## Kline/Candlestick Data + +> **Response:** + +```javascript +[ + [ + 1499040000000, // Open time + "0.01634790", // Open + "0.80000000", // High + "0.01575800", // Low + "0.01577100", // Close + "148976.11427815", // Volume + 1499644799999, // Close time + "2434.19055334", // Quote asset volume + 308, // Number of trades + "1756.87402397", // Taker buy base asset volume + "28.46694368", // Taker buy quote asset volume + "17928899.62484339" // Ignore. + ] +] +``` + +``GET /fapi/v1/klines`` + +Kline/candlestick bars for a symbol. +Klines are uniquely identified by their open time. + +**Weight:** based on parameter `LIMIT` + +| LIMIT | weight | +| ----------- | ------ | +| [1,100) | 1 | +| [100, 500) | 2 | +| [500, 1000] | 5 | + +> 1000 | 10 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| --------- | ------ | --------- | ---------------------- | +| symbol | STRING | YES | | +| interval | ENUM | YES | | +| startTime | LONG | NO | | +| endTime | LONG | NO | | +| limit | INT | NO | Default 500; max 1500. | + +* If startTime and endTime are not sent, the most recent klines are returned. + +## Index Price Kline/Candlestick Data + +> **Response:** + +```javascript +[ + [ + 1591256400000, // Open time + "9653.69440000", // Open + "9653.69640000", // High + "9651.38600000", // Low + "9651.55200000", // Close (or latest price) + "0 ", // Ignore + 1591256459999, // Close time + "0", // Ignore + 60, // Number of bisic data + "0", // Ignore + "0", // Ignore + "0" // Ignore + ] +] +``` + +``GET /fapi/v1/indexPriceKlines`` + +Kline/candlestick bars for the index price of a pair. + +Klines are uniquely identified by their open time. + +**Weight:** based on parameter `LIMIT` + +| LIMIT | weight | +| ----------- | ------ | +| [1,100) | 1 | +| [100, 500) | 2 | +| [500, 1000] | 5 | + +> 1000 | 10 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| --------- | ------ | --------- | ---------------------- | +| pair | STRING | YES | | +| interval | ENUM | YES | | +| startTime | LONG | NO | | +| endTime | LONG | NO | | +| limit | INT | NO | Default 500; max 1500. | + +* If startTime and endTime are not sent, the most recent klines are returned. + +## Mark Price Kline/Candlestick Data + +> **Response:** + +```javascript +[ + [ + 1591256460000, // Open time + "9653.29201333", // Open + "9654.56401333", // High + "9653.07367333", // Low + "9653.07367333", // Close (or latest price) + "0 ", // Ignore + 1591256519999, // Close time + "0", // Ignore + 60, // Number of bisic data + "0", // Ignore + "0", // Ignore + "0" // Ignore + ] +] +``` + +``GET /fapi/v1/markPriceKlines`` + +Kline/candlestick bars for the mark price of a symbol. + +Klines are uniquely identified by their open time. + +**Weight:** based on parameter `LIMIT` + +| LIMIT | weight | +| ----------- | ------ | +| [1,100) | 1 | +| [100, 500) | 2 | +| [500, 1000] | 5 | + +> 1000 | 10 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| --------- | ------ | --------- | ---------------------- | +| symbol | STRING | YES | | +| interval | ENUM | YES | | +| startTime | LONG | NO | | +| endTime | LONG | NO | | +| limit | INT | NO | Default 500; max 1500. | + +* If startTime and endTime are not sent, the most recent klines are returned. + +## Mark Price + +> **Response:** + +```javascript +{ + "symbol": "BTCUSDT", + "markPrice": "11793.63104562", // mark price + "indexPrice": "11781.80495970", // index price + "estimatedSettlePrice": "11781.16138815", // Estimated Settle Price, only useful in the last hour before the settlement starts. + "lastFundingRate": "0.00038246", // This is the lasted funding rate + "nextFundingTime": 1597392000000, + "interestRate": "0.00010000", + "time": 1597370495002 +} +``` + +> **OR (when symbol not sent)** + +```javascript +[ + { + "symbol": "BTCUSDT", + "markPrice": "11793.63104562", // mark price + "indexPrice": "11781.80495970", // index price + "estimatedSettlePrice": "11781.16138815", // Estimated Settle Price, only useful in the last hour before the settlement starts. + "lastFundingRate": "0.00038246", // This is the lasted funding rate + "nextFundingTime": 1597392000000, + "interestRate": "0.00010000", + "time": 1597370495002 + } +] +``` + +``GET /fapi/v1/premiumIndex`` + +Mark Price and Funding Rate + +**Weight:** +1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ------ | ------ | --------- | ----------- | +| symbol | STRING | NO | | + +## Get Funding Rate History + +> **Response:** + +```javascript +[ + { + "symbol": "BTCUSDT", + "fundingRate": "-0.03750000", + "fundingTime": 1570608000000, + }, + { + "symbol": "BTCUSDT", + "fundingRate": "0.00010000", + "fundingTime": 1570636800000, + } +] +``` + +``GET /fapi/v1/fundingRate`` + +**Weight:** +1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| --------- | ------ | --------- | ----------------------------------------------------- | +| symbol | STRING | NO | | +| startTime | LONG | NO | Timestamp in ms to get funding rate from INCLUSIVE. | +| endTime | LONG | NO | Timestamp in ms to get funding rate until INCLUSIVE. | +| limit | INT | NO | Default 100; max 1000 | + +* If `startTime` and `endTime` are not sent, the most recent `limit` datas are returned. +* If the number of data between `startTime` and `endTime` is larger than `limit`, return as `startTime` + `limit`. +* In ascending order. + +## 24hr Ticker Price Change Statistics + +> **Response:** + +```javascript +{ + "symbol": "BTCUSDT", + "priceChange": "-94.99999800", + "priceChangePercent": "-95.960", + "weightedAvgPrice": "0.29628482", + "prevClosePrice": "0.10002000", + "lastPrice": "4.00000200", + "lastQty": "200.00000000", + "openPrice": "99.00000000", + "highPrice": "100.00000000", + "lowPrice": "0.10000000", + "volume": "8913.30000000", + "quoteVolume": "15.30000000", + "openTime": 1499783499040, + "closeTime": 1499869899040, + "firstId": 28385, // First tradeId + "lastId": 28460, // Last tradeId + "count": 76 // Trade count +} +``` + +> OR + +```javascript +[ + { + "symbol": "BTCUSDT", + "priceChange": "-94.99999800", + "priceChangePercent": "-95.960", + "weightedAvgPrice": "0.29628482", + "prevClosePrice": "0.10002000", + "lastPrice": "4.00000200", + "lastQty": "200.00000000", + "openPrice": "99.00000000", + "highPrice": "100.00000000", + "lowPrice": "0.10000000", + "volume": "8913.30000000", + "quoteVolume": "15.30000000", + "openTime": 1499783499040, + "closeTime": 1499869899040, + "firstId": 28385, // First tradeId + "lastId": 28460, // Last tradeId + "count": 76 // Trade count + } +] +``` + +``GET /fapi/v1/ticker/24hr`` + +24 hour rolling window price change statistics. +**Careful** when accessing this with no symbol. + +**Weight:** +1 for a single symbol; +**40** when the symbol parameter is omitted + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ------ | ------ | --------- | ----------- | +| symbol | STRING | NO | | + +* If the symbol is not sent, tickers for all symbols will be returned in an array. + +## Symbol Price Ticker + +> **Response:** + +```javascript +{ + "symbol": "BTCUSDT", + "price": "6000.01", + "time": 1589437530011 // Transaction time +} +``` + +> OR + +```javascript +[ + { + "symbol": "BTCUSDT", + "price": "6000.01", + "time": 1589437530011 + } +] +``` + +``GET /fapi/v1/ticker/price`` + +Latest price for a symbol or symbols. + +**Weight:** +1 for a single symbol; +**2** when the symbol parameter is omitted + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ------ | ------ | --------- | ----------- | +| symbol | STRING | NO | | + +* If the symbol is not sent, prices for all symbols will be returned in an array. + +## Symbol Order Book Ticker + +> **Response:** + +```javascript +{ + "symbol": "BTCUSDT", + "bidPrice": "4.00000000", + "bidQty": "431.00000000", + "askPrice": "4.00000200", + "askQty": "9.00000000", + "time": 1589437530011 // Transaction time +} +``` + +> OR + +```javascript +[ + { + "symbol": "BTCUSDT", + "bidPrice": "4.00000000", + "bidQty": "431.00000000", + "askPrice": "4.00000200", + "askQty": "9.00000000", + "time": 1589437530011 + } +] +``` + +``GET /fapi/v1/ticker/bookTicker`` + +Best price/qty on the order book for a symbol or symbols. + +**Weight:** +1 for a single symbol; +**2** when the symbol parameter is omitted + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ------ | ------ | --------- | ----------- | +| symbol | STRING | NO | | + +* If the symbol is not sent, bookTickers for all symbols will be returned in an array. + +# Websocket Market Streams + +* The baseurl for websocket is **wss://fstream.asterdex.com** +* Streams can be access either in a single raw stream or a combined stream +* Raw streams are accessed at **/ws/\** +* Combined streams are accessed at **/stream?streams=\/\/\** +* Combined stream events are wrapped as follows: **{"stream":"\","data":\}** +* All symbols for streams are **lowercase** +* A single connection is only valid for 24 hours; expect to be disconnected at the 24 hour mark +* The websocket server will send a `ping frame` every 5 minutes. If the websocket server does not receive a `pong frame` back from the connection within a 15 minute period, the connection will be disconnected. Unsolicited `pong frames` are allowed. +* WebSocket connections have a limit of 10 incoming messages per second. +* A connection that goes beyond the limit will be disconnected; IPs that are repeatedly disconnected may be banned. +* A single connection can listen to a maximum of **200** streams. +* Considering the possible data latency from RESTful endpoints during an extremely volatile market, it is highly recommended to get the order status, position, etc from the Websocket user data stream. + +## Live Subscribing/Unsubscribing to streams + +* The following data can be sent through the websocket instance in order to subscribe/unsubscribe from streams. Examples can be seen below. +* The `id` used in the JSON payloads is an unsigned INT used as an identifier to uniquely identify the messages going back and forth. + +### Subscribe to a stream + +> **Response** + +```javascript +{ + "result": null, + "id": 1 +} +``` + +* **Request** + + { + "method": "SUBSCRIBE", + "params": + [ + "btcusdt@aggTrade", + "btcusdt@depth" + ], + "id": 1 + } + +### Unsubscribe to a stream + +> **Response** + +```javascript +{ + "result": null, + "id": 312 +} +``` + +* **Request** + + { + "method": "UNSUBSCRIBE", + "params": + [ + "btcusdt@depth" + ], + "id": 312 + } + +### Listing Subscriptions + +> **Response** + +```javascript +{ + "result": [ + "btcusdt@aggTrade" + ], + "id": 3 +} +``` + +* **Request** + + { + "method": "LIST_SUBSCRIPTIONS", + "id": 3 + } + +### Setting Properties + +Currently, the only property can be set is to set whether `combined` stream payloads are enabled are not. +The combined property is set to `false` when connecting using `/ws/` ("raw streams") and `true` when connecting using `/stream/`. + +> **Response** + +```javascript +{ + "result": null, + "id": 5 +} +``` + +* **Request** + + { + "method": "SET_PROPERTY", + "params": + [ + "combined", + true + ], + "id": 5 + } + +### Retrieving Properties + +> **Response** + +```javascript +{ + "result": true, // Indicates that combined is set to true. + "id": 2 +} +``` + +* **Request** + + { + "method": "GET_PROPERTY", + "params": + [ + "combined" + ], + "id": 2 + } + +### Error Messages + +| Error Message | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------- | +| {"code": 0, "msg": "Unknown property"} | Parameter used in the`SET_PROPERTY` or `GET_PROPERTY` was invalid | +| {"code": 1, "msg": "Invalid value type: expected Boolean"} | Value should only be`true` or `false` | +| {"code": 2, "msg": "Invalid request: property name must be a string"} | Property name provided was invalid | +| {"code": 2, "msg": "Invalid request: request ID must be an unsigned integer"} | Parameter`id` had to be provided or the value provided in the `id` parameter is an unsupported type | +| {"code": 2, "msg": "Invalid request: unknown variant %s, expected one of`SUBSCRIBE`, `UNSUBSCRIBE`, `LIST_SUBSCRIPTIONS`, `SET_PROPERTY`, `GET_PROPERTY` at line 1 column 28"} | Possible typo in the provided method or provided method was neither of the expected values | +| {"code": 2, "msg": "Invalid request: too many parameters"} | Unnecessary parameters provided in the data | +| {"code": 2, "msg": "Invalid request: property name must be a string"} | Property name was not provided | +| {"code": 2, "msg": "Invalid request: missing field`method` at line 1 column 73"} | `method` was not provided in the data | +| {"code":3,"msg":"Invalid JSON: expected value at line %s column %s"} | JSON data sent has incorrect syntax. | + +## Aggregate Trade Streams + +> **Payload:** + +```javascript +{ + "e": "aggTrade", // Event type + "E": 123456789, // Event time + "s": "BTCUSDT", // Symbol + "a": 5933014, // Aggregate trade ID + "p": "0.001", // Price + "q": "100", // Quantity + "f": 100, // First trade ID + "l": 105, // Last trade ID + "T": 123456785, // Trade time + "m": true, // Is the buyer the market maker? +} +``` + +The Aggregate Trade Streams push market trade information that is aggregated for a single taker order every 100 milliseconds. + +**Stream Name:** +``@aggTrade`` + +**Update Speed:** 100ms + +* Only market trades will be aggregated, which means the insurance fund trades and ADL trades won't be aggregated. + +## Mark Price Stream + +> **Payload:** + +```javascript +{ + "e": "markPriceUpdate", // Event type + "E": 1562305380000, // Event time + "s": "BTCUSDT", // Symbol + "p": "11794.15000000", // Mark price + "i": "11784.62659091", // Index price + "P": "11784.25641265", // Estimated Settle Price, only useful in the last hour before the settlement starts + "r": "0.00038167", // Funding rate + "T": 1562306400000 // Next funding time + } +``` + +Mark price and funding rate for a single symbol pushed every 3 seconds or every second. + +**Stream Name:** +``@markPrice`` or ``@markPrice@1s`` + +**Update Speed:** 3000ms or 1000ms + +## Mark Price Stream for All market + +> **Payload:** + +```javascript +[ + { + "e": "markPriceUpdate", // Event type + "E": 1562305380000, // Event time + "s": "BTCUSDT", // Symbol + "p": "11185.87786614", // Mark price + "i": "11784.62659091" // Index price + "P": "11784.25641265", // Estimated Settle Price, only useful in the last hour before the settlement starts + "r": "0.00030000", // Funding rate + "T": 1562306400000 // Next funding time + } +] +``` + +Mark price and funding rate for all symbols pushed every 3 seconds or every second. + +**Stream Name:** +``!markPrice@arr`` or ``!markPrice@arr@1s`` + +**Update Speed:** 3000ms or 1000ms + +## Kline/Candlestick Streams + +> **Payload:** + +```javascript +{ + "e": "kline", // Event type + "E": 123456789, // Event time + "s": "BTCUSDT", // Symbol + "k": { + "t": 123400000, // Kline start time + "T": 123460000, // Kline close time + "s": "BTCUSDT", // Symbol + "i": "1m", // Interval + "f": 100, // First trade ID + "L": 200, // Last trade ID + "o": "0.0010", // Open price + "c": "0.0020", // Close price + "h": "0.0025", // High price + "l": "0.0015", // Low price + "v": "1000", // Base asset volume + "n": 100, // Number of trades + "x": false, // Is this kline closed? + "q": "1.0000", // Quote asset volume + "V": "500", // Taker buy base asset volume + "Q": "0.500", // Taker buy quote asset volume + "B": "123456" // Ignore + } +} +``` + +The Kline/Candlestick Stream push updates to the current klines/candlestick every 250 milliseconds (if existing). + +**Kline/Candlestick chart intervals:** + +m -> minutes; h -> hours; d -> days; w -> weeks; M -> months + +* 1m +* 3m +* 5m +* 15m +* 30m +* 1h +* 2h +* 4h +* 6h +* 8h +* 12h +* 1d +* 3d +* 1w +* 1M + +**Stream Name:** +``@kline_`` + +**Update Speed:** 250ms + +## Individual Symbol Mini Ticker Stream + +> **Payload:** + +```javascript +{ + "e": "24hrMiniTicker", // Event type + "E": 123456789, // Event time + "s": "BTCUSDT", // Symbol + "c": "0.0025", // Close price + "o": "0.0010", // Open price + "h": "0.0025", // High price + "l": "0.0010", // Low price + "v": "10000", // Total traded base asset volume + "q": "18" // Total traded quote asset volume + } +``` + +24hr rolling window mini-ticker statistics for a single symbol. These are NOT the statistics of the UTC day, but a 24hr rolling window from requestTime to 24hrs before. + +**Stream Name:** +``@miniTicker`` + +**Update Speed:** 500ms + +## All Market Mini Tickers Stream + +> **Payload:** + +```javascript +[ + { + "e": "24hrMiniTicker", // Event type + "E": 123456789, // Event time + "s": "BTCUSDT", // Symbol + "c": "0.0025", // Close price + "o": "0.0010", // Open price + "h": "0.0025", // High price + "l": "0.0010", // Low price + "v": "10000", // Total traded base asset volume + "q": "18" // Total traded quote asset volume + } +] +``` + +24hr rolling window mini-ticker statistics for all symbols. These are NOT the statistics of the UTC day, but a 24hr rolling window from requestTime to 24hrs before. Note that only tickers that have changed will be present in the array. + +**Stream Name:** +``!miniTicker@arr`` + +**Update Speed:** 1000ms + +## Individual Symbol Ticker Streams + +> **Payload:** + +```javascript +{ + "e": "24hrTicker", // Event type + "E": 123456789, // Event time + "s": "BTCUSDT", // Symbol + "p": "0.0015", // Price change + "P": "250.00", // Price change percent + "w": "0.0018", // Weighted average price + "c": "0.0025", // Last price + "Q": "10", // Last quantity + "o": "0.0010", // Open price + "h": "0.0025", // High price + "l": "0.0010", // Low price + "v": "10000", // Total traded base asset volume + "q": "18", // Total traded quote asset volume + "O": 0, // Statistics open time + "C": 86400000, // Statistics close time + "F": 0, // First trade ID + "L": 18150, // Last trade Id + "n": 18151 // Total number of trades +} +``` + +24hr rollwing window ticker statistics for a single symbol. These are NOT the statistics of the UTC day, but a 24hr rolling window from requestTime to 24hrs before. + +**Stream Name:** +``@ticker`` + +**Update Speed:** 500ms + +## All Market Tickers Streams + +> **Payload:** + +```javascript +[ + { + "e": "24hrTicker", // Event type + "E": 123456789, // Event time + "s": "BTCUSDT", // Symbol + "p": "0.0015", // Price change + "P": "250.00", // Price change percent + "w": "0.0018", // Weighted average price + "c": "0.0025", // Last price + "Q": "10", // Last quantity + "o": "0.0010", // Open price + "h": "0.0025", // High price + "l": "0.0010", // Low price + "v": "10000", // Total traded base asset volume + "q": "18", // Total traded quote asset volume + "O": 0, // Statistics open time + "C": 86400000, // Statistics close time + "F": 0, // First trade ID + "L": 18150, // Last trade Id + "n": 18151 // Total number of trades + } +] +``` + +24hr rollwing window ticker statistics for all symbols. These are NOT the statistics of the UTC day, but a 24hr rolling window from requestTime to 24hrs before. Note that only tickers that have changed will be present in the array. + +**Stream Name:** +``!ticker@arr`` + +**Update Speed:** 1000ms + +## Individual Symbol Book Ticker Streams + +> **Payload:** + +```javascript +{ + "e":"bookTicker", // event type + "u":400900217, // order book updateId + "E": 1568014460893, // event time + "T": 1568014460891, // transaction time + "s":"BNBUSDT", // symbol + "b":"25.35190000", // best bid price + "B":"31.21000000", // best bid qty + "a":"25.36520000", // best ask price + "A":"40.66000000" // best ask qty +} +``` + +Pushes any update to the best bid or ask's price or quantity in real-time for a specified symbol. + +**Stream Name:** `@bookTicker` + +**Update Speed:** Real-time + +## All Book Tickers Stream + +> **Payload:** + +```javascript +{ + // Same as @bookTicker payload +} +``` + +Pushes any update to the best bid or ask's price or quantity in real-time for all symbols. + +**Stream Name:** `!bookTicker` + +**Update Speed:** Real-time + +## Liquidation Order Streams + +> **Payload:** + +```javascript +{ + + "e":"forceOrder", // Event Type + "E":1568014460893, // Event Time + "o":{ + + "s":"BTCUSDT", // Symbol + "S":"SELL", // Side + "o":"LIMIT", // Order Type + "f":"IOC", // Time in Force + "q":"0.014", // Original Quantity + "p":"9910", // Price + "ap":"9910", // Average Price + "X":"FILLED", // Order Status + "l":"0.014", // Order Last Filled Quantity + "z":"0.014", // Order Filled Accumulated Quantity + "T":1568014460893, // Order Trade Time + + } + +} +``` + +The Liquidation Order Snapshot Streams push force liquidation order information for specific symbol. + +For each symbol,only the latest one liquidation order within 1000ms will be pushed as the snapshot. If no liquidation happens in the interval of 1000ms, no stream will be pushed. + +**Stream Name:** ``@forceOrder`` + +**Update Speed:** 1000ms + +## All Market Liquidation Order Streams + +> **Payload:** + +```javascript +{ + + "e":"forceOrder", // Event Type + "E":1568014460893, // Event Time + "o":{ + + "s":"BTCUSDT", // Symbol + "S":"SELL", // Side + "o":"LIMIT", // Order Type + "f":"IOC", // Time in Force + "q":"0.014", // Original Quantity + "p":"9910", // Price + "ap":"9910", // Average Price + "X":"FILLED", // Order Status + "l":"0.014", // Order Last Filled Quantity + "z":"0.014", // Order Filled Accumulated Quantity + "T":1568014460893, // Order Trade Time + + } + +} +``` + +The All Liquidation Order Snapshot Streams push force liquidation order information for all symbols in the market. + +For each symbol,only the latest one liquidation order within 1000ms will be pushed as the snapshot. If no liquidation happens in the interval of 1000ms, no stream will be pushed. + +**Stream Name:** ``!forceOrder@arr`` + +**Update Speed:** 1000ms + +## Partial Book Depth Streams + +> **Payload:** + +```javascript +{ + "e": "depthUpdate", // Event type + "E": 1571889248277, // Event time + "T": 1571889248276, // Transaction time + "s": "BTCUSDT", + "U": 390497796, + "u": 390497878, + "pu": 390497794, + "b": [ // Bids to be updated + [ + "7403.89", // Price Level to be + "0.002" // Quantity + ], + [ + "7403.90", + "3.906" + ], + [ + "7404.00", + "1.428" + ], + [ + "7404.85", + "5.239" + ], + [ + "7405.43", + "2.562" + ] + ], + "a": [ // Asks to be updated + [ + "7405.96", // Price level to be + "3.340" // Quantity + ], + [ + "7406.63", + "4.525" + ], + [ + "7407.08", + "2.475" + ], + [ + "7407.15", + "4.800" + ], + [ + "7407.20", + "0.175" + ] + ] +} +``` + +Top **** bids and asks, Valid **** are 5, 10, or 20. + +**Stream Names:** `@depth` OR `@depth@500ms` OR `@depth@100ms`. + +**Update Speed:** 250ms, 500ms or 100ms + +## Diff. Book Depth Streams + +> **Payload:** + +```javascript +{ + "e": "depthUpdate", // Event type + "E": 123456789, // Event time + "T": 123456788, // Transaction time + "s": "BTCUSDT", // Symbol + "U": 157, // First update ID in event + "u": 160, // Final update ID in event + "pu": 149, // Final update Id in last stream(ie `u` in last stream) + "b": [ // Bids to be updated + [ + "0.0024", // Price level to be updated + "10" // Quantity + ] + ], + "a": [ // Asks to be updated + [ + "0.0026", // Price level to be updated + "100" // Quantity + ] + ] +} +``` + +Bids and asks, pushed every 250 milliseconds, 500 milliseconds, 100 milliseconds (if existing) + +**Stream Name:** +``@depth`` OR ``@depth@500ms`` OR ``@depth@100ms`` + +**Update Speed:** 250ms, 500ms, 100ms + +## How to manage a local order book correctly + +1. Open a stream to **wss://fstream.asterdex.com/stream?streams=btcusdt@depth**. +2. Buffer the events you receive from the stream. For same price, latest received update covers the previous one. +3. Get a depth snapshot from **https://fapi.asterdex.com/fapi/v1/depth?symbol=BTCUSDT&limit=1000** . +4. Drop any event where `u` is < `lastUpdateId` in the snapshot. +5. The first processed event should have `U` <= `lastUpdateId` **AND** `u` >= `lastUpdateId` +6. While listening to the stream, each new event's `pu` should be equal to the previous event's `u`, otherwise initialize the process from step 3. +7. The data in each event is the **absolute** quantity for a price level. +8. If the quantity is 0, **remove** the price level. +9. Receiving an event that removes a price level that is not in your local order book can happen and is normal. + +# Account/Trades Endpoints + + + +## Change Position Mode(TRADE) + +> **Response:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +``POST /fapi/v1/positionSide/dual (HMAC SHA256)`` + +Change user's position mode (Hedge Mode or One-way Mode ) on ***EVERY symbol*** + +**Weight:** +1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ---------------- | ------ | --------- | ----------------------------------------- | +| dualSidePosition | STRING | YES | "true": Hedge Mode; "false": One-way Mode | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +## Get Current Position Mode(USER_DATA) + +> **Response:** + +```javascript +{ + "dualSidePosition": true // "true": Hedge Mode; "false": One-way Mode +} +``` + +``GET /fapi/v1/positionSide/dual (HMAC SHA256)`` + +Get user's position mode (Hedge Mode or One-way Mode ) on ***EVERY symbol*** + +**Weight:** +30 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ---------- | ---- | --------- | ----------- | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +## Change Multi-Assets Mode (TRADE) + +> **Response:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +``POST /fapi/v1/multiAssetsMargin (HMAC SHA256)`` + +Change user's Multi-Assets mode (Multi-Assets Mode or Single-Asset Mode) on ***Every symbol*** + +**Weight:** +1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ----------------- | ------ | --------- | ----------------------------------------------------- | +| multiAssetsMargin | STRING | YES | "true": Multi-Assets Mode; "false": Single-Asset Mode | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +## Get Current Multi-Assets Mode (USER_DATA) + +> **Response:** + +```javascript +{ + "multiAssetsMargin": true // "true": Multi-Assets Mode; "false": Single-Asset Mode +} +``` + +``GET /fapi/v1/multiAssetsMargin (HMAC SHA256)`` + +Get user's Multi-Assets mode (Multi-Assets Mode or Single-Asset Mode) on ***Every symbol*** + +**Weight:** +30 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ---------- | ---- | --------- | ----------- | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +## New Order (TRADE) + +> **Response:** + +```javascript +{ + "clientOrderId": "testOrder", + "cumQty": "0", + "cumQuote": "0", + "executedQty": "0", + "orderId": 22542179, + "avgPrice": "0.00000", + "origQty": "10", + "price": "0", + "reduceOnly": false, + "side": "BUY", + "positionSide": "SHORT", + "status": "NEW", + "stopPrice": "9300", // please ignore when order type is TRAILING_STOP_MARKET + "closePosition": false, // if Close-All + "symbol": "BTCUSDT", + "timeInForce": "GTC", + "type": "TRAILING_STOP_MARKET", + "origType": "TRAILING_STOP_MARKET", + "activatePrice": "9020", // activation price, only return with TRAILING_STOP_MARKET order + "priceRate": "0.3", // callback rate, only return with TRAILING_STOP_MARKET order + "updateTime": 1566818724722, + "workingType": "CONTRACT_PRICE", + "priceProtect": false // if conditional order trigger is protected +} +``` + +``POST /fapi/v1/order (HMAC SHA256)`` + +Send in a new order. + +**Weight:** +1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ---------------- | ------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------- | +| symbol | STRING | YES | | +| side | ENUM | YES | | +| positionSide | ENUM | NO | Default`BOTH` for One-way Mode ; `LONG` or `SHORT` for Hedge Mode. It must be sent in Hedge Mode. | +| type | ENUM | YES | | +| timeInForce | ENUM | NO | | +| quantity | DECIMAL | NO | Cannot be sent with`closePosition`=`true`(Close-All) | +| reduceOnly | STRING | NO | "true" or "false". default "false". Cannot be sent in Hedge Mode; cannot be sent with`closePosition`=`true` | +| price | DECIMAL | NO | | +| newClientOrderId | STRING | NO | A unique id among open orders. Automatically generated if not sent. Can only be string following the rule:`^[\.A-Z\:/a-z0-9_-]{1,36}$` | +| stopPrice | DECIMAL | NO | Used with`STOP/STOP_MARKET` or `TAKE_PROFIT/TAKE_PROFIT_MARKET` orders. | +| closePosition | STRING | NO | `true`, `false`;Close-All,used with `STOP_MARKET` or `TAKE_PROFIT_MARKET`. | +| activationPrice | DECIMAL | NO | Used with`TRAILING_STOP_MARKET` orders, default as the latest price(supporting different `workingType`) | +| callbackRate | DECIMAL | NO | Used with`TRAILING_STOP_MARKET` orders, min 0.1, max 5 where 1 for 1% | +| workingType | ENUM | NO | stopPrice triggered by: "MARK_PRICE", "CONTRACT_PRICE". Default "CONTRACT_PRICE" | +| priceProtect | STRING | NO | "TRUE" or "FALSE", default "FALSE". Used with`STOP/STOP_MARKET` or `TAKE_PROFIT/TAKE_PROFIT_MARKET` orders. | +| newOrderRespType | ENUM | NO | "ACK", "RESULT", default "ACK" | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +Additional mandatory parameters based on `type`: + +| Type | Additional mandatory parameters | +| -------------------------------- | ---------------------------------- | +| `LIMIT` | `timeInForce`, `quantity`, `price` | +| `MARKET` | `quantity` | +| `STOP/TAKE_PROFIT` | `quantity`, `price`, `stopPrice` | +| `STOP_MARKET/TAKE_PROFIT_MARKET` | `stopPrice` | +| `TRAILING_STOP_MARKET` | `callbackRate` | + +* Order with type `STOP`, parameter `timeInForce` can be sent ( default `GTC`). +* Order with type `TAKE_PROFIT`, parameter `timeInForce` can be sent ( default `GTC`). +* Condition orders will be triggered when: + + * If parameter`priceProtect`is sent as true: + + * when price reaches the `stopPrice` ,the difference rate between "MARK_PRICE" and "CONTRACT_PRICE" cannot be larger than the "triggerProtect" of the symbol + * "triggerProtect" of a symbol can be got from `GET /fapi/v1/exchangeInfo` + * `STOP`, `STOP_MARKET`: + + * BUY: latest price ("MARK_PRICE" or "CONTRACT_PRICE") >= `stopPrice` + * SELL: latest price ("MARK_PRICE" or "CONTRACT_PRICE") <= `stopPrice` + * `TAKE_PROFIT`, `TAKE_PROFIT_MARKET`: + + * BUY: latest price ("MARK_PRICE" or "CONTRACT_PRICE") <= `stopPrice` + * SELL: latest price ("MARK_PRICE" or "CONTRACT_PRICE") >= `stopPrice` + * `TRAILING_STOP_MARKET`: + + * BUY: the lowest price after order placed <= `activationPrice`, and the latest price >= the lowest price * (1 + `callbackRate`) + * SELL: the highest price after order placed >= `activationPrice`, and the latest price <= the highest price * (1 - `callbackRate`) +* For `TRAILING_STOP_MARKET`, if you got such error code.``{"code": -2021, "msg": "Order would immediately trigger."}``means that the parameters you send do not meet the following requirements: + + * BUY: `activationPrice` should be smaller than latest price. + * SELL: `activationPrice` should be larger than latest price. +* If `newOrderRespType ` is sent as `RESULT` : + + * `MARKET` order: the final FILLED result of the order will be return directly. + * `LIMIT` order with special `timeInForce`: the final status result of the order(FILLED or EXPIRED) will be returned directly. +* `STOP_MARKET`, `TAKE_PROFIT_MARKET` with `closePosition`=`true`: + + * Follow the same rules for condition orders. + * If triggered,**close all** current long position( if `SELL`) or current short position( if `BUY`). + * Cannot be used with `quantity` paremeter + * Cannot be used with `reduceOnly` parameter + * In Hedge Mode,cannot be used with `BUY` orders in `LONG` position side. and cannot be used with `SELL` orders in `SHORT` position side + +## Place Multiple Orders (TRADE) + +> **Response:** + +```javascript +[ + { + "clientOrderId": "testOrder", + "cumQty": "0", + "cumQuote": "0", + "executedQty": "0", + "orderId": 22542179, + "avgPrice": "0.00000", + "origQty": "10", + "price": "0", + "reduceOnly": false, + "side": "BUY", + "positionSide": "SHORT", + "status": "NEW", + "stopPrice": "9300", // please ignore when order type is TRAILING_STOP_MARKET + "symbol": "BTCUSDT", + "timeInForce": "GTC", + "type": "TRAILING_STOP_MARKET", + "origType": "TRAILING_STOP_MARKET", + "activatePrice": "9020", // activation price, only return with TRAILING_STOP_MARKET order + "priceRate": "0.3", // callback rate, only return with TRAILING_STOP_MARKET order + "updateTime": 1566818724722, + "workingType": "CONTRACT_PRICE", + "priceProtect": false // if conditional order trigger is protected + }, + { + "code": -2022, + "msg": "ReduceOnly Order is rejected." + } +] +``` + +``POST /fapi/v1/batchOrders (HMAC SHA256)`` + +**Weight:** +5 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ----------- | ---------- | --------- | ------------------------ | +| batchOrders | LIST | YES | order list. Max 5 orders | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +**Where ``batchOrders`` is the list of order parameters in JSON** + +| Name | Type | Mandatory | Description | +| ---------------- | ------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------- | +| symbol | STRING | YES | | +| side | ENUM | YES | | +| positionSide | ENUM | NO | Default`BOTH` for One-way Mode ; `LONG` or `SHORT` for Hedge Mode. It must be sent with Hedge Mode. | +| type | ENUM | YES | | +| timeInForce | ENUM | NO | | +| quantity | DECIMAL | YES | | +| reduceOnly | STRING | NO | "true" or "false". default "false". | +| price | DECIMAL | NO | | +| newClientOrderId | STRING | NO | A unique id among open orders. Automatically generated if not sent. Can only be string following the rule:`^[\.A-Z\:/a-z0-9_-]{1,36}$` | +| stopPrice | DECIMAL | NO | Used with`STOP/STOP_MARKET` or `TAKE_PROFIT/TAKE_PROFIT_MARKET` orders. | +| activationPrice | DECIMAL | NO | Used with`TRAILING_STOP_MARKET` orders, default as the latest price(supporting different `workingType`) | +| callbackRate | DECIMAL | NO | Used with`TRAILING_STOP_MARKET` orders, min 0.1, max 4 where 1 for 1% | +| workingType | ENUM | NO | stopPrice triggered by: "MARK_PRICE", "CONTRACT_PRICE". Default "CONTRACT_PRICE" | +| priceProtect | STRING | NO | "TRUE" or "FALSE", default "FALSE". Used with`STOP/STOP_MARKET` or `TAKE_PROFIT/TAKE_PROFIT_MARKET` orders. | +| newOrderRespType | ENUM | NO | "ACK", "RESULT", default "ACK" | + +* Paremeter rules are same with `New Order` +* Batch orders are processed concurrently, and the order of matching is not guaranteed. +* The order of returned contents for batch orders is the same as the order of the order list. + + +## Transfer Between Futures And Spot (USER_DATA) + +> **Response:** + +```javascript +{ + "tranId": 21841, //transaction id + "status": "SUCCESS" //status +} +``` + +`` +POST /fapi/v3/asset/wallet/transfer (HMAC SHA256) +`` + +**Weight:** +5 + +**Parameters:** + +Name | Type | Mandatory | Description +---------------- | ------- | -------- | ---- +amount | DECIMAL | YES | amount +asset | STRING | YES | asset +clientTranId | STRING | YES | transaction id +kindType | STRING | YES | kindType +timestamp | LONG | YES | timestamp + +Notes: + +* kindType can take the following values: + FUTURE_SPOT (futures converted to spot) + SPOT_FUTURE (spot converted to futures) + + +## Query Order (USER_DATA) + +> **Response:** + +```javascript +{ + "avgPrice": "0.00000", + "clientOrderId": "abc", + "cumQuote": "0", + "executedQty": "0", + "orderId": 1917641, + "origQty": "0.40", + "origType": "TRAILING_STOP_MARKET", + "price": "0", + "reduceOnly": false, + "side": "BUY", + "positionSide": "SHORT", + "status": "NEW", + "stopPrice": "9300", // please ignore when order type is TRAILING_STOP_MARKET + "closePosition": false, // if Close-All + "symbol": "BTCUSDT", + "time": 1579276756075, // order time + "timeInForce": "GTC", + "type": "TRAILING_STOP_MARKET", + "activatePrice": "9020", // activation price, only return with TRAILING_STOP_MARKET order + "priceRate": "0.3", // callback rate, only return with TRAILING_STOP_MARKET order + "updateTime": 1579276756075, // update time + "workingType": "CONTRACT_PRICE", + "priceProtect": false // if conditional order trigger is protected +} +``` + +``GET /fapi/v1/order (HMAC SHA256)`` + +Check an order's status. + +**Weight:** +1 + +* These orders will not be found: + * order status is `CANCELED` or `EXPIRED`, **AND** + * order has NO filled trade, **AND** + * created time + 7 days < current time + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ----------------- | ------ | --------- | ----------- | +| symbol | STRING | YES | | +| orderId | LONG | NO | | +| origClientOrderId | STRING | NO | | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +Notes: + +* Either `orderId` or `origClientOrderId` must be sent. + +## Cancel Order (TRADE) + +> **Response:** + +```javascript +{ + "clientOrderId": "myOrder1", + "cumQty": "0", + "cumQuote": "0", + "executedQty": "0", + "orderId": 283194212, + "origQty": "11", + "origType": "TRAILING_STOP_MARKET", + "price": "0", + "reduceOnly": false, + "side": "BUY", + "positionSide": "SHORT", + "status": "CANCELED", + "stopPrice": "9300", // please ignore when order type is TRAILING_STOP_MARKET + "closePosition": false, // if Close-All + "symbol": "BTCUSDT", + "timeInForce": "GTC", + "type": "TRAILING_STOP_MARKET", + "activatePrice": "9020", // activation price, only return with TRAILING_STOP_MARKET order + "priceRate": "0.3", // callback rate, only return with TRAILING_STOP_MARKET order + "updateTime": 1571110484038, + "workingType": "CONTRACT_PRICE", + "priceProtect": false // if conditional order trigger is protected +} +``` + +``DELETE /fapi/v1/order (HMAC SHA256)`` + +Cancel an active order. + +**Weight:** +1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ----------------- | ------ | --------- | ----------- | +| symbol | STRING | YES | | +| orderId | LONG | NO | | +| origClientOrderId | STRING | NO | | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +Either `orderId` or `origClientOrderId` must be sent. + +## Cancel All Open Orders (TRADE) + +> **Response:** + +```javascript +{ + "code": "200", + "msg": "The operation of cancel all open order is done." +} +``` + +``DELETE /fapi/v1/allOpenOrders (HMAC SHA256)`` + +**Weight:** +1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ---------- | ------ | --------- | ----------- | +| symbol | STRING | YES | | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +## Cancel Multiple Orders (TRADE) + +> **Response:** + +```javascript +[ + { + "clientOrderId": "myOrder1", + "cumQty": "0", + "cumQuote": "0", + "executedQty": "0", + "orderId": 283194212, + "origQty": "11", + "origType": "TRAILING_STOP_MARKET", + "price": "0", + "reduceOnly": false, + "side": "BUY", + "positionSide": "SHORT", + "status": "CANCELED", + "stopPrice": "9300", // please ignore when order type is TRAILING_STOP_MARKET + "closePosition": false, // if Close-All + "symbol": "BTCUSDT", + "timeInForce": "GTC", + "type": "TRAILING_STOP_MARKET", + "activatePrice": "9020", // activation price, only return with TRAILING_STOP_MARKET order + "priceRate": "0.3", // callback rate, only return with TRAILING_STOP_MARKET order + "updateTime": 1571110484038, + "workingType": "CONTRACT_PRICE", + "priceProtect": false // if conditional order trigger is protected + }, + { + "code": -2011, + "msg": "Unknown order sent." + } +] +``` + +``DELETE /fapi/v1/batchOrders (HMAC SHA256)`` + +**Weight:** +1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| --------------------- | -------------- | --------- | ----------------------------------------------------------------------------------------------- | +| symbol | STRING | YES | | +| orderIdList | LIST\ | NO | max length 10 e.g. [1234567,2345678] | +| origClientOrderIdList | LIST\ | NO | max length 10 e.g. ["my_id_1","my_id_2"], encode the double quotes. No space after comma. | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +Either `orderIdList` or `origClientOrderIdList ` must be sent. + +## Auto-Cancel All Open Orders (TRADE) + +> **Response:** + +```javascript +{ + "symbol": "BTCUSDT", + "countdownTime": "100000" +} +``` + +Cancel all open orders of the specified symbol at the end of the specified countdown. + +``POST /fapi/v1/countdownCancelAll (HMAC SHA256)`` + +**Weight:** +10 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ------------- | ------ | --------- | -------------------------------------------------------- | +| symbol | STRING | YES | | +| countdownTime | LONG | YES | countdown time, 1000 for 1 second. 0 to cancel the timer | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +* The endpoint should be called repeatedly as heartbeats so that the existing countdown time can be canceled and replaced by a new one. +* Example usage: + Call this endpoint at 30s intervals with an countdownTime of 120000 (120s). + If this endpoint is not called within 120 seconds, all your orders of the specified symbol will be automatically canceled. + If this endpoint is called with an countdownTime of 0, the countdown timer will be stopped. +* The system will check all countdowns **approximately every 10 milliseconds**, so please note that sufficient redundancy should be considered when using this function. We do not recommend setting the countdown time to be too precise or too small. + +## Query Current Open Order (USER_DATA) + +> **Response:** + +```javascript +{ + "avgPrice": "0.00000", + "clientOrderId": "abc", + "cumQuote": "0", + "executedQty": "0", + "orderId": 1917641, + "origQty": "0.40", + "origType": "TRAILING_STOP_MARKET", + "price": "0", + "reduceOnly": false, + "side": "BUY", + "positionSide": "SHORT", + "status": "NEW", + "stopPrice": "9300", // please ignore when order type is TRAILING_STOP_MARKET + "closePosition": false, // if Close-All + "symbol": "BTCUSDT", + "time": 1579276756075, // order time + "timeInForce": "GTC", + "type": "TRAILING_STOP_MARKET", + "activatePrice": "9020", // activation price, only return with TRAILING_STOP_MARKET order + "priceRate": "0.3", // callback rate, only return with TRAILING_STOP_MARKET order + "updateTime": 1579276756075, + "workingType": "CONTRACT_PRICE", + "priceProtect": false // if conditional order trigger is protected +} +``` + +``GET /fapi/v1/openOrder (HMAC SHA256)`` + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ----------------- | ------ | --------- | ----------- | +| symbol | STRING | YES | | +| orderId | LONG | NO | | +| origClientOrderId | STRING | NO | | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +* Either`orderId` or `origClientOrderId` must be sent +* If the queried order has been filled or cancelled, the error message "Order does not exist" will be returned. + +## Current All Open Orders (USER_DATA) + +> **Response:** + +```javascript +[ + { + "avgPrice": "0.00000", + "clientOrderId": "abc", + "cumQuote": "0", + "executedQty": "0", + "orderId": 1917641, + "origQty": "0.40", + "origType": "TRAILING_STOP_MARKET", + "price": "0", + "reduceOnly": false, + "side": "BUY", + "positionSide": "SHORT", + "status": "NEW", + "stopPrice": "9300", // please ignore when order type is TRAILING_STOP_MARKET + "closePosition": false, // if Close-All + "symbol": "BTCUSDT", + "time": 1579276756075, // order time + "timeInForce": "GTC", + "type": "TRAILING_STOP_MARKET", + "activatePrice": "9020", // activation price, only return with TRAILING_STOP_MARKET order + "priceRate": "0.3", // callback rate, only return with TRAILING_STOP_MARKET order + "updateTime": 1579276756075, // update time + "workingType": "CONTRACT_PRICE", + "priceProtect": false // if conditional order trigger is protected + } +] +``` + +``GET /fapi/v1/openOrders (HMAC SHA256)`` + +Get all open orders on a symbol. **Careful** when accessing this with no symbol. + +**Weight:** +1 for a single symbol; **40** when the symbol parameter is omitted + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ---------- | ------ | --------- | ----------- | +| symbol | STRING | NO | | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +* If the symbol is not sent, orders for all symbols will be returned in an array. + +## All Orders (USER_DATA) + +> **Response:** + +```javascript +[ + { + "avgPrice": "0.00000", + "clientOrderId": "abc", + "cumQuote": "0", + "executedQty": "0", + "orderId": 1917641, + "origQty": "0.40", + "origType": "TRAILING_STOP_MARKET", + "price": "0", + "reduceOnly": false, + "side": "BUY", + "positionSide": "SHORT", + "status": "NEW", + "stopPrice": "9300", // please ignore when order type is TRAILING_STOP_MARKET + "closePosition": false, // if Close-All + "symbol": "BTCUSDT", + "time": 1579276756075, // order time + "timeInForce": "GTC", + "type": "TRAILING_STOP_MARKET", + "activatePrice": "9020", // activation price, only return with TRAILING_STOP_MARKET order + "priceRate": "0.3", // callback rate, only return with TRAILING_STOP_MARKET order + "updateTime": 1579276756075, // update time + "workingType": "CONTRACT_PRICE", + "priceProtect": false // if conditional order trigger is protected + } +] +``` + +``GET /fapi/v1/allOrders (HMAC SHA256)`` + +Get all account orders; active, canceled, or filled. + +* These orders will not be found: + * order status is `CANCELED` or `EXPIRED`, **AND** + * order has NO filled trade, **AND** + * created time + 7 days < current time + +**Weight:** +5 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ---------- | ------ | --------- | ---------------------- | +| symbol | STRING | YES | | +| orderId | LONG | NO | | +| startTime | LONG | NO | | +| endTime | LONG | NO | | +| limit | INT | NO | Default 500; max 1000. | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +**Notes:** + +* If `orderId` is set, it will get orders >= that `orderId`. Otherwise most recent orders are returned. +* The query time period must be less then 7 days( default as the recent 7 days). + +## Futures Account Balance v3 (USER_DATA) + +> **Response:** + +```javascript +[ + { + "accountAlias": "SgsR", // unique account code + "asset": "USDT", // asset name + "balance": "122607.35137903", // wallet balance + "crossWalletBalance": "23.72469206", // crossed wallet balance + "crossUnPnl": "0.00000000" // unrealized profit of crossed positions + "availableBalance": "23.72469206", // available balance + "maxWithdrawAmount": "23.72469206", // maximum amount for transfer out + "marginAvailable": true, // whether the asset can be used as margin in Multi-Assets mode + "updateTime": 1617939110373 + } +] +``` + +``GET /fapi/v3/balance (HMAC SHA256)`` + +**Weight:** +5 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ---------- | ---- | --------- | ----------- | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +## Account Information v3 (USER_DATA) + +> **Response:** + +```javascript +{ + "feeTier": 0, // account commisssion tier + "canTrade": true, // if can trade + "canDeposit": true, // if can transfer in asset + "canWithdraw": true, // if can transfer out asset + "updateTime": 0, + "totalInitialMargin": "0.00000000", // total initial margin required with current mark price (useless with isolated positions), only for USDT asset + "totalMaintMargin": "0.00000000", // total maintenance margin required, only for USDT asset + "totalWalletBalance": "23.72469206", // total wallet balance, only for USDT asset + "totalUnrealizedProfit": "0.00000000", // total unrealized profit, only for USDT asset + "totalMarginBalance": "23.72469206", // total margin balance, only for USDT asset + "totalPositionInitialMargin": "0.00000000", // initial margin required for positions with current mark price, only for USDT asset + "totalOpenOrderInitialMargin": "0.00000000", // initial margin required for open orders with current mark price, only for USDT asset + "totalCrossWalletBalance": "23.72469206", // crossed wallet balance, only for USDT asset + "totalCrossUnPnl": "0.00000000", // unrealized profit of crossed positions, only for USDT asset + "availableBalance": "23.72469206", // available balance, only for USDT asset + "maxWithdrawAmount": "23.72469206" // maximum amount for transfer out, only for USDT asset + "assets": [ + { + "asset": "USDT", // asset name + "walletBalance": "23.72469206", // wallet balance + "unrealizedProfit": "0.00000000", // unrealized profit + "marginBalance": "23.72469206", // margin balance + "maintMargin": "0.00000000", // maintenance margin required + "initialMargin": "0.00000000", // total initial margin required with current mark price + "positionInitialMargin": "0.00000000", //initial margin required for positions with current mark price + "openOrderInitialMargin": "0.00000000", // initial margin required for open orders with current mark price + "crossWalletBalance": "23.72469206", // crossed wallet balance + "crossUnPnl": "0.00000000" // unrealized profit of crossed positions + "availableBalance": "23.72469206", // available balance + "maxWithdrawAmount": "23.72469206", // maximum amount for transfer out + "marginAvailable": true, // whether the asset can be used as margin in Multi-Assets mode + "updateTime": 1625474304765 // last update time + }, + { + "asset": "BUSD", // asset name + "walletBalance": "103.12345678", // wallet balance + "unrealizedProfit": "0.00000000", // unrealized profit + "marginBalance": "103.12345678", // margin balance + "maintMargin": "0.00000000", // maintenance margin required + "initialMargin": "0.00000000", // total initial margin required with current mark price + "positionInitialMargin": "0.00000000", //initial margin required for positions with current mark price + "openOrderInitialMargin": "0.00000000", // initial margin required for open orders with current mark price + "crossWalletBalance": "103.12345678", // crossed wallet balance + "crossUnPnl": "0.00000000" // unrealized profit of crossed positions + "availableBalance": "103.12345678", // available balance + "maxWithdrawAmount": "103.12345678", // maximum amount for transfer out + "marginAvailable": true, // whether the asset can be used as margin in Multi-Assets mode + "updateTime": 1625474304765 // last update time + } + ], + "positions": [ // positions of all symbols in the market are returned + // only "BOTH" positions will be returned with One-way mode + // only "LONG" and "SHORT" positions will be returned with Hedge mode + { + "symbol": "BTCUSDT", // symbol name + "initialMargin": "0", // initial margin required with current mark price + "maintMargin": "0", // maintenance margin required + "unrealizedProfit": "0.00000000", // unrealized profit + "positionInitialMargin": "0", // initial margin required for positions with current mark price + "openOrderInitialMargin": "0", // initial margin required for open orders with current mark price + "leverage": "100", // current initial leverage + "isolated": true, // if the position is isolated + "entryPrice": "0.00000", // average entry price + "maxNotional": "250000", // maximum available notional with current leverage + "positionSide": "BOTH", // position side + "positionAmt": "0", // position amount + "updateTime": 0 // last update time + } + ] +} +``` + +``GET /fapi/v3/account (HMAC SHA256)`` + +Get current account information. + +**Weight:** +5 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ---------- | ---- | --------- | ----------- | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +## Change Initial Leverage (TRADE) + +> **Response:** + +```javascript +{ + "leverage": 21, + "maxNotionalValue": "1000000", + "symbol": "BTCUSDT" +} +``` + +``POST /fapi/v1/leverage (HMAC SHA256)`` + +Change user's initial leverage of specific symbol market. + +**Weight:** +1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ---------- | ------ | --------- | ------------------------------------------ | +| symbol | STRING | YES | | +| leverage | INT | YES | target initial leverage: int from 1 to 125 | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +## Change Margin Type (TRADE) + +> **Response:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +``POST /fapi/v1/marginType (HMAC SHA256)`` + +**Weight:** +1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ---------- | ------ | --------- | ----------------- | +| symbol | STRING | YES | | +| marginType | ENUM | YES | ISOLATED, CROSSED | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +## Modify Isolated Position Margin (TRADE) + +> **Response:** + +```javascript +{ + "amount": 100.0, + "code": 200, + "msg": "Successfully modify position margin.", + "type": 1 +} +``` + +``POST /fapi/v1/positionMargin (HMAC SHA256)`` + +**Weight:** +1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ------------ | ------- | --------- | --------------------------------------------------------------------------------------------------- | +| symbol | STRING | YES | | +| positionSide | ENUM | NO | Default`BOTH` for One-way Mode ; `LONG` or `SHORT` for Hedge Mode. It must be sent with Hedge Mode. | +| amount | DECIMAL | YES | | +| type | INT | YES | 1: Add position margin,2: Reduce position margin | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +* Only for isolated symbol + +## Get Position Margin Change History (TRADE) + +> **Response:** + +```javascript +[ + { + "amount": "23.36332311", + "asset": "USDT", + "symbol": "BTCUSDT", + "time": 1578047897183, + "type": 1, + "positionSide": "BOTH" + }, + { + "amount": "100", + "asset": "USDT", + "symbol": "BTCUSDT", + "time": 1578047900425, + "type": 1, + "positionSide": "LONG" + } +] +``` + +``GET /fapi/v1/positionMargin/history (HMAC SHA256)`` + +**Weight:** +1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ---------- | ------ | --------- | ------------------------------------------------- | +| symbol | STRING | YES | | +| type | INT | NO | 1: Add position margin,2: Reduce position margin | +| startTime | LONG | NO | | +| endTime | LONG | NO | | +| limit | INT | NO | Default: 500 | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +## Position Information v3 (USER_DATA) + +> **Response:** + +> For One-way position mode: + +```javascript +[ + { + "entryPrice": "0.00000", + "marginType": "isolated", + "isAutoAddMargin": "false", + "isolatedMargin": "0.00000000", + "leverage": "10", + "liquidationPrice": "0", + "markPrice": "6679.50671178", + "maxNotionalValue": "20000000", + "positionAmt": "0.000", + "symbol": "BTCUSDT", + "unRealizedProfit": "0.00000000", + "positionSide": "BOTH", + "updateTime": 0 + } +] +``` + +> For Hedge position mode: + +```javascript +[ + { + "entryPrice": "6563.66500", + "marginType": "isolated", + "isAutoAddMargin": "false", + "isolatedMargin": "15517.54150468", + "leverage": "10", + "liquidationPrice": "5930.78", + "markPrice": "6679.50671178", + "maxNotionalValue": "20000000", + "positionAmt": "20.000", + "symbol": "BTCUSDT", + "unRealizedProfit": "2316.83423560" + "positionSide": "LONG", + "updateTime": 1625474304765 + }, + { + "entryPrice": "0.00000", + "marginType": "isolated", + "isAutoAddMargin": "false", + "isolatedMargin": "5413.95799991", + "leverage": "10", + "liquidationPrice": "7189.95", + "markPrice": "6679.50671178", + "maxNotionalValue": "20000000", + "positionAmt": "-10.000", + "symbol": "BTCUSDT", + "unRealizedProfit": "-1156.46711780" + "positionSide": "SHORT", + "updateTime": 0 + } +] +``` + +``GET /fapi/v3/positionRisk (HMAC SHA256)`` + +Get current position information. + +**Weight:** +5 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ---------- | ------ | --------- | ----------- | +| symbol | STRING | NO | | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +**Note** +Please use with user data stream `ACCOUNT_UPDATE` to meet your timeliness and accuracy needs. + +## Account Trade List (USER_DATA) + +> **Response:** + +```javascript +[ + { + "buyer": false, + "commission": "-0.07819010", + "commissionAsset": "USDT", + "id": 698759, + "maker": false, + "orderId": 25851813, + "price": "7819.01", + "qty": "0.002", + "quoteQty": "15.63802", + "realizedPnl": "-0.91539999", + "side": "SELL", + "positionSide": "SHORT", + "symbol": "BTCUSDT", + "time": 1569514978020 + } +] +``` + +``GET /fapi/v1/userTrades (HMAC SHA256)`` + +Get trades for a specific account and symbol. + +**Weight:** +5 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ---------- | ------ | --------- | -------------------------------------------------------- | +| symbol | STRING | YES | | +| startTime | LONG | NO | | +| endTime | LONG | NO | | +| fromId | LONG | NO | Trade id to fetch from. Default gets most recent trades. | +| limit | INT | NO | Default 500; max 1000. | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +* 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. +* The parameter `fromId` cannot be sent with `startTime` or `endTime`. + +## Get Income History(USER_DATA) + +> **Response:** + +```javascript +[ + { + "symbol": "", // trade symbol, if existing + "incomeType": "TRANSFER", // income type + "income": "-0.37500000", // income amount + "asset": "USDT", // income asset + "info":"TRANSFER", // extra information + "time": 1570608000000, + "tranId":"9689322392", // transaction id + "tradeId":"" // trade id, if existing + }, + { + "symbol": "BTCUSDT", + "incomeType": "COMMISSION", + "income": "-0.01000000", + "asset": "USDT", + "info":"COMMISSION", + "time": 1570636800000, + "tranId":"9689322392", + "tradeId":"2059192" + } +] +``` + +``GET /fapi/v1/income (HMAC SHA256)`` + +**Weight:** +30 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ---------- | ------ | --------- | -------------------------------------------------------------------------------------------------------------------------------- | +| symbol | STRING | NO | | +| incomeType | STRING | NO | "TRANSFER","WELCOME_BONUS", "REALIZED_PNL","FUNDING_FEE", "COMMISSION", "INSURANCE_CLEAR", and "MARKET_MERCHANT_RETURN_REWARD" | +| startTime | LONG | NO | Timestamp in ms to get funding from INCLUSIVE. | +| endTime | LONG | NO | Timestamp in ms to get funding until INCLUSIVE. | +| limit | INT | NO | Default 100; max 1000 | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +* If neither `startTime` nor `endTime` is sent, the recent 7-day data will be returned. +* If `incomeType ` is not sent, all kinds of flow will be returned +* "trandId" is unique in the same incomeType for a user + +## Notional and Leverage Brackets (USER_DATA) + +> **Response:** + +```javascript +[ + { + "symbol": "ETHUSDT", + "brackets": [ + { + "bracket": 1, // Notional bracket + "initialLeverage": 75, // Max initial leverage for this bracket + "notionalCap": 10000, // Cap notional of this bracket + "notionalFloor": 0, // Notional threshold of this bracket + "maintMarginRatio": 0.0065, // Maintenance ratio for this bracket + "cum":0 // Auxiliary number for quick calculation + + }, + ] + } +] +``` + +> **OR** (if symbol sent) + +```javascript +{ + "symbol": "ETHUSDT", + "brackets": [ + { + "bracket": 1, + "initialLeverage": 75, + "notionalCap": 10000, + "notionalFloor": 0, + "maintMarginRatio": 0.0065, + "cum":0 + }, + ] +} +``` + +``GET /fapi/v1/leverageBracket`` + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ---------- | ------ | --------- | ----------- | +| symbol | STRING | NO | | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +## Position ADL Quantile Estimation (USER_DATA) + +> **Response:** + +```javascript +[ + { + "symbol": "ETHUSDT", + "adlQuantile": + { + // if the positions of the symbol are crossed margined in Hedge Mode, "LONG" and "SHORT" will be returned a same quantile value, and "HEDGE" will be returned instead of "BOTH". + "LONG": 3, + "SHORT": 3, + "HEDGE": 0 // only a sign, ignore the value + } + }, + { + "symbol": "BTCUSDT", + "adlQuantile": + { + // for positions of the symbol are in One-way Mode or isolated margined in Hedge Mode + "LONG": 1, // adl quantile for "LONG" position in hedge mode + "SHORT": 2, // adl qauntile for "SHORT" position in hedge mode + "BOTH": 0 // adl qunatile for position in one-way mode + } + } + ] +``` + +``GET /fapi/v1/adlQuantile`` + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ---------- | ------ | --------- | ----------- | +| symbol | STRING | NO | | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +* Values update every 30s. +* Values 0, 1, 2, 3, 4 shows the queue position and possibility of ADL from low to high. +* For positions of the symbol are in One-way Mode or isolated margined in Hedge Mode, "LONG", "SHORT", and "BOTH" will be returned to show the positions' adl quantiles of different position sides. +* If the positions of the symbol are crossed margined in Hedge Mode: + + * "HEDGE" as a sign will be returned instead of "BOTH"; + * A same value caculated on unrealized pnls on long and short sides' positions will be shown for "LONG" and "SHORT" when there are positions in both of long and short sides. + +## User's Force Orders (USER_DATA) + +> **Response:** + +```javascript +[ + { + "orderId": 6071832819, + "symbol": "BTCUSDT", + "status": "FILLED", + "clientOrderId": "autoclose-1596107620040000020", + "price": "10871.09", + "avgPrice": "10913.21000", + "origQty": "0.001", + "executedQty": "0.001", + "cumQuote": "10.91321", + "timeInForce": "IOC", + "type": "LIMIT", + "reduceOnly": false, + "closePosition": false, + "side": "SELL", + "positionSide": "BOTH", + "stopPrice": "0", + "workingType": "CONTRACT_PRICE", + "origType": "LIMIT", + "time": 1596107620044, + "updateTime": 1596107620087 + } + { + "orderId": 6072734303, + "symbol": "BTCUSDT", + "status": "FILLED", + "clientOrderId": "adl_autoclose", + "price": "11023.14", + "avgPrice": "10979.82000", + "origQty": "0.001", + "executedQty": "0.001", + "cumQuote": "10.97982", + "timeInForce": "GTC", + "type": "LIMIT", + "reduceOnly": false, + "closePosition": false, + "side": "BUY", + "positionSide": "SHORT", + "stopPrice": "0", + "workingType": "CONTRACT_PRICE", + "origType": "LIMIT", + "time": 1596110725059, + "updateTime": 1596110725071 + } +] +``` + +``GET /fapi/v1/forceOrders`` + +**Weight:** 20 with symbol, 50 without symbol + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ------------- | ------ | --------- | ----------------------------------------------------------- | +| symbol | STRING | NO | | +| autoCloseType | ENUM | NO | "LIQUIDATION" for liquidation orders, "ADL" for ADL orders. | +| startTime | LONG | NO | | +| endTime | LONG | NO | | +| limit | INT | NO | Default 50; max 100. | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +* If "autoCloseType" is not sent, orders with both of the types will be returned +* If "startTime" is not sent, data within 7 days before "endTime" can be queried + +## User Commission Rate (USER_DATA) + +> **Response:** + +```javascript +{ + "symbol": "BTCUSDT", + "makerCommissionRate": "0.0002", // 0.02% + "takerCommissionRate": "0.0004" // 0.04% +} +``` + +``GET /fapi/v1/commissionRate (HMAC SHA256)`` + +**Weight:** +20 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ---------- | ------ | --------- | ----------- | +| symbol | STRING | YES | | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +# User Data Streams + +* The base API endpoint is: **https://fapi.asterdex.com** +* A User Data Stream `listenKey` is valid for 60 minutes after creation. +* Doing a `PUT` on a `listenKey` will extend its validity for 60 minutes. +* Doing a `DELETE` on a `listenKey` will close the stream and invalidate the `listenKey`. +* Doing a `POST` on an account with an active `listenKey` will return the currently active `listenKey` and extend its validity for 60 minutes. +* The baseurl for websocket is **wss://fstream.asterdex.com** +* User Data Streams are accessed at **/ws/\** +* User data stream payloads are **not guaranteed** to be in order during heavy periods; **make sure to order your updates using E** +* A single connection to **fstream.asterdex.com** is only valid for 24 hours; expect to be disconnected at the 24 hour mark + +## Start User Data Stream (USER_STREAM) + +> **Response:** + +```javascript +{ + "listenKey": "pqia91ma19a5s61cv6a81va65sdf19v8a65a1a5s61cv6a81va65sdf19v8a65a1" +} +``` + +``POST /fapi/v1/listenKey`` + +Start a new user data stream. The stream will close after 60 minutes unless a keepalive is sent. If the account has an active `listenKey`, that `listenKey` will be returned and its validity will be extended for 60 minutes. + +**Weight:** +1 + +**Parameters:** + +None + +## Keepalive User Data Stream (USER_STREAM) + +> **Response:** + +```javascript +{} +``` + +``PUT /fapi/v1/listenKey`` + +Keepalive a user data stream to prevent a time out. User data streams will close after 60 minutes. It's recommended to send a ping about every 60 minutes. + +**Weight:** +1 + +**Parameters:** + +None + +## Close User Data Stream (USER_STREAM) + +> **Response:** + +```javascript +{} +``` + +``DELETE /fapi/v1/listenKey`` + +Close out a user data stream. + +**Weight:** +1 + +**Parameters:** + +None + +## Event: User Data Stream Expired + +> **Payload:** + +```javascript +{ + 'e': 'listenKeyExpired', // event type + 'E': 1576653824250 // event time +} +``` + +When the `listenKey` used for the user data stream turns expired, this event will be pushed. + +**Notice:** + +* This event is not related to the websocket disconnection. +* This event will be received only when a valid `listenKey` in connection got expired. +* No more user data event will be updated after this event received until a new valid `listenKey` used. + +## Event: Margin Call + +> **Payload:** + +```javascript +{ + "e":"MARGIN_CALL", // Event Type + "E":1587727187525, // Event Time + "cw":"3.16812045", // Cross Wallet Balance. Only pushed with crossed position margin call + "p":[ // Position(s) of Margin Call + { + "s":"ETHUSDT", // Symbol + "ps":"LONG", // Position Side + "pa":"1.327", // Position Amount + "mt":"CROSSED", // Margin Type + "iw":"0", // Isolated Wallet (if isolated position) + "mp":"187.17127", // Mark Price + "up":"-1.166074", // Unrealized PnL + "mm":"1.614445" // Maintenance Margin Required + } + ] +} +``` + +* When the user's position risk ratio is too high, this stream will be pushed. +* This message is only used as risk guidance information and is not recommended for investment strategies. +* In the case of a highly volatile market, there may be the possibility that the user's position has been liquidated at the same time when this stream is pushed out. + +## Event: Balance and Position Update + +> **Payload:** + +```javascript +{ + "e": "ACCOUNT_UPDATE", // Event Type + "E": 1564745798939, // Event Time + "T": 1564745798938 , // Transaction + "a": // Update Data + { + "m":"ORDER", // Event reason type + "B":[ // Balances + { + "a":"USDT", // Asset + "wb":"122624.12345678", // Wallet Balance + "cw":"100.12345678", // Cross Wallet Balance + "bc":"50.12345678" // Balance Change except PnL and Commission + }, + { + "a":"BUSD", + "wb":"1.00000000", + "cw":"0.00000000", + "bc":"-49.12345678" + } + ], + "P":[ + { + "s":"BTCUSDT", // Symbol + "pa":"0", // Position Amount + "ep":"0.00000", // Entry Price + "cr":"200", // (Pre-fee) Accumulated Realized + "up":"0", // Unrealized PnL + "mt":"isolated", // Margin Type + "iw":"0.00000000", // Isolated Wallet (if isolated position) + "ps":"BOTH" // Position Side + }, + { + "s":"BTCUSDT", + "pa":"20", + "ep":"6563.66500", + "cr":"0", + "up":"2850.21200", + "mt":"isolated", + "iw":"13200.70726908", + "ps":"LONG" + }, + { + "s":"BTCUSDT", + "pa":"-10", + "ep":"6563.86000", + "cr":"-45.04000000", + "up":"-1423.15600", + "mt":"isolated", + "iw":"6570.42511771", + "ps":"SHORT" + } + ] + } +} +``` + +Event type is `ACCOUNT_UPDATE`. + +* When balance or position get updated, this event will be pushed. + + * `ACCOUNT_UPDATE` will be pushed only when update happens on user's account, including changes on balances, positions, or margin type. + * Unfilled orders or cancelled orders will not make the event `ACCOUNT_UPDATE` pushed, since there's no change on positions. + * Only positions of symbols with non-zero isolatd wallet or non-zero position amount will be pushed in the "position" part of the event `ACCOUNT_UPDATE` when any position changes. +* When "FUNDING FEE" changes to the user's balance, the event will be pushed with the brief message: + + * When "FUNDING FEE" occurs in a **crossed position**, `ACCOUNT_UPDATE` will be pushed with only the balance `B`(including the "FUNDING FEE" asset only), without any position `P` message. + * When "FUNDING FEE" occurs in an **isolated position**, `ACCOUNT_UPDATE` will be pushed with only the balance `B`(including the "FUNDING FEE" asset only) and the relative position message `P`( including the isolated position on which the "FUNDING FEE" occurs only, without any other position message). +* The field "m" represents the reason type for the event and may shows the following possible types: + + * DEPOSIT + * WITHDRAW + * ORDER + * FUNDING_FEE + * WITHDRAW_REJECT + * ADJUSTMENT + * INSURANCE_CLEAR + * ADMIN_DEPOSIT + * ADMIN_WITHDRAW + * MARGIN_TRANSFER + * MARGIN_TYPE_CHANGE + * ASSET_TRANSFER + * OPTIONS_PREMIUM_FEE + * OPTIONS_SETTLE_PROFIT + * AUTO_EXCHANGE +* The field "bc" represents the balance change except for PnL and commission. + +## Event: Order Update + +> **Payload:** + +```javascript +{ + + "e":"ORDER_TRADE_UPDATE", // Event Type + "E":1568879465651, // Event Time + "T":1568879465650, // Transaction Time + "o":{ + "s":"BTCUSDT", // Symbol + "c":"TEST", // Client Order Id + // special client order id: + // starts with "autoclose-": liquidation order + // "adl_autoclose": ADL auto close order + "S":"SELL", // Side + "o":"TRAILING_STOP_MARKET", // Order Type + "f":"GTC", // Time in Force + "q":"0.001", // Original Quantity + "p":"0", // Original Price + "ap":"0", // Average Price + "sp":"7103.04", // Stop Price. Please ignore with TRAILING_STOP_MARKET order + "x":"NEW", // Execution Type + "X":"NEW", // Order Status + "i":8886774, // Order Id + "l":"0", // Order Last Filled Quantity + "z":"0", // Order Filled Accumulated Quantity + "L":"0", // Last Filled Price + "N":"USDT", // Commission Asset, will not push if no commission + "n":"0", // Commission, will not push if no commission + "T":1568879465651, // Order Trade Time + "t":0, // Trade Id + "b":"0", // Bids Notional + "a":"9.91", // Ask Notional + "m":false, // Is this trade the maker side? + "R":false, // Is this reduce only + "wt":"CONTRACT_PRICE", // Stop Price Working Type + "ot":"TRAILING_STOP_MARKET", // Original Order Type + "ps":"LONG", // Position Side + "cp":false, // If Close-All, pushed with conditional order + "AP":"7476.89", // Activation Price, only puhed with TRAILING_STOP_MARKET order + "cr":"5.0", // Callback Rate, only puhed with TRAILING_STOP_MARKET order + "rp":"0" // Realized Profit of the trade + } + +} +``` + +When new order created, order status changed will push such event. +event type is `ORDER_TRADE_UPDATE`. + +**Side** + +* BUY +* SELL + +**Order Type** + +* MARKET +* LIMIT +* STOP +* TAKE_PROFIT +* LIQUIDATION + +**Execution Type** + +* NEW +* CANCELED +* CALCULATED - Liquidation Execution +* EXPIRED +* TRADE + +**Order Status** + +* NEW +* PARTIALLY_FILLED +* FILLED +* CANCELED +* EXPIRED +* NEW_INSURANCE - Liquidation with Insurance Fund +* NEW_ADL - Counterparty Liquidation` + +**Time in force** + +* GTC +* IOC +* FOK +* GTX + +**Working Type** + +* MARK_PRICE +* CONTRACT_PRICE + +## Event: Account Configuration Update previous Leverage Update + +> **Payload:** + +```javascript +{ + "e":"ACCOUNT_CONFIG_UPDATE", // Event Type + "E":1611646737479, // Event Time + "T":1611646737476, // Transaction Time + "ac":{ + "s":"BTCUSDT", // symbol + "l":25 // leverage + + } +} +``` + +> **Or** + +```javascript +{ + "e":"ACCOUNT_CONFIG_UPDATE", // Event Type + "E":1611646737479, // Event Time + "T":1611646737476, // Transaction Time + "ai":{ // User's Account Configuration + "j":true // Multi-Assets Mode + } +} +``` + +When the account configuration is changed, the event type will be pushed as `ACCOUNT_CONFIG_UPDATE` + +When the leverage of a trade pair changes, the payload will contain the object `ac` to represent the account configuration of the trade pair, where `s` represents the specific trade pair and `l` represents the leverage + +When the user Multi-Assets margin mode changes the payload will contain the object `ai` representing the user account configuration, where `j` represents the user Multi-Assets margin mode + +# Error Codes + +> Here is the error JSON payload: + +```javascript +{ + "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 + +* An unknown error occured while processing the request. + +> -1001 DISCONNECTED + +* Internal error; unable to process your request. Please try again. + +> -1002 UNAUTHORIZED + +* You are not authorized to execute this request. + +> -1003 TOO_MANY_REQUESTS + +* Too many requests queued. +* Too many requests; please use the websocket for live updates. +* Too many requests; current limit is %s requests per minute. Please use the websocket for live updates to avoid polling the API. +* Way too many requests; IP banned until %s. Please use the websocket for live updates to avoid bans. + +> -1004 DUPLICATE_IP + +* This IP is already on the white list + +> -1005 NO_SUCH_IP + +* No such IP has been white listed + +> -1006 UNEXPECTED_RESP + +* An unexpected response was received from the message bus. Execution status unknown. + +> -1007 TIMEOUT + +* Timeout waiting for response from backend server. Send status unknown; execution status unknown. + +> -1010 ERROR_MSG_RECEIVED + +* ERROR_MSG_RECEIVED. + +> -1011 NON_WHITE_LIST + +* This IP cannot access this route. + +> -1013 INVALID_MESSAGE + +* INVALID_MESSAGE. + +> -1014 UNKNOWN_ORDER_COMPOSITION + +* Unsupported order combination. + +> -1015 TOO_MANY_ORDERS + +* Too many new orders. +* Too many new orders; current limit is %s orders per %s. + +> -1016 SERVICE_SHUTTING_DOWN + +* This service is no longer available. + +> -1020 UNSUPPORTED_OPERATION + +* This operation is not supported. + +> -1021 INVALID_TIMESTAMP + +* Timestamp for this request is outside of the recvWindow. +* Timestamp for this request was 1000ms ahead of the server's time. + +> -1022 INVALID_SIGNATURE + +* Signature for this request is not valid. + +> -1023 START_TIME_GREATER_THAN_END_TIME + +* Start time is greater than end time. + +## 11xx - Request issues + +> -1100 ILLEGAL_CHARS + +* Illegal characters found in a parameter. +* Illegal characters found in parameter '%s'; legal range is '%s'. + +> -1101 TOO_MANY_PARAMETERS + +* Too many parameters sent for this endpoint. +* Too many parameters; expected '%s' and received '%s'. +* Duplicate values for a parameter detected. + +> -1102 MANDATORY_PARAM_EMPTY_OR_MALFORMED + +* A mandatory parameter was not sent, was empty/null, or malformed. +* Mandatory parameter '%s' was not sent, was empty/null, or malformed. +* Param '%s' or '%s' must be sent, but both were empty/null! + +> -1103 UNKNOWN_PARAM + +* An unknown parameter was sent. + +> -1104 UNREAD_PARAMETERS + +* Not all sent parameters were read. +* Not all sent parameters were read; read '%s' parameter(s) but was sent '%s'. + +> -1105 PARAM_EMPTY + +* A parameter was empty. +* Parameter '%s' was empty. + +> -1106 PARAM_NOT_REQUIRED + +* A parameter was sent when not required. +* Parameter '%s' sent when not required. + +> -1108 BAD_ASSET + +* Invalid asset. + +> -1109 BAD_ACCOUNT + +* Invalid account. + +> -1110 BAD_INSTRUMENT_TYPE + +* Invalid symbolType. + +> -1111 BAD_PRECISION + +* Precision is over the maximum defined for this asset. + +> -1112 NO_DEPTH + +* No orders on book for symbol. + +> -1113 WITHDRAW_NOT_NEGATIVE + +* Withdrawal amount must be negative. + +> -1114 TIF_NOT_REQUIRED + +* TimeInForce parameter sent when not required. + +> -1115 INVALID_TIF + +* Invalid timeInForce. + +> -1116 INVALID_ORDER_TYPE + +* Invalid orderType. + +> -1117 INVALID_SIDE + +* Invalid side. + +> -1118 EMPTY_NEW_CL_ORD_ID + +* New client order ID was empty. + +> -1119 EMPTY_ORG_CL_ORD_ID + +* Original client order ID was empty. + +> -1120 BAD_INTERVAL + +* Invalid interval. + +> -1121 BAD_SYMBOL + +* Invalid symbol. + +> -1125 INVALID_LISTEN_KEY + +* This listenKey does not exist. + +> -1127 MORE_THAN_XX_HOURS + +* Lookup interval is too big. +* More than %s hours between startTime and endTime. + +> -1128 OPTIONAL_PARAMS_BAD_COMBO + +* Combination of optional parameters invalid. + +> -1130 INVALID_PARAMETER + +* Invalid data sent for a parameter. +* Data sent for parameter '%s' is not valid. + +> -1136 INVALID_NEW_ORDER_RESP_TYPE + +* Invalid newOrderRespType. + +## 20xx - Processing Issues + +> -2010 NEW_ORDER_REJECTED + +* NEW_ORDER_REJECTED + +> -2011 CANCEL_REJECTED + +* CANCEL_REJECTED + +> -2013 NO_SUCH_ORDER + +* Order does not exist. + +> -2014 BAD_API_KEY_FMT + +* API-key format invalid. + +> -2015 REJECTED_MBX_KEY + +* Invalid API-key, IP, or permissions for action. + +> -2016 NO_TRADING_WINDOW + +* No trading window could be found for the symbol. Try ticker/24hrs instead. + +> -2018 BALANCE_NOT_SUFFICIENT + +* Balance is insufficient. + +> -2019 MARGIN_NOT_SUFFICIEN + +* Margin is insufficient. + +> -2020 UNABLE_TO_FILL + +* Unable to fill. + +> -2021 ORDER_WOULD_IMMEDIATELY_TRIGGER + +* Order would immediately trigger. + +> -2022 REDUCE_ONLY_REJECT + +* ReduceOnly Order is rejected. + +> -2023 USER_IN_LIQUIDATION + +* User in liquidation mode now. + +> -2024 POSITION_NOT_SUFFICIENT + +* Position is not sufficient. + +> -2025 MAX_OPEN_ORDER_EXCEEDED + +* Reach max open order limit. + +> -2026 REDUCE_ONLY_ORDER_TYPE_NOT_SUPPORTED + +* This OrderType is not supported when reduceOnly. + +> -2027 MAX_LEVERAGE_RATIO + +* Exceeded the maximum allowable position at current leverage. + +> -2028 MIN_LEVERAGE_RATIO + +* Leverage is smaller than permitted: insufficient margin balance. + +## 40xx - Filters and other Issues + +> -4000 INVALID_ORDER_STATUS + +* Invalid order status. + +> -4001 PRICE_LESS_THAN_ZERO + +* Price less than 0. + +> -4002 PRICE_GREATER_THAN_MAX_PRICE + +* Price greater than max price. + +> -4003 QTY_LESS_THAN_ZERO + +* Quantity less than zero. + +> -4004 QTY_LESS_THAN_MIN_QTY + +* Quantity less than min quantity. + +> -4005 QTY_GREATER_THAN_MAX_QTY + +* Quantity greater than max quantity. + +> -4006 STOP_PRICE_LESS_THAN_ZERO + +* Stop price less than zero. + +> -4007 STOP_PRICE_GREATER_THAN_MAX_PRICE + +* Stop price greater than max price. + +> -4008 TICK_SIZE_LESS_THAN_ZERO + +* Tick size less than zero. + +> -4009 MAX_PRICE_LESS_THAN_MIN_PRICE + +* Max price less than min price. + +> -4010 MAX_QTY_LESS_THAN_MIN_QTY + +* Max qty less than min qty. + +> -4011 STEP_SIZE_LESS_THAN_ZERO + +* Step size less than zero. + +> -4012 MAX_NUM_ORDERS_LESS_THAN_ZERO + +* Max mum orders less than zero. + +> -4013 PRICE_LESS_THAN_MIN_PRICE + +* Price less than min price. + +> -4014 PRICE_NOT_INCREASED_BY_TICK_SIZE + +* Price not increased by tick size. + +> -4015 INVALID_CL_ORD_ID_LEN + +* Client order id is not valid. +* Client order id length should not be more than 36 chars + +> -4016 PRICE_HIGHTER_THAN_MULTIPLIER_UP + +* Price is higher than mark price multiplier cap. + +> -4017 MULTIPLIER_UP_LESS_THAN_ZERO + +* Multiplier up less than zero. + +> -4018 MULTIPLIER_DOWN_LESS_THAN_ZERO + +* Multiplier down less than zero. + +> -4019 COMPOSITE_SCALE_OVERFLOW + +* Composite scale too large. + +> -4020 TARGET_STRATEGY_INVALID + +* Target strategy invalid for orderType '%s',reduceOnly '%b'. + +> -4021 INVALID_DEPTH_LIMIT + +* Invalid depth limit. +* '%s' is not valid depth limit. + +> -4022 WRONG_MARKET_STATUS + +* market status sent is not valid. + +> -4023 QTY_NOT_INCREASED_BY_STEP_SIZE + +* Qty not increased by step size. + +> -4024 PRICE_LOWER_THAN_MULTIPLIER_DOWN + +* Price is lower than mark price multiplier floor. + +> -4025 MULTIPLIER_DECIMAL_LESS_THAN_ZERO + +* Multiplier decimal less than zero. + +> -4026 COMMISSION_INVALID + +* Commission invalid. +* `%s` less than zero. +* `%s` absolute value greater than `%s` + +> -4027 INVALID_ACCOUNT_TYPE + +* Invalid account type. + +> -4028 INVALID_LEVERAGE + +* Invalid leverage +* Leverage `%s` is not valid +* Leverage `%s` already exist with `%s` + +> -4029 INVALID_TICK_SIZE_PRECISION + +* Tick size precision is invalid. + +> -4030 INVALID_STEP_SIZE_PRECISION + +* Step size precision is invalid. + +> -4031 INVALID_WORKING_TYPE + +* Invalid parameter working type +* Invalid parameter working type: `%s` + +> -4032 EXCEED_MAX_CANCEL_ORDER_SIZE + +* Exceed maximum cancel order size. +* Invalid parameter working type: `%s` + +> -4033 INSURANCE_ACCOUNT_NOT_FOUND + +* Insurance account not found. + +> -4044 INVALID_BALANCE_TYPE + +* Balance Type is invalid. + +> -4045 MAX_STOP_ORDER_EXCEEDED + +* Reach max stop order limit. + +> -4046 NO_NEED_TO_CHANGE_MARGIN_TYPE + +* No need to change margin type. + +> -4047 THERE_EXISTS_OPEN_ORDERS + +* Margin type cannot be changed if there exists open orders. + +> -4048 THERE_EXISTS_QUANTITY + +* Margin type cannot be changed if there exists position. + +> -4049 ADD_ISOLATED_MARGIN_REJECT + +* Add margin only support for isolated position. + +> -4050 CROSS_BALANCE_INSUFFICIENT + +* Cross balance insufficient. + +> -4051 ISOLATED_BALANCE_INSUFFICIENT + +* Isolated balance insufficient. + +> -4052 NO_NEED_TO_CHANGE_AUTO_ADD_MARGIN + +* No need to change auto add margin. + +> -4053 AUTO_ADD_CROSSED_MARGIN_REJECT + +* Auto add margin only support for isolated position. + +> -4054 ADD_ISOLATED_MARGIN_NO_POSITION_REJECT + +* Cannot add position margin: position is 0. + +> -4055 AMOUNT_MUST_BE_POSITIVE + +* Amount must be positive. + +> -4056 INVALID_API_KEY_TYPE + +* Invalid api key type. + +> -4057 INVALID_RSA_PUBLIC_KEY + +* Invalid api public key + +> -4058 MAX_PRICE_TOO_LARGE + +* maxPrice and priceDecimal too large,please check. + +> -4059 NO_NEED_TO_CHANGE_POSITION_SIDE + +* No need to change position side. + +> -4060 INVALID_POSITION_SIDE + +* Invalid position side. + +> -4061 POSITION_SIDE_NOT_MATCH + +* Order's position side does not match user's setting. + +> -4062 REDUCE_ONLY_CONFLICT + +* Invalid or improper reduceOnly value. + +> -4063 INVALID_OPTIONS_REQUEST_TYPE + +* Invalid options request type + +> -4064 INVALID_OPTIONS_TIME_FRAME + +* Invalid options time frame + +> -4065 INVALID_OPTIONS_AMOUNT + +* Invalid options amount + +> -4066 INVALID_OPTIONS_EVENT_TYPE + +* Invalid options event type + +> -4067 POSITION_SIDE_CHANGE_EXISTS_OPEN_ORDERS + +* Position side cannot be changed if there exists open orders. + +> -4068 POSITION_SIDE_CHANGE_EXISTS_QUANTITY + +* Position side cannot be changed if there exists position. + +> -4069 INVALID_OPTIONS_PREMIUM_FEE + +* Invalid options premium fee + +> -4070 INVALID_CL_OPTIONS_ID_LEN + +* Client options id is not valid. +* Client options id length should be less than 32 chars + +> -4071 INVALID_OPTIONS_DIRECTION + +* Invalid options direction + +> -4072 OPTIONS_PREMIUM_NOT_UPDATE + +* premium fee is not updated, reject order + +> -4073 OPTIONS_PREMIUM_INPUT_LESS_THAN_ZERO + +* input premium fee is less than 0, reject order + +> -4074 OPTIONS_AMOUNT_BIGGER_THAN_UPPER + +* Order amount is bigger than upper boundary or less than 0, reject order + +> -4075 OPTIONS_PREMIUM_OUTPUT_ZERO + +* output premium fee is less than 0, reject order + +> -4076 OPTIONS_PREMIUM_TOO_DIFF + +* original fee is too much higher than last fee + +> -4077 OPTIONS_PREMIUM_REACH_LIMIT + +* place order amount has reached to limit, reject order + +> -4078 OPTIONS_COMMON_ERROR + +* options internal error + +> -4079 INVALID_OPTIONS_ID + +* invalid options id +* invalid options id: %s +* duplicate options id %d for user %d + +> -4080 OPTIONS_USER_NOT_FOUND + +* user not found +* user not found with id: %s + +> -4081 OPTIONS_NOT_FOUND + +* options not found +* options not found with id: %s + +> -4082 INVALID_BATCH_PLACE_ORDER_SIZE + +* Invalid number of batch place orders. +* Invalid number of batch place orders: %s + +> -4083 PLACE_BATCH_ORDERS_FAIL + +* Fail to place batch orders. + +> -4084 UPCOMING_METHOD + +* Method is not allowed currently. Upcoming soon. + +> -4085 INVALID_NOTIONAL_LIMIT_COEF + +* Invalid notional limit coefficient + +> -4086 INVALID_PRICE_SPREAD_THRESHOLD + +* Invalid price spread threshold + +> -4087 REDUCE_ONLY_ORDER_PERMISSION + +* User can only place reduce only order + +> -4088 NO_PLACE_ORDER_PERMISSION + +* User can not place order currently + +> -4104 INVALID_CONTRACT_TYPE + +* Invalid contract type + +> -4114 INVALID_CLIENT_TRAN_ID_LEN + +* clientTranId is not valid +* Client tran id length should be less than 64 chars + +> -4115 DUPLICATED_CLIENT_TRAN_ID + +* clientTranId is duplicated +* Client tran id should be unique within 7 days + +> -4118 REDUCE_ONLY_MARGIN_CHECK_FAILED + +* ReduceOnly Order Failed. Please check your existing position and open orders + +> -4131 MARKET_ORDER_REJECT + +* The counterparty's best price does not meet the PERCENT_PRICE filter limit + +> -4135 INVALID_ACTIVATION_PRICE + +* Invalid activation price + +> -4137 QUANTITY_EXISTS_WITH_CLOSE_POSITION + +* Quantity must be zero with closePosition equals true + +> -4138 REDUCE_ONLY_MUST_BE_TRUE + +* Reduce only must be true with closePosition equals true + +> -4139 ORDER_TYPE_CANNOT_BE_MKT + +* Order type can not be market if it's unable to cancel + +> -4140 INVALID_OPENING_POSITION_STATUS + +* Invalid symbol status for opening position + +> -4141 SYMBOL_ALREADY_CLOSED + +* Symbol is closed + +> -4142 STRATEGY_INVALID_TRIGGER_PRICE + +* REJECT: take profit or stop order will be triggered immediately + +> -4144 INVALID_PAIR + +* Invalid pair + +> -4161 ISOLATED_LEVERAGE_REJECT_WITH_POSITION + +* Leverage reduction is not supported in Isolated Margin Mode with open positions + +> -4164 MIN_NOTIONAL + +* Order's notional must be no smaller than 5.0 (unless you choose reduce only) +* Order's notional must be no smaller than %s (unless you choose reduce only) + +> -4165 INVALID_TIME_INTERVAL + +* Invalid time interval +* Maximum time interval is %s days + +> -4183 PRICE_HIGHTER_THAN_STOP_MULTIPLIER_UP + +* Price is higher than stop price multiplier cap. +* Limit price can't be higher than %s. + +> -4184 PRICE_LOWER_THAN_STOP_MULTIPLIER_DOWN + +* Price is lower than stop price multiplier floor. +* Limit price can't be lower than %s. + diff --git a/aster-finance-futures-api-v3_CN.md b/aster-finance-futures-api-v3_CN.md new file mode 100644 index 0000000..f05681e --- /dev/null +++ b/aster-finance-futures-api-v3_CN.md @@ -0,0 +1,4707 @@ +- [基本信息](#基本信息) + - [Rest 基本信息](#rest-基本信息) + - [HTTP 返回代码](#http-返回代码) + - [接口错误代码](#接口错误代码) + - [接口的基本信息](#接口的基本信息) + - [访问限制](#访问限制) + - [IP 访问限制](#ip-访问限制) + - [下单频率限制](#下单频率限制) + - [接口鉴权类型](#接口鉴权类型) + - [鉴权签名体](#鉴权签名体) + - [需要签名的接口](#需要签名的接口) + - [时间同步安全](#时间同步安全) + - [POST /fapi/v3/order 的示例](#post-fapiv3order-的示例) + - [GET /fapi/v3/order 的示例](#get-fapiv3order-的示例) + - [完整python脚本示例](#完整python脚本示例) + - [公开API参数](#公开api参数) + - [术语解释](#术语解释) + - [枚举定义](#枚举定义) + - [过滤器](#过滤器) + - [交易对过滤器](#交易对过滤器) + - [PRICE_FILTER 价格过滤器](#price_filter-价格过滤器) + - [LOT_SIZE 订单尺寸](#lot_size-订单尺寸) + - [MARKET_LOT_SIZE 市价订单尺寸](#market_lot_size-市价订单尺寸) + - [MAX_NUM_ORDERS 最多订单数](#max_num_orders-最多订单数) + - [MAX_NUM_ALGO_ORDERS 最多条件订单数](#max_num_algo_orders-最多条件订单数) + - [PERCENT_PRICE 价格振幅过滤器](#percent_price-价格振幅过滤器) + - [MIN_NOTIONAL 最小名义价值](#min_notional-最小名义价值) +- [行情接口](#行情接口) + - [测试服务器连通性 PING](#测试服务器连通性-ping) + - [获取服务器时间](#获取服务器时间) + - [获取交易规则和交易对](#获取交易规则和交易对) + - [深度信息](#深度信息) + - [近期成交](#近期成交) + - [查询历史成交(MARKET_DATA)](#查询历史成交market_data) + - [近期成交(归集)](#近期成交归集) + - [K线数据](#k线数据) + - [价格指数K线数据](#价格指数k线数据) + - [标记价格K线数据](#标记价格k线数据) + - [最新标记价格和资金费率](#最新标记价格和资金费率) + - [查询资金费率历史](#查询资金费率历史) + - [24hr价格变动情况](#24hr价格变动情况) + - [最新价格](#最新价格) + - [当前最优挂单](#当前最优挂单) +- [Websocket 行情推送](#websocket-行情推送) + - [实时订阅/取消数据流](#实时订阅取消数据流) + - [订阅一个信息流](#订阅一个信息流) + - [取消订阅一个信息流](#取消订阅一个信息流) + - [已订阅信息流](#已订阅信息流) + - [设定属性](#设定属性) + - [检索属性](#检索属性) + - [错误信息](#错误信息) + - [最新合约价格](#最新合约价格) + - [归集交易](#归集交易) + - [最新标记价格](#最新标记价格) + - [全市场最新标记价格](#全市场最新标记价格) + - [K线](#k线) + - [按Symbol的精简Ticker](#按symbol的精简ticker) + - [全市场的精简Ticker](#全市场的精简ticker) + - [按Symbol的完整Ticker](#按symbol的完整ticker) + - [全市场的完整Ticker](#全市场的完整ticker) + - [按Symbol的最优挂单信息](#按symbol的最优挂单信息) + - [全市场最优挂单信息](#全市场最优挂单信息) + - [有限档深度信息](#有限档深度信息) + - [增量深度信息](#增量深度信息) + - [如何正确在本地维护一个orderbook副本](#如何正确在本地维护一个orderbook副本) +- [账户和交易接口](#账户和交易接口) + - [更改持仓模式(TRADE)](#更改持仓模式trade) + - [查询持仓模式(USER_DATA)](#查询持仓模式user_data) + - [更改联合保证金模式(TRADE)](#更改联合保证金模式trade) + - [查询联合保证金模式(USER_DATA)](#查询联合保证金模式user_data) + - [下单 (TRADE)](#下单-trade) + - [测试下单接口 (TRADE)](#测试下单接口-trade) + - [批量下单 (TRADE)](#批量下单-trade) + - [查询订单 (USER_DATA)](#查询订单-user_data) + - [撤销订单 (TRADE)](#撤销订单-trade) + - [撤销全部订单 (TRADE)](#撤销全部订单-trade) + - [批量撤销订单 (TRADE)](#批量撤销订单-trade) + - [倒计时撤销所有订单 (TRADE)](#倒计时撤销所有订单-trade) + - [查询当前挂单 (USER_DATA)](#查询当前挂单-user_data) + - [查看当前全部挂单 (USER_DATA)](#查看当前全部挂单-user_data) + - [查询所有订单(包括历史订单) (USER_DATA)](#查询所有订单包括历史订单-user_data) + - [账户余额v3 (USER_DATA)](#账户余额v3-user_data) + - [账户信息v3 (USER_DATA)](#账户信息v3-user_data) + - [调整开仓杠杆 (TRADE)](#调整开仓杠杆-trade) + - [变换逐全仓模式 (TRADE)](#变换逐全仓模式-trade) + - [调整逐仓保证金 (TRADE)](#调整逐仓保证金-trade) + - [逐仓保证金变动历史 (TRADE)](#逐仓保证金变动历史-trade) + - [用户持仓风险v3 (USER_DATA)](#用户持仓风险v3-user_data) + - [账户成交历史 (USER_DATA)](#账户成交历史-user_data) + - [获取账户损益资金流水(USER_DATA)](#获取账户损益资金流水user_data) + - [杠杆分层标准 (USER_DATA)](#杠杆分层标准-user_data) + - [持仓ADL队列估算 (USER_DATA)](#持仓adl队列估算-user_data) + - [用户强平单历史 (USER_DATA)](#用户强平单历史-user_data) + - [用户手续费率 (USER_DATA)](#用户手续费率-user_data) +- [Websocket 账户信息推送](#websocket-账户信息推送) + - [生成listenKey (USER_STREAM)](#生成listenkey-user_stream) + - [延长listenKey有效期 (USER_STREAM)](#延长listenkey有效期-user_stream) + - [关闭listenKey (USER_STREAM)](#关闭listenkey-user_stream) + - [listenKey 过期推送](#listenkey-过期推送) + - [追加保证金通知](#追加保证金通知) + - [Balance和Position更新推送](#balance和position更新推送) + - [订单/交易 更新推送](#订单交易-更新推送) + - [杠杆倍数等账户配置 更新推送](#杠杆倍数等账户配置-更新推送) +- [错误代码](#错误代码) + - [10xx - 常规服务器或网络问题](#10xx---常规服务器或网络问题) + - [11xx - Request issues](#11xx---request-issues) + - [20xx - Processing Issues](#20xx---processing-issues) + - [40xx - Filters and other Issues](#40xx---filters-and-other-issues) + +# 基本信息 + + +## Rest 基本信息 + +* 接口可能需要用户的AGENT,如何创建AGENT请参考[这里](https://www.asterdex.com/) +* 本篇列出REST接口的baseurl **https://fapi.asterdex.com** +* 所有接口的响应都是JSON格式 +* 响应中如有数组,数组元素以时间升序排列,越早的数据越提前。 +* 所有时间、时间戳均为UNIX时间,单位为毫秒 +* 所有数据类型采用JAVA的数据类型定义 + +### HTTP 返回代码 +* HTTP `4XX` 错误码用于指示错误的请求内容、行为、格式。 +* HTTP `403` 错误码表示违反WAF限制(Web应用程序防火墙)。 +* HTTP `429` 错误码表示警告访问频次超限,即将被封IP +* HTTP `418` 表示收到429后继续访问,于是被封了。 +* HTTP `5XX` 错误码用于指示Aster Finance服务侧的问题。 +* HTTP `503` 表示API服务端已经向业务核心提交了请求但未能获取响应,特别需要注意的是其不代表请求失败,而是未知。很可能已经得到了执行,也有可能执行失败,需要做进一步确认。 + + +### 接口错误代码 +* 每个接口都有可能抛出异常 + +> 异常响应格式如下: + +```javascript +{ + "code": -1121, + "msg": "Invalid symbol." +} +``` + +* 具体的错误码及其解释在[错误代码](#错误代码) + +### 接口的基本信息 +* `GET`方法的接口, 参数必须在`query string`中发送. +* `POST`, `PUT`, 和 `DELETE` 方法的接口, 在 `request body`中发送(content type `application/x-www-form-urlencoded`) +* 对参数的顺序不做要求。 + +## 访问限制 +* 在 `/fapi/v3/exchangeInfo`接口中`rateLimits`数组里包含有REST接口(不限于本篇的REST接口)的访问限制。包括带权重的访问频次限制、下单速率限制。本篇`枚举定义`章节有限制类型的进一步说明。 +* 违反上述任何一个访问限制都会收到HTTP 429,这是一个警告. + + + + +### IP 访问限制 +* 每个请求将包含一个`X-MBX-USED-WEIGHT-(intervalNum)(intervalLetter)`的头,其中包含当前IP所有请求的已使用权重。 +* 每个路由都有一个"权重",该权重确定每个接口计数的请求数。较重的接口和对多个交易对进行操作的接口将具有较重的"权重"。 +* 收到429时,您有责任作为API退回而不向其发送更多的请求。 +* **如果屡次违反速率限制和/或在收到429后未能退回,将导致API的IP被禁(http状态418)。** +* 频繁违反限制,封禁时间会逐渐延长 ,**对于重复违反者,将会被封从2分钟到3天**。 +* **访问限制是基于IP的,而不是AGENT** + + + + +### 下单频率限制 +* 每个下单请求回报将包含一个`X-MBX-ORDER-COUNT-(intervalNum)(intervalLetter)`的头,其中包含当前账户已用的下单限制数量。 +* 被拒绝或不成功的下单并不保证回报中包含以上头内容。 +* **下单频率限制是基于每个账户计数的。** + +**关于交易时效性** +互联网状况并不100%可靠,不可完全依赖,因此你的程序本地到服务器的时延会有抖动. +这是我们设置`recvWindow`的目的所在,如果你从事高频交易,对交易时效性有较高的要求,可以灵活设置recvWindow以达到你的要求。 + + + +## 接口鉴权类型 +* 每个接口都有自己的鉴权类型,鉴权类型决定了访问时应当进行何种鉴权 +* 如果需要鉴权,应当在请求体中添加signer + +鉴权类型 | 描述 +------------ | ------------ +NONE | 不需要鉴权的接口 +TRADE | 需要有效的signer和签名 +USER_DATA | 需要有效的signer和签名 +USER_STREAM | 需要有效的signer和签名 +MARKET_DATA | 需要有效的signer和签名 + +## 鉴权签名体 +参数 | 描述 +------------ | ------------ +user | 主账户钱包地址 +signer | API钱包地址 +nonce | 当前时间戳,单位为微秒 +signature | 签名 + +## 需要签名的接口 +* TRADE 与 USER_DATA,USER_STREAM,MARKET_DATA +* 接口参数转字符串后按照key值ASCII编码后生成的字符串 请注意所有参数取值请以字符串的方式进行签名 +* 生成字符串后在与鉴权签名参数的user,signer,nonce使用web3的abi参数编码生成字节码 +* 生成字节码后使用Keccak算法生成hash +* 使用派生地址的私钥用web3的ecdsa签名算法对该hash进行签名生成signature + +### 时间同步安全 +* 签名接口均需要传递`timestamp`参数,其值应当是请求发送时刻的unix时间戳(毫秒) +* 服务器收到请求时会判断请求中的时间戳,如果是5000毫秒之前发出的,则请求会被认为无效。这个时间窗口值可以通过发送可选参数`recvWindow`来自定义。 + +> 逻辑伪代码: + + ```javascript + if (timestamp < (serverTime + 1000) && (serverTime - timestamp) <= recvWindow) { + // process request + } else { + // reject request + } + ``` + +## POST /fapi/v3/order 的示例 + +#### 所有参数均通过from body请求(Python 3.9.6) + +#### 示例 : 以下参数为api注册信息,user,signer,privateKey仅供示范(privateKey为signer的私钥) + +Key | Value +------------ | ------------ +user | 0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e +signer | 0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0 +privateKey | 0x4fd0a42218f3eae43a6ce26d22544e986139a01e5b34a62db53757ffca81bae1 + +#### 示例 : nonce参数为当前系统微秒值,超过系统时间,或者落后系统时间超过5s为非法请求 +```python +#python +nonce = math.trunc(time.time()*1000000) +print(nonce) +#1748310859508867 +``` +```java +//java +Instant now = Instant.now(); +long microsecond = now.getEpochSecond() * 1000000 + now.getNano() / 1000; +``` + +#### 示例 : 以下参数为业务请求参数 + +```python + my_dict = {'symbol': 'SANDUSDT', 'positionSide': 'BOTH', 'type': 'LIMIT', 'side': 'BUY', + 'timeInForce': 'GTC', 'quantity': "190", 'price': 0.28694} +``` + +#### 示例 : 所有参数通过 form body 发送(方法以python为例) + +> **第一步将所有业务参数转字符串后按照ascII排序生成字符串:** + +```python + #定义所有元素取值转换为字符串 + def _trim_dict(my_dict) : + # 假设待删除的字典为d + for key in my_dict: + value = my_dict[key] + if isinstance(value, list): + new_value = [] + for item in value: + if isinstance(item, dict): + new_value.append(json.dumps(_trim_dict(item))) + else: + new_value.append(str(item)) + my_dict[key] = json.dumps(new_value) + continue + if isinstance(value, dict): + my_dict[key] = json.dumps(_trim_dict(value)) + continue + my_dict[key] = str(value) + + return my_dict + + #移除空值元素 + my_dict = {key: value for key, value in my_dict.items() if value is not None} + my_dict['recvWindow'] = 50000 + my_dict['timestamp'] = int(round(time.time()*1000)) + # my_dict['timestamp'] = 1749545309665 + #将元素转换为字符串 + _trim_dict(my_dict) + #根据ASCII排序生成字符串并移除特殊字符 + json_str = json.dumps(my_dict, sort_keys=True).replace(' ', '').replace('\'','\"') + print(json_str) + {"positionSide":"BOTH","price":"0.28694","quantity":"190","recvWindow":"50000","side":"BUY","symbol":"SANDUSDT","timeInForce":"GTC","timestamp":"1749545309665","type":"LIMIT"} +``` + +> **第二步将第一步生成的字符串与账户信息以及nonce进行abi编码生成hash字符串:** + +```python + from eth_abi import encode + from web3 import Web3 + #使用WEB3 ABI对生成的字符串和user, signer, nonce进行编码 + encoded = encode(['string', 'address', 'address', 'uint256'], [json_str, user, signer, nonce]) + print(encoded.hex()) + #000000000000000000000000000000000000000000000000000000000000008000000000000000000000000063dd5acc6b1aa0f563956c0e534dd30b6dcf7c4e00000000000000000000000021cf8ae13bb72632562c6fff438652ba1a151bb00000000000000000000000000000000000000000000000000006361457bcec8300000000000000000000000000000000000000000000000000000000000000af7b22706f736974696f6e53696465223a22424f5448222c227072696365223a22302e3238363934222c227175616e74697479223a22313930222c227265637657696e646f77223a223530303030222c2273696465223a22425559222c2273796d626f6c223a2253414e4455534454222c2274696d65496e466f726365223a22475443222c2274696d657374616d70223a2231373439353435333039363635222c2274797065223a224c494d4954227d0000000000000000000000000000000000 + #keccak hex + keccak_hex =Web3.keccak(encoded).hex() + print(keccak_hex) + #9e0273fc91323f5cdbcb00c358be3dee2854afb2d3e4c68497364a2f27a377fc +``` +> **第三步将第二步生成的hash用privateKey进行签名:** +```python + from eth_account import Account + from eth_abi import encode + from web3 import Web3, EthereumTesterProvider + from eth_account.messages import encode_defunct + + signable_msg = encode_defunct(hexstr=keccak_hex) + signed_message = Account.sign_message(signable_message=signable_msg, private_key=priKey) + signature = '0x'+signed_message.signature.hex() + print(signature) + #0x0337dd720a21543b80ff861cd3c26646b75b3a6a4b5d45805d4c1d6ad6fc33e65f0722778dd97525466560c69fbddbe6874eb4ed6f5fa7e576e486d9b5da67f31b +``` +> **第四步将所有参数以及第三步生成的signature组装成请求体:** + +```python + my_dict['nonce'] = nonce + my_dict['user'] = user + my_dict['signer'] = signer + my_dict['signature'] = '0x'+signed_message.signature.hex() + url ='http://127.0.0.1:9081/fapi/v3/order' + headers = { + 'Content-Type': 'application/x-www-form-urlencoded', + 'User-Agent': 'PythonApp/1.0' + } + res = requests.post(url,data=my_dict,headers=headers) + print(url) + #curl -X POST 'http://127.0.0.1:9081/fapi/v3/order' -d 'symbol=SANDUSDT&positionSide=BOTH&type=LIMIT&side=BUY&timeInForce=GTC&quantity=190&price=0.28694&recvWindow=50000×tamp=1749545309665&nonce=1748310859508867&user=0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e&signer=0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0&signature=0x0337dd720a21543b80ff861cd3c26646b75b3a6a4b5d45805d4c1d6ad6fc33e65f0722778dd97525466560c69fbddbe6874eb4ed6f5fa7e576e486d9b5da67f31b' + +``` + +## GET /fapi/v3/order 的示例 +#### 示例 : 所有参数通过 query string 发送(Python 3.9.6) + +#### 示例 : 以下参数为api注册信息,user,signer,privateKey仅供示范(privateKey为agent的私钥) + +Key | Value +------------ | ------------ +user | 0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e +signer | 0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0 +privateKey | 0x4fd0a42218f3eae43a6ce26d22544e986139a01e5b34a62db53757ffca81bae1 + +#### 示例 : nonce参数为当前系统微秒值,超过系统时间50s,或者落后系统时间超过5s为非法请求 +```python +#python +nonce = math.trunc(time.time()*1000000) +print(nonce) +#1748310859508867 +``` +```java +//java +Instant now = Instant.now(); +long microsecond = now.getEpochSecond() * 1000000 + now.getNano() / 1000; +``` + +#### 示例 : 以下参数为业务请求参数 +```python +my_dict = {'symbol':'SANDUSDT','side':"SELL","type":'LIMIT','orderId':2194215} +``` + +> **第一步将所有业务参数转字符串后按照ascII排序生成字符串:** + +```python + #定义所有元素取值转换为字符串 + def _trim_dict(my_dict) : + for key in my_dict: + value = my_dict[key] + if isinstance(value, list): + new_value = [] + for item in value: + if isinstance(item, dict): + new_value.append(json.dumps(_trim_dict(item))) + else: + new_value.append(str(item)) + my_dict[key] = json.dumps(new_value) + continue + if isinstance(value, dict): + my_dict[key] = json.dumps(_trim_dict(value)) + continue + my_dict[key] = str(value) + + return my_dict + + #移除空值元素 + my_dict = {key: value for key, value in my_dict.items() if value is not None} + my_dict['recvWindow'] = 50000 + my_dict['timestamp'] = int(round(time.time()*1000)) + # my_dict['timestamp'] = 1749545309665 + #将元素转换为字符串 + _trim_dict(my_dict) + #根据ASCII排序生成字符串并移除特殊字符 + json_str = json.dumps(my_dict, sort_keys=True).replace(' ', '').replace('\'','\"') + print(json_str) + #{"orderId":"2194215","recvWindow":"50000","side":"BUY","symbol":"SANDUSDT","timestamp":"1749545309665","type":"LIMIT"} +``` + +> **第二步将第一步生成的字符串与账户信息以及nonce进行abi编码生成hash字符串:** + +```python + from eth_abi import encode + from web3 import Web3 + + #使用WEB3 ABI对生成的字符串和user, signer, nonce进行编码 + encoded = encode(['string', 'address', 'address', 'uint256'], [json_str, user, signer, nonce]) + print(encoded.hex()) + #000000000000000000000000000000000000000000000000000000000000008000000000000000000000000063dd5acc6b1aa0f563956c0e534dd30b6dcf7c4e00000000000000000000000021cf8ae13bb72632562c6fff438652ba1a151bb00000000000000000000000000000000000000000000000000006361457bcec8300000000000000000000000000000000000000000000000000000000000000767b226f726465724964223a2232313934323135222c227265637657696e646f77223a223530303030222c2273696465223a22425559222c2273796d626f6c223a2253414e4455534454222c2274696d657374616d70223a2231373439353435333039363635222c2274797065223a224c494d4954227d00000000000000000000 + keccak_hex =Web3.keccak(encoded).hex() + print(keccak_hex) + #6ad9569ea1355bf62de1b09b33b267a9404239af6d9227fa59e3633edae19e2a +``` +> **第三步将第二步生成的hash用privateKey进行签名:** +```python + from eth_account import Account + from eth_abi import encode + from web3 import Web3, EthereumTesterProvider + from eth_account.messages import encode_defunct + + signable_msg = encode_defunct(hexstr=keccak_hex) + signed_message = Account.sign_message(signable_message=signable_msg, private_key=priKey) + signature = '0x'+signed_message.signature.hex() + print(signature) + #0x4f5e36e91f0d4cf5b29b6559ebc2c808d3c808ebb13b2bcaaa478b98fb4195642c7473f0d1aa101359aaf278126af1a53bcb482fb05003bfb6bdc03de03c63151b +``` +> **第四步将所有参数以及第三步生成的signature组装成请求体:** + +```python + my_dict['nonce'] = nonce + my_dict['user'] = user + my_dict['signer'] = signer + my_dict['signature'] = '0x'+signed_message.signature.hex() + + url ='http://127.0.0.1:9081/fapi/v3/order' + + res = requests.get(url, params=my_dict) + print(url) + #curl -X GET 'http://127.0.0.1:9081/fapi/v3/order?symbol=SANDUSDT&side=BUY&type=LIMIT&orderId=2194215&recvWindow=50000×tamp=1749545309665&nonce=1748310859508867&user=0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e&signer=0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0&signature=0x4f5e36e91f0d4cf5b29b6559ebc2c808d3c808ebb13b2bcaaa478b98fb4195642c7473f0d1aa101359aaf278126af1a53bcb482fb05003bfb6bdc03de03c63151b' + +``` +## 完整python脚本示例 +```python +#Python 3.9.6 +#eth-account~=0.13.7 +#eth-abi~=5.2.0 +#web3~=7.11.0 +#requests~=2.32.3 + +import json +import math +import time +import requests + +from eth_abi import encode +from eth_account import Account +from eth_account.messages import encode_defunct +from web3 import Web3 + +user = '0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e' +signer='0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0' +priKey = "0x4fd0a42218f3eae43a6ce26d22544e986139a01e5b34a62db53757ffca81bae1" +host = 'http://127.0.0.1:9081' +placeOrder = {'url': '/fapi/v3/order', 'method': 'POST', + 'params':{'symbol': 'SANDUSDT', 'positionSide': 'BOTH', 'type': 'LIMIT', 'side': 'BUY', + 'timeInForce': 'GTC', 'quantity': "30", 'price': 0.325,'reduceOnly': True}} +getOrder = {'url':'/fapi/v3/order','method':'GET','params':{'symbol':'SANDUSDT','side':"BUY","type":'LIMIT','orderId':2194215}} + +def call(api): + nonce = math.trunc(time.time() * 1000000) + my_dict = api['params'] + send(api['url'],api['method'],sign(my_dict,nonce)) + +def sign(my_dict,nonce): + my_dict = {key: value for key, value in my_dict.items() if value is not None} + my_dict['recvWindow'] = 50000 + my_dict['timestamp'] = int(round(time.time()*1000)) + msg = trim_param(my_dict,nonce) + signable_msg = encode_defunct(hexstr=msg) + signed_message = Account.sign_message(signable_message=signable_msg, private_key=priKey) + my_dict['nonce'] = nonce + my_dict['user'] = user + my_dict['signer'] = signer + my_dict['signature'] = '0x'+signed_message.signature.hex() + + print(my_dict['signature']) + return my_dict + +def trim_param(my_dict,nonce) -> str: + _trim_dict(my_dict) + json_str = json.dumps(my_dict, sort_keys=True).replace(' ', '').replace('\'','\"') + print(json_str) + encoded = encode(['string', 'address', 'address', 'uint256'], [json_str, user, signer, nonce]) + print(encoded.hex()) + keccak_hex =Web3.keccak(encoded).hex() + print(keccak_hex) + return keccak_hex + +def _trim_dict(my_dict) : + for key in my_dict: + value = my_dict[key] + if isinstance(value, list): + new_value = [] + for item in value: + if isinstance(item, dict): + new_value.append(json.dumps(_trim_dict(item))) + else: + new_value.append(str(item)) + my_dict[key] = json.dumps(new_value) + continue + if isinstance(value, dict): + my_dict[key] = json.dumps(_trim_dict(value)) + continue + my_dict[key] = str(value) + + return my_dict + +def send(url, method, my_dict): + url = host + url + print(url) + print(my_dict) + if method == 'POST': + headers = { + 'Content-Type': 'application/x-www-form-urlencoded', + 'User-Agent': 'PythonApp/1.0' + } + res = requests.post(url, data=my_dict, headers=headers) + print(res.text) + if method == 'GET': + res = requests.get(url, params=my_dict) + print(res.text) + if method == 'DELETE': + res = requests.delete(url, data=my_dict) + print(res.text) + +if __name__ == '__main__': + call(placeOrder) + # call(getOrder) + +``` + +## 公开API参数 +### 术语解释 +* `base asset` 指一个交易对的交易对象,即写在靠前部分的资产名 +* `quote asset` 指一个交易对的定价资产,即写在靠后部分资产名 + + +### 枚举定义 + +**交易对类型:** + +* FUTURE 期货 + +**合约类型 (contractType):** + +* PERPETUAL 永续合约 + + +**合约状态 (contractStatus, status):** + +* PENDING_TRADING 待上市 +* TRADING 交易中 +* PRE_SETTLE 预结算 +* SETTLING 结算中 +* CLOSE 已下架 + + +**订单状态 (status):** + +* NEW 新建订单 +* PARTIALLY_FILLED 部分成交 +* FILLED 全部成交 +* CANCELED 已撤销 +* REJECTED 订单被拒绝 +* EXPIRED 订单过期(根据timeInForce参数规则) + +**订单种类 (orderTypes, type):** + +* LIMIT 限价单 +* MARKET 市价单 +* STOP 止损限价单 +* STOP_MARKET 止损市价单 +* TAKE_PROFIT 止盈限价单 +* TAKE_PROFIT_MARKET 止盈市价单 +* TRAILING_STOP_MARKET 跟踪止损单 + +**订单方向 (side):** + +* BUY 买入 +* SELL 卖出 + +**持仓方向:** + +* BOTH 单一持仓方向 +* LONG 多头(双向持仓下) +* SHORT 空头(双向持仓下) + +**有效方式 (timeInForce):** + +* GTC - Good Till Cancel 成交为止 +* IOC - Immediate or Cancel 无法立即成交(吃单)的部分就撤销 +* FOK - Fill or Kill 无法全部立即成交就撤销 +* GTX - Good Till Crossing 无法成为挂单方就撤销 + +**条件价格触发类型 (workingType)** + +* MARK_PRICE +* CONTRACT_PRICE + +**响应类型 (newOrderRespType)** + +* ACK +* RESULT + +**K线间隔:** + +m -> 分钟; h -> 小时; d -> 天; w -> 周; M -> 月 + +* 1m +* 3m +* 5m +* 15m +* 30m +* 1h +* 2h +* 4h +* 6h +* 8h +* 12h +* 1d +* 3d +* 1w +* 1M + +**限制种类 (rateLimitType)** + +> REQUEST_WEIGHT + +```javascript + { + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 2400 + } +``` + +> ORDERS + +```javascript + { + "rateLimitType": "ORDERS", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200 + } +``` + +* REQUESTS_WEIGHT 单位时间请求权重之和上限 + +* ORDERS 单位时间下单(撤单)次数上限 + + +**限制间隔** + +* MINUTE + + + +## 过滤器 +过滤器,即Filter,定义了一系列交易规则。 +共有两类,分别是针对交易对的过滤器`symbol filters`,和针对整个交易所的过滤器`exchange filters`(暂不支持) + +### 交易对过滤器 +#### PRICE_FILTER 价格过滤器 + +> **/exchangeInfo 响应中的格式:** + +```javascript + { + "filterType": "PRICE_FILTER", + "minPrice": "0.00000100", + "maxPrice": "100000.00000000", + "tickSize": "0.00000100" + } +``` + +价格过滤器用于检测order订单中price参数的合法性 + +* `minPrice` 定义了 `price`/`stopPrice` 允许的最小值 +* `maxPrice` 定义了 `price`/`stopPrice` 允许的最大值。 +* `tickSize` 定义了 `price`/`stopPrice` 的步进间隔,即price必须等于minPrice+(tickSize的整数倍) +以上每一项均可为0,为0时代表这一项不再做限制。 + +逻辑伪代码如下: + +* `price` >= `minPrice` +* `price` <= `maxPrice` +* (`price`-`minPrice`) % `tickSize` == 0 + + + +#### LOT_SIZE 订单尺寸 + +> */exchangeInfo 响应中的格式:** + +```javascript + { + "filterType": "LOT_SIZE", + "minQty": "0.00100000", + "maxQty": "100000.00000000", + "stepSize": "0.00100000" + } +``` + +lots是拍卖术语,这个过滤器对订单中的`quantity`也就是数量参数进行合法性检查。包含三个部分: + +* `minQty` 表示 `quantity` 允许的最小值. +* `maxQty` 表示 `quantity` 允许的最大值 +* `stepSize` 表示 `quantity`允许的步进值。 + +逻辑伪代码如下: + +* `quantity` >= `minQty` +* `quantity` <= `maxQty` +* (`quantity`-`minQty`) % `stepSize` == 0 + + +#### MARKET_LOT_SIZE 市价订单尺寸 +参考LOT_SIZE,区别仅在于对市价单还是限价单生效 + +#### MAX_NUM_ORDERS 最多订单数 + + +> **/exchangeInfo 响应中的格式:** + +```javascript + { + "filterType": "MAX_NUM_ORDERS", + "limit": 200 + } +``` + +定义了某个交易对最多允许的挂单数量(不包括已关闭的订单) + +普通订单与条件订单均计算在内 + + +#### MAX_NUM_ALGO_ORDERS 最多条件订单数 + +> **/exchangeInfo format:** + +```javascript + { + "filterType": "MAX_NUM_ALGO_ORDERS", + "limit": 100 + } +``` + +定义了某个交易对最多允许的条件订单的挂单数量(不包括已关闭的订单)。 + +条件订单目前包括`STOP`, `STOP_MARKET`, `TAKE_PROFIT`, `TAKE_PROFIT_MARKET`, 和 `TRAILING_STOP_MARKET` + + +#### PERCENT_PRICE 价格振幅过滤器 + +> **/exchangeInfo 响应中的格式:** + +```javascript + { + "filterType": "PERCENT_PRICE", + "multiplierUp": "1.1500", + "multiplierDown": "0.8500", + "multiplierDecimal": 4 + } +``` + +`PERCENT_PRICE` 定义了基于标记价格计算的挂单价格的可接受区间. + +挂单价格必须同时满足以下条件: + +* 买单: `price` <= `markPrice` * `multiplierUp` +* 卖单: `price` >= `markPrice` * `multiplierDown` + + +#### MIN_NOTIONAL 最小名义价值 + +> **/exchangeInfo 响应中的格式:** + +```javascript + { + "filterType": "MIN_NOTIONAL", + "notioanl": "1" + } +``` + +MIN_NOTIONAL过滤器定义了交易对订单所允许的最小名义价值(成交额)。 +订单的名义价值是`价格`*`数量`。 +由于`MARKET`订单没有价格,因此会使用 mark price 计算。 + + + + + + +--- + + +# 行情接口 +## 测试服务器连通性 PING +`` +GET /fapi/v3/ping +`` + +> **响应:** + +```javascript +{} +``` + +测试能否联通 + +**权重:** +1 + +**参数:** +NONE + + + +## 获取服务器时间 + +> **响应:** + +```javascript +{ + "serverTime": 1499827319559 // 当前的系统时间 +} +``` + +`` +GET /fapi/v3/time +`` + +获取服务器时间 + +**权重:** +1 + +**参数:** +NONE + + +## 获取交易规则和交易对 + +> **响应:** + +```javascript +{ + "exchangeFilters": [], + "rateLimits": [ // API访问的限制 + { + "interval": "MINUTE", // 按照分钟计算 + "intervalNum": 1, // 按照1分钟计算 + "limit": 2400, // 上限次数 + "rateLimitType": "REQUEST_WEIGHT" // 按照访问权重来计算 + }, + { + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200, + "rateLimitType": "ORDERS" // 按照订单数量来计算 + } + ], + "serverTime": 1565613908500, // 请忽略。如果需要获取当前系统时间,请查询接口 “GET /fapi/v3/time” + "assets": [ // 资产信息 + { + "asset": "BUSD", + "marginAvailable": true, // 是否可用作保证金 + "autoAssetExchange": 0 // 保证金资产自动兑换阈值 + }, + { + "asset": "USDT", + "marginAvailable": true, // 是否可用作保证金 + "autoAssetExchange": 0 // 保证金资产自动兑换阈值 + }, + { + "asset": "BNB", + "marginAvailable": false, // 是否可用作保证金 + "autoAssetExchange": null // 保证金资产自动兑换阈值 + } + ], + "symbols": [ // 交易对信息 + { + "symbol": "BLZUSDT", // 交易对 + "pair": "BLZUSDT", // 标的交易对 + "contractType": "PERPETUAL", // 合约类型 + "deliveryDate": 4133404800000, // 交割日期 + "onboardDate": 1598252400000, // 上线日期 + "status": "TRADING", // 交易对状态 + "maintMarginPercent": "2.5000", // 请忽略 + "requiredMarginPercent": "5.0000", // 请忽略 + "baseAsset": "BLZ", // 标的资产 + "quoteAsset": "USDT", // 报价资产 + "marginAsset": "USDT", // 保证金资产 + "pricePrecision": 5, // 价格小数点位数(仅作为系统精度使用,注意同tickSize 区分) + "quantityPrecision": 0, // 数量小数点位数(仅作为系统精度使用,注意同stepSize 区分) + "baseAssetPrecision": 8, // 标的资产精度 + "quotePrecision": 8, // 报价资产精度 + "underlyingType": "COIN", + "underlyingSubType": ["STORAGE"], + "settlePlan": 0, + "triggerProtect": "0.15", // 开启"priceProtect"的条件订单的触发阈值 + "filters": [ + { + "filterType": "PRICE_FILTER", // 价格限制 + "maxPrice": "300", // 价格上限, 最大价格 + "minPrice": "0.0001", // 价格下限, 最小价格 + "tickSize": "0.0001" // 订单最小价格间隔 + }, + { + "filterType": "LOT_SIZE", // 数量限制 + "maxQty": "10000000", // 数量上限, 最大数量 + "minQty": "1", // 数量下限, 最小数量 + "stepSize": "1" // 订单最小数量间隔 + }, + { + "filterType": "MARKET_LOT_SIZE", // 市价订单数量限制 + "maxQty": "590119", // 数量上限, 最大数量 + "minQty": "1", // 数量下限, 最小数量 + "stepSize": "1" // 允许的步进值 + }, + { + "filterType": "MAX_NUM_ORDERS", // 最多订单数限制 + "limit": 200 + }, + { + "filterType": "MAX_NUM_ALGO_ORDERS", // 最多条件订单数限制 + "limit": 100 + }, + { + "filterType": "MIN_NOTIONAL", // 最小名义价值 + "notional": "1", + }, + { + "filterType": "PERCENT_PRICE", // 价格比限制 + "multiplierUp": "1.1500", // 价格上限百分比 + "multiplierDown": "0.8500", // 价格下限百分比 + "multiplierDecimal": 4 + } + ], + "OrderType": [ // 订单类型 + "LIMIT", // 限价单 + "MARKET", // 市价单 + "STOP", // 止损单 + "STOP_MARKET", // 止损市价单 + "TAKE_PROFIT", // 止盈单 + "TAKE_PROFIT_MARKET", // 止盈暑市价单 + "TRAILING_STOP_MARKET" // 跟踪止损市价单 + ], + "timeInForce": [ // 有效方式 + "GTC", // 成交为止, 一直有效 + "IOC", // 无法立即成交(吃单)的部分就撤销 + "FOK", // 无法全部立即成交就撤销 + "GTX" // 无法成为挂单方就撤销 + ], + "liquidationFee": "0.010000", // 强平费率 + "marketTakeBound": "0.30", // 市价吃单(相对于标记价格)允许可造成的最大价格偏离比例 + } + ], + "timezone": "UTC" // 服务器所用的时间区域 +} + +``` + +`` +GET /fapi/v3/exchangeInfo +`` + +获取交易规则和交易对 + +**权重:** +1 + +**参数:** +NONE + + + +## 深度信息 + +> **响应:** + +```javascript +{ + "lastUpdateId": 1027024, + "E": 1589436922972, // 消息时间 + "T": 1589436922959, // 撮合引擎时间 + "bids": [ // 买单 + [ + "4.00000000", // 价格 + "431.00000000" // 数量 + ] + ], + "asks": [ // 卖单 + [ + "4.00000200", // 价格 + "12.00000000" // 数量 + ] + ] +} +``` + +`` +GET /fapi/v3/depth +`` + +**权重:** + +limit | 权重 +------------ | ------------ +5, 10, 20, 50 | 2 +100 | 5 +500 | 10 +1000 | 20 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +------ | ------ | -------- | ----------------------------------------------------------- +symbol | STRING | YES | 交易对 +limit | INT | NO | 默认 500; 可选值:[5, 10, 20, 50, 100, 500, 1000] + + + +## 近期成交 + +> **响应:** + +```javascript +[ + { + "id": 28457, // 成交ID + "price": "4.00000100", // 成交价格 + "qty": "12.00000000", // 成交量 + "quoteQty": "48.00", // 成交额 + "time": 1499865549590, // 时间 + "isBuyerMaker": true // 买方是否为挂单方 + } +] +``` + +`` +GET /fapi/v3/trades +`` + +获取近期订单簿成交 + +**权重:** +1 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +------ | ------ | -------- | ---------------------- +symbol | STRING | YES | 交易对 +limit | INT | NO | 默认:500,最大1000 + +* 仅返回订单簿成交,即不会返回保险基金和自动减仓(ADL)成交 + +## 查询历史成交(MARKET_DATA) + +> **响应:** + +```javascript +[ + { + "id": 28457, // 成交ID + "price": "4.00000100", // 成交价格 + "qty": "12.00000000", // 成交量 + "quoteQty": "48.00", // 成交额 + "time": 1499865549590, // 时间 + "isBuyerMaker": true // 买方是否为挂单方 + } +] +``` + +`` +GET /fapi/v3/historicalTrades +`` + +查询订单簿历史成交 + +**权重:** +20 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +------ | ------ | -------- | ---------------------------------------------- +symbol | STRING | YES | 交易对 +limit | INT | NO | 默认值:500 最大值:1000. +fromId | LONG | NO | 从哪一条成交id开始返回. 缺省返回最近的成交记录 + +* 仅返回订单簿成交,即不会返回保险基金和自动减仓(ADL)成交 + +## 近期成交(归集) + +> **响应:** + +```javascript +[ + { + "a": 26129, // 归集成交ID + "p": "0.01633102", // 成交价 + "q": "4.70443515", // 成交量 + "f": 27781, // 被归集的首个成交ID + "l": 27781, // 被归集的末个成交ID + "T": 1498793709153, // 成交时间 + "m": true, // 是否为主动卖出单 + } +] +``` + +`` +GET /fapi/v3/aggTrades +`` + +归集交易与逐笔交易的区别在于,同一价格、同一方向、同一时间(按秒计算)的订单簿trade会被聚合为一条 + +**权重:** +20 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +--------- | ------ | -------- | ---------------------------------- +symbol | STRING | YES | 交易对 +fromId | LONG | NO | 从包含fromID的成交开始返回结果 +startTime | LONG | NO | 从该时刻之后的成交记录开始返回结果 +endTime | LONG | NO | 返回该时刻为止的成交记录 +limit | INT | NO | 默认 500; 最大 1000. + +* 如果同时发送`startTime`和`endTime`,间隔必须小于一小时 +* 如果没有发送任何筛选参数(`fromId`, `startTime`, `endTime`),默认返回最近的成交记录 +* 保险基金和自动减仓(ADL)成交不属于订单簿成交,故不会被归并聚合 + + +## K线数据 + +> **响应:** + +```javascript +[ + [ + 1499040000000, // 开盘时间 + "0.01634790", // 开盘价 + "0.80000000", // 最高价 + "0.01575800", // 最低价 + "0.01577100", // 收盘价(当前K线未结束的即为最新价) + "148976.11427815", // 成交量 + 1499644799999, // 收盘时间 + "2434.19055334", // 成交额 + 308, // 成交笔数 + "1756.87402397", // 主动买入成交量 + "28.46694368", // 主动买入成交额 + "17928899.62484339" // 请忽略该参数 + ] +] +``` + +`` +GET /fapi/v3/klines +`` + +每根K线的开盘时间可视为唯一ID + +**权重:** 取决于请求中的LIMIT参数 + +LIMIT参数 | 权重 +---|--- +[1,100) | 1 +[100, 500) | 2 +[500, 1000] | 5 +> 1000 | 10 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +--------- | ------ | -------- | ---------------------- +symbol | STRING | YES | 交易对 +interval | ENUM | YES | 时间间隔 +startTime | LONG | NO | 起始时间 +endTime | LONG | NO | 结束时间 +limit | INT | NO | 默认值:500 最大值:1500. + +* 缺省返回最近的数据 + + + +## 价格指数K线数据 + +> **响应:** + +```javascript +[ + [ + 1591256400000, // 开盘时间 + "9653.69440000", // 开盘价 + "9653.69640000", // 最高价 + "9651.38600000", // 最低价 + "9651.55200000", // 收盘价(当前K线未结束的即为最新价) + "0 ", // 请忽略 + 1591256459999, // 收盘时间 + "0", // 请忽略 + 60, // 构成记录数 + "0", // 请忽略 + "0", // 请忽略 + "0" // 请忽略 + ] +] +``` + +`` +GET /fapi/v3/indexPriceKlines +`` + +每根K线的开盘时间可视为唯一ID + +**权重:** 取决于请求中的LIMIT参数 + +LIMIT参数 | 权重 +---|--- +[1,100) | 1 +[100, 500) | 2 +[500, 1000] | 5 +> 1000 | 10 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +--------- | ------ | -------- | ---------------------- +pair | STRING | YES | 标的交易对 +interval | ENUM | YES | 时间间隔 +startTime | LONG | NO | 起始时间 +endTime | LONG | NO | 结束时间 +limit | INT | NO | 默认值:500 最大值:1500 + +* 缺省返回最近的数据 + + +## 标记价格K线数据 + +> **响应:** + +```javascript +[ + [ + 1591256400000, // 开盘时间 + "9653.69440000", // 开盘价 + "9653.69640000", // 最高价 + "9651.38600000", // 最低价 + "9651.55200000", // 收盘价(当前K线未结束的即为最新价) + "0 ", // 请忽略 + 1591256459999, // 收盘时间 + "0", // 请忽略 + 60, // 构成记录数 + "0", // 请忽略 + "0", // 请忽略 + "0" // 请忽略 + ] +] +``` + +`` +GET /fapi/v3/markPriceKlines +`` +每根K线的开盘时间可视为唯一ID + +**权重:** 取决于请求中的LIMIT参数 + +LIMIT参数 | 权重 +---|--- +[1,100) | 1 +[100, 500) | 2 +[500, 1000] | 5 +> 1000 | 10 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +--------- | ------ | -------- | ---------------------- +symbol | STRING | YES | 交易对 +interval | ENUM | YES | 时间间隔 +startTime | LONG | NO | 起始时间 +endTime | LONG | NO | 结束时间 +limit | INT | NO | 默认值:500 最大值:1500 + +* 缺省返回最近的数据 + + +## 最新标记价格和资金费率 + +> **响应:** + +```javascript +{ + "symbol": "BTCUSDT", // 交易对 + "markPrice": "11793.63104562", // 标记价格 + "indexPrice": "11781.80495970", // 指数价格 + "estimatedSettlePrice": "11781.16138815", // 预估结算价,仅在交割开始前最后一小时有意义 + "lastFundingRate": "0.00038246", // 最近更新的资金费率 + "nextFundingTime": 1597392000000, // 下次资金费时间 + "interestRate": "0.00010000", // 标的资产基础利率 + "time": 1597370495002 // 更新时间 +} +``` + +> **当不指定symbol时相应** + +```javascript +[ + { + "symbol": "BTCUSDT", // 交易对 + "markPrice": "11793.63104562", // 标记价格 + "indexPrice": "11781.80495970", // 指数价格 + "estimatedSettlePrice": "11781.16138815", // 预估结算价,仅在交割开始前最后一小时有意义 + "lastFundingRate": "0.00038246", // 最近更新的资金费率 + "nextFundingTime": 1597392000000, // 下次资金费时间 + "interestRate": "0.00010000", // 标的资产基础利率 + "time": 1597370495002 // 更新时间 + } +] +``` + + +`` +GET /fapi/v3/premiumIndex +`` + +采集各大交易所数据加权平均 + +**权重:** +1 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +------ | ------ | -------- | ------ +symbol | STRING | NO | 交易对 + + +## 查询资金费率历史 + +> **响应:** + +```javascript +[ + { + "symbol": "BTCUSDT", // 交易对 + "fundingRate": "-0.03750000", // 资金费率 + "fundingTime": 1570608000000, // 资金费时间 + }, + { + "symbol": "BTCUSDT", + "fundingRate": "0.00010000", + "fundingTime": 1570636800000, + } +] +``` + +`` +GET /fapi/v3/fundingRate +`` + +**权重:** +1 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +--------- | ------ | -------- | ----------------------------------------------------- +symbol | STRING | NO | 交易对 +startTime | LONG | NO | 起始时间 +endTime | LONG | NO | 结束时间 +limit | INT | NO | 默认值:100 最大值:1000 + +* 如果 `startTime` 和 `endTime` 都未发送, 返回最近 `limit` 条数据. +* 如果 `startTime` 和 `endTime` 之间的数据量大于 `limit`, 返回 `startTime` + `limit`情况下的数据。 + + +## 24hr价格变动情况 + +> **响应:** + +```javascript +{ + "symbol": "BTCUSDT", + "priceChange": "-94.99999800", //24小时价格变动 + "priceChangePercent": "-95.960", //24小时价格变动百分比 + "weightedAvgPrice": "0.29628482", //加权平均价 + "lastPrice": "4.00000200", //最近一次成交价 + "lastQty": "200.00000000", //最近一次成交额 + "openPrice": "99.00000000", //24小时内第一次成交的价格 + "highPrice": "100.00000000", //24小时最高价 + "lowPrice": "0.10000000", //24小时最低价 + "volume": "8913.30000000", //24小时成交量 + "quoteVolume": "15.30000000", //24小时成交额 + "openTime": 1499783499040, //24小时内,第一笔交易的发生时间 + "closeTime": 1499869899040, //24小时内,最后一笔交易的发生时间 + "firstId": 28385, // 首笔成交id + "lastId": 28460, // 末笔成交id + "count": 76 // 成交笔数 +} +``` + +> 或(当不发送交易对信息) + +```javascript +[ + { + "symbol": "BTCUSDT", + "priceChange": "-94.99999800", //24小时价格变动 + "priceChangePercent": "-95.960", //24小时价格变动百分比 + "weightedAvgPrice": "0.29628482", //加权平均价 + "lastPrice": "4.00000200", //最近一次成交价 + "lastQty": "200.00000000", //最近一次成交额 + "openPrice": "99.00000000", //24小时内第一次成交的价格 + "highPrice": "100.00000000", //24小时最高价 + "lowPrice": "0.10000000", //24小时最低价 + "volume": "8913.30000000", //24小时成交量 + "quoteVolume": "15.30000000", //24小时成交额 + "openTime": 1499783499040, //24小时内,第一笔交易的发生时间 + "closeTime": 1499869899040, //24小时内,最后一笔交易的发生时间 + "firstId": 28385, // 首笔成交id + "lastId": 28460, // 末笔成交id + "count": 76 // 成交笔数 + } +] +``` + +`` +GET /fapi/v3/ticker/24hr +`` + +请注意,不携带symbol参数会返回全部交易对数据,不仅数据庞大,而且权重极高 + +**权重:** +* 带symbol为`1` +* 不带为`40` + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +------ | ------ | -------- | ------ +symbol | STRING | NO | 交易对 + +* 不发送交易对参数,则会返回所有交易对信息 + + +## 最新价格 + +> **响应:** + +```javascript +{ + "symbol": "LTCBTC", // 交易对 + "price": "4.00000200", // 价格 + "time": 1589437530011 // 撮合引擎时间 +} +``` + +> 或(当不发送symbol) + +```javascript +[ + { + "symbol": "BTCUSDT", // 交易对 + "price": "6000.01", // 价格 + "time": 1589437530011 // 撮合引擎时间 + } +] +``` + +`` +GET /fapi/v3/ticker/price +`` + +返回最近价格 + +**权重:** +* 单交易对`1` +* 无交易对`2` + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +------ | ------ | -------- | ------ +symbol | STRING | NO | 交易对 + +* 不发送交易对参数,则会返回所有交易对信息 + + +## 当前最优挂单 + +> **响应:** + +```javascript +{ + "symbol": "BTCUSDT", // 交易对 + "bidPrice": "4.00000000", //最优买单价 + "bidQty": "431.00000000", //挂单量 + "askPrice": "4.00000200", //最优卖单价 + "askQty": "9.00000000", //挂单量 + "time": 1589437530011 // 撮合引擎时间 +} +``` +> 或(当不发送symbol) + +```javascript +[ + { + "symbol": "BTCUSDT", // 交易对 + "bidPrice": "4.00000000", //最优买单价 + "bidQty": "431.00000000", //挂单量 + "askPrice": "4.00000200", //最优卖单价 + "askQty": "9.00000000", //挂单量 + "time": 1589437530011 // 撮合引擎时间 + } +] +``` + +`` +GET /fapi/v3/ticker/bookTicker +`` + +返回当前最优的挂单(最高买单,最低卖单) + +**权重:** +* 单交易对`1` +* 无交易对`2` + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +------ | ------ | -------- | ------ +symbol | STRING | NO | 交易对 + +* 不发送交易对参数,则会返回所有交易对信息 + + + + +# Websocket 行情推送 + +* 本篇所列出的所有wss接口baseurl: **wss://fstream.asterdex.com** +* 订阅单一stream格式为 **/ws/\** +* 组合streams的URL格式为 **/stream?streams=\/\/\** +* 订阅组合streams时,事件payload会以这样的格式封装 **{"stream":"\","data":\}** +* stream名称中所有交易对均为**小写** +* 每个链接有效期不超过24小时,请妥善处理断线重连。 +* 服务端每5分钟会发送ping帧,客户端应当在15分钟内回复pong帧,否则服务端会主动断开链接。允许客户端发送不成对的pong帧(即客户端可以以高于15分钟每次的频率发送pong帧保持链接)。 +* Websocket服务器每秒最多接受10个订阅消息。 +* 如果用户发送的消息超过限制,连接会被断开连接。反复被断开连接的IP有可能被服务器屏蔽。 +* 单个连接最多可以订阅 **200** 个Streams。 + + + + +## 实时订阅/取消数据流 + +* 以下数据可以通过websocket发送以实现订阅或取消订阅数据流。示例如下。 +* 响应内容中的`id`是无符号整数,作为往来信息的唯一标识。 + +### 订阅一个信息流 + +> **响应** + + ```javascript + { + "result": null, + "id": 1 + } + ``` + +* **请求** + + { + "method": "SUBSCRIBE", + "params": + [ + "btcusdt@aggTrade", + "btcusdt@depth" + ], + "id": 1 + } + + + +### 取消订阅一个信息流 + +> **响应** + + ```javascript + { + "result": null, + "id": 312 + } + ``` + +* **请求** + + { + "method": "UNSUBSCRIBE", + "params": + [ + "btcusdt@depth" + ], + "id": 312 + } + + + +### 已订阅信息流 + +> **响应** + + ```javascript + { + "result": [ + "btcusdt@aggTrade" + ], + "id": 3 + } + ``` + + +* **请求** + + { + "method": "LIST_SUBSCRIPTIONS", + "id": 3 + } + + + +### 设定属性 +当前,唯一可以设置的属性是设置是否启用`combined`("组合")信息流。 +当使用`/ws/`("原始信息流")进行连接时,combined属性设置为`false`,而使用 `/stream/`进行连接时则将属性设置为`true`。 + + +> **响应** + + ```javascript + { + "result": null + "id": 5 + } + ``` + +* **请求** + + { + "method": "SET_PROPERTY", + "params": + [ + "combined", + true + ], + "id": 5 + } + + + + +### 检索属性 + +> **响应** + + ```javascript + { + "result": true, // Indicates that combined is set to true. + "id": 2 + } + ``` + +* **请求** + + { + "method": "GET_PROPERTY", + "params": + [ + "combined" + ], + "id": 2 + } + + + + +### 错误信息 + +错误信息 | 描述 +---|--- +{"code": 0, "msg": "Unknown property"} | `SET_PROPERTY` 或 `GET_PROPERTY`中应用的参数无效 +{"code": 1, "msg": "Invalid value type: expected Boolean"} | 仅接受`true`或`false` +{"code": 2, "msg": "Invalid request: property name must be a string"}| 提供的属性名无效 +{"code": 2, "msg": "Invalid request: request ID must be an unsigned integer"}| 参数`id`未提供或`id`值是无效类型 +{"code": 2, "msg": "Invalid request: unknown variant %s, expected one of `SUBSCRIBE`, `UNSUBSCRIBE`, `LIST_SUBSCRIPTIONS`, `SET_PROPERTY`, `GET_PROPERTY` at line 1 column 28"} | 错字提醒,或提供的值不是预期类型 +{"code": 2, "msg": "Invalid request: too many parameters"}| 数据中提供了不必要参数 +{"code": 2, "msg": "Invalid request: property name must be a string"} | 未提供属性名 +{"code": 2, "msg": "Invalid request: missing field `method` at line 1 column 73"} | 数据未提供`method` +{"code":3,"msg":"Invalid JSON: expected value at line %s column %s"} | JSON 语法有误. + + + + +## 最新合约价格 +aggTrade中的价格'p'或ticker/miniTicker中的价格'c'均可以作为最新成交价。 + +## 归集交易 + +> **Payload:** + +```javascript +{ + "e": "aggTrade", // 事件类型 + "E": 123456789, // 事件时间 + "s": "BNBUSDT", // 交易对 + "a": 5933014, // 归集成交 ID + "p": "0.001", // 成交价格 + "q": "100", // 成交量 + "f": 100, // 被归集的首个交易ID + "l": 105, // 被归集的末次交易ID + "T": 123456785, // 成交时间 + "m": true // 买方是否是做市方。如true,则此次成交是一个主动卖出单,否则是一个主动买入单。 +} +``` + +同一价格、同一方向、同一时间(100ms计算)的trade会被聚合为一条. + +**Stream Name:** +``@aggTrade`` + +**Update Speed:** 100ms + + + + + +## 最新标记价格 + +> **Payload:** + +```javascript + { + "e": "markPriceUpdate", // 事件类型 + "E": 1562305380000, // 事件时间 + "s": "BTCUSDT", // 交易对 + "p": "11794.15000000", // 标记价格 + "i": "11784.62659091", // 现货指数价格 + "P": "11784.25641265", // 预估结算价,仅在结算前最后一小时有参考价值 + "r": "0.00038167", // 资金费率 + "T": 1562306400000 // 下次资金时间 + } +``` + + +**Stream Name:** +``@markPrice`` 或 ``@markPrice@1s`` + +**Update Speed:** 3000ms 或 1000ms + + + + + + +## 全市场最新标记价格 + +> **Payload:** + +```javascript +[ + { + "e": "markPriceUpdate", // 事件类型 + "E": 1562305380000, // 事件时间 + "s": "BTCUSDT", // 交易对 + "p": "11185.87786614", // 标记价格 + "i": "11784.62659091" // 现货指数价格 + "P": "11784.25641265", // 预估结算价,仅在结算前最后一小时有参考价值 + "r": "0.00030000", // 资金费率 + "T": 1562306400000 // 下个资金时间 + } +] +``` + + +**Stream Name:** +``!markPrice@arr`` 或 ``!markPrice@arr@1s`` + +**Update Speed:** 3000ms 或 1000ms + + + + + +## K线 + +> **Payload:** + +```javascript +{ + "e": "kline", // 事件类型 + "E": 123456789, // 事件时间 + "s": "BNBUSDT", // 交易对 + "k": { + "t": 123400000, // 这根K线的起始时间 + "T": 123460000, // 这根K线的结束时间 + "s": "BNBUSDT", // 交易对 + "i": "1m", // K线间隔 + "f": 100, // 这根K线期间第一笔成交ID + "L": 200, // 这根K线期间末一笔成交ID + "o": "0.0010", // 这根K线期间第一笔成交价 + "c": "0.0020", // 这根K线期间末一笔成交价 + "h": "0.0025", // 这根K线期间最高成交价 + "l": "0.0015", // 这根K线期间最低成交价 + "v": "1000", // 这根K线期间成交量 + "n": 100, // 这根K线期间成交笔数 + "x": false, // 这根K线是否完结(是否已经开始下一根K线) + "q": "1.0000", // 这根K线期间成交额 + "V": "500", // 主动买入的成交量 + "Q": "0.500", // 主动买入的成交额 + "B": "123456" // 忽略此参数 + } +} +``` + +K线stream逐秒推送所请求的K线种类(最新一根K线)的更新。推送间隔250毫秒(如有刷新) + +**订阅Kline需要提供间隔参数,最短为分钟线,最长为月线。支持以下间隔:** + +m -> 分钟; h -> 小时; d -> 天; w -> 周; M -> 月 + +* 1m +* 3m +* 5m +* 15m +* 30m +* 1h +* 2h +* 4h +* 6h +* 8h +* 12h +* 1d +* 3d +* 1w +* 1M + +**Stream Name:** +``@kline_`` + +**Update Speed:** 250ms + + + + +## 按Symbol的精简Ticker + +> **Payload:** + +```javascript + { + "e": "24hrMiniTicker", // 事件类型 + "E": 123456789, // 事件时间(毫秒) + "s": "BNBUSDT", // 交易对 + "c": "0.0025", // 最新成交价格 + "o": "0.0010", // 24小时前开始第一笔成交价格 + "h": "0.0025", // 24小时内最高成交价 + "l": "0.0010", // 24小时内最低成交价 + "v": "10000", // 成交量 + "q": "18" // 成交额 + } +``` + +按Symbol刷新的24小时精简ticker信息. + +**Stream Name:** +``@miniTicker` + +**Update Speed:** 500ms + + + +## 全市场的精简Ticker + +> **Payload:** + +```javascript +[ + { + "e": "24hrMiniTicker", // 事件类型 + "E": 123456789, // 事件时间(毫秒) + "s": "BNBUSDT", // 交易对 + "c": "0.0025", // 最新成交价格 + "o": "0.0010", // 24小时前开始第一笔成交价格 + "h": "0.0025", // 24小时内最高成交价 + "l": "0.0010", // 24小时内最低成交价 + "v": "10000", // 成交量 + "q": "18" // 成交额 + } +] +``` + +所有symbol24小时精简ticker信息.需要注意的是,只有发生变化的ticker更新才会被推送。 + +**Stream Name:** +`!miniTicker@arr` + +**Update Speed:** 1000ms + + + + +## 按Symbol的完整Ticker + + +> **Payload:** + +```javascript +{ + "e": "24hrTicker", // 事件类型 + "E": 123456789, // 事件时间 + "s": "BNBUSDT", // 交易对 + "p": "0.0015", // 24小时价格变化 + "P": "250.00", // 24小时价格变化(百分比) + "w": "0.0018", // 平均价格 + "c": "0.0025", // 最新成交价格 + "Q": "10", // 最新成交价格上的成交量 + "o": "0.0010", // 24小时内第一比成交的价格 + "h": "0.0025", // 24小时内最高成交价 + "l": "0.0010", // 24小时内最低成交价 + "v": "10000", // 24小时内成交量 + "q": "18", // 24小时内成交额 + "O": 0, // 统计开始时间 + "C": 86400000, // 统计关闭时间 + "F": 0, // 24小时内第一笔成交交易ID + "L": 18150, // 24小时内最后一笔成交交易ID + "n": 18151 // 24小时内成交数 +} +``` + +按Symbol刷新的24小时完整ticker信息 + +**Stream Name:** +``@ticker`` + +**Update Speed:** 500ms + + + +## 全市场的完整Ticker + + +> **Payload:** + +```javascript +[ + { + "e": "24hrTicker", // 事件类型 + "E": 123456789, // 事件时间 + "s": "BNBUSDT", // 交易对 + "p": "0.0015", // 24小时价格变化 + "P": "250.00", // 24小时价格变化(百分比) + "w": "0.0018", // 平均价格 + "c": "0.0025", // 最新成交价格 + "Q": "10", // 最新成交价格上的成交量 + "o": "0.0010", // 24小时内第一比成交的价格 + "h": "0.0025", // 24小时内最高成交价 + "l": "0.0010", // 24小时内最低成交价 + "v": "10000", // 24小时内成交量 + "q": "18", // 24小时内成交额 + "O": 0, // 统计开始时间 + "C": 86400000, // 统计结束时间 + "F": 0, // 24小时内第一笔成交交易ID + "L": 18150, // 24小时内最后一笔成交交易ID + "n": 18151 // 24小时内成交数 + } +] +``` + +所有symbol 24小时完整ticker信息.需要注意的是,只有发生变化的ticker更新才会被推送。 + +**Stream Name:** +``!ticker@arr`` + +**Update Speed:** 1000ms + + +## 按Symbol的最优挂单信息 + +> **Payload:** + +```javascript +{ + "e":"bookTicker", // 事件类型 + "u":400900217, // 更新ID + "E": 1568014460893, // 事件推送时间 + "T": 1568014460891, // 撮合时间 + "s":"BNBUSDT", // 交易对 + "b":"25.35190000", // 买单最优挂单价格 + "B":"31.21000000", // 买单最优挂单数量 + "a":"25.36520000", // 卖单最优挂单价格 + "A":"40.66000000" // 卖单最优挂单数量 +} +``` + + +实时推送指定交易对最优挂单信息 + +**Stream Name:** `@bookTicker` + +**Update Speed:** 实时 + + + + + +## 全市场最优挂单信息 + +> **Payload:** + +```javascript +{ + // Same as @bookTicker payload +} +``` + +所有交易对交易对最优挂单信息 + +**Stream Name:** `!bookTicker` + +**Update Speed:** 实时 + + + +##强平订单 + +> **Payload:** + +```javascript +{ + + "e":"forceOrder",                   // 事件类型 + "E":1568014460893,                  // 事件时间 + "o":{ + + "s":"BTCUSDT",                   // 交易对 + "S":"SELL",                      // 订单方向 + "o":"LIMIT",                     // 订单类型 + "f":"IOC",                       // 有效方式 + "q":"0.014",                     // 订单数量 + "p":"9910",                      // 订单价格 + "ap":"9910",                     // 平均价格 + "X":"FILLED",                    // 订单状态 + "l":"0.014",                     // 订单最近成交量 + "z":"0.014",                     // 订单累计成交量 + "T":1568014460893,          // 交易时间 + + } + +} +``` + +推送特定`symbol`的强平订单快照信息。 + +1000ms内至多仅推送一条最近的强平订单作为快照 + +**Stream Name:**  ``@forceOrder`` + +**Update Speed:** 1000ms + + + + + +## 有限档深度信息 + +> **Payload:** + +```javascript +{ + "e": "depthUpdate", // 事件类型 + "E": 1571889248277, // 事件时间 + "T": 1571889248276, // 交易时间 + "s": "BTCUSDT", + "U": 390497796, + "u": 390497878, + "pu": 390497794, + "b": [ // 买方 + [ + "7403.89", // 价格 + "0.002" // 数量 + ], + [ + "7403.90", + "3.906" + ], + [ + "7404.00", + "1.428" + ], + [ + "7404.85", + "5.239" + ], + [ + "7405.43", + "2.562" + ] + ], + "a": [ // 卖方 + [ + "7405.96", // 价格 + "3.340" // 数量 + ], + [ + "7406.63", + "4.525" + ], + [ + "7407.08", + "2.475" + ], + [ + "7407.15", + "4.800" + ], + [ + "7407.20", + "0.175" + ] + ] +} +``` + +推送有限档深度信息。levels表示几档买卖单信息, 可选 5/10/20档 + +**Stream Names:** `@depth` 或 `@depth@500ms` 或 `@depth@100ms`. + +**Update Speed:** 250ms 或 500ms 或 100ms + + + + +## 增量深度信息 + +> **Payload:** + +```javascript +{ + "e": "depthUpdate", // 事件类型 + "E": 123456789, // 事件时间 + "T": 123456788, // 撮合时间 + "s": "BNBUSDT", // 交易对 + "U": 157, // 从上次推送至今新增的第一个 update Id + "u": 160, // 从上次推送至今新增的最后一个 update Id + "pu": 149, // 上次推送的最后一个update Id(即上条消息的‘u’) + "b": [ // 变动的买单深度 + [ + "0.0024", // 价格 + "10" // 数量 + ] + ], + "a": [ // 变动的卖单深度 + [ + "0.0026", // 价格 + "100" // 数量 + ] + ] +} +``` + +orderbook的变化部分,推送间隔250毫秒,500毫秒,100毫秒(如有刷新) + +**Stream 名称:** +``@depth`` OR ``@depth@500ms`` OR ``@depth@100ms`` + +**Update Speed:** 250ms 或 500ms 或 100ms + + +## 如何正确在本地维护一个orderbook副本 +1. 订阅 **wss://fstream.asterdex.com/stream?streams=btcusdt@depth** +2. 开始缓存收到的更新。同一个价位,后收到的更新覆盖前面的。 +3. 访问Rest接口 **https://fapi.asterdex.com/fapi/v3/depth?symbol=BTCUSDT&limit=1000**获得一个1000档的深度快照 +4. 将目前缓存到的信息中`u`< 步骤3中获取到的快照中的`lastUpdateId`的部分丢弃(丢弃更早的信息,已经过期)。 +5. 将深度快照中的内容更新到本地orderbook副本中,并从websocket接收到的第一个`U` <= `lastUpdateId` **且** `u` >= `lastUpdateId` 的event开始继续更新本地副本。 +6. 每一个新event的`pu`应该等于上一个event的`u`,否则可能出现了丢包,请从step3重新进行初始化。 +7. 每一个event中的挂单量代表这个价格目前的挂单量**绝对值**,而不是相对变化。 +8. 如果某个价格对应的挂单量为0,表示该价位的挂单已经撤单或者被吃,应该移除这个价位。 + + + + +# 账户和交易接口 + + + + +## 更改持仓模式(TRADE) + +> **响应:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +`` +POST /fapi/v3/positionSide/dual (HMAC SHA256) +`` + +变换用户在 ***所有symbol*** 合约上的持仓模式:双向持仓或单向持仓。 + +**权重:** +1 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +---------- | ------ | -------- | ----------------- +dualSidePosition | STRING | YES | "true": 双向持仓模式;"false": 单向持仓模式 +recvWindow | LONG | NO | +timestamp | LONG | YES | + + + +## 查询持仓模式(USER_DATA) + +> **响应:** + +```javascript +{ + "dualSidePosition": true // "true": 双向持仓模式;"false": 单向持仓模式 +} +``` + +`` +GET /fapi/v3/positionSide/dual (HMAC SHA256) +`` + +查询用户目前在 ***所有symbol*** 合约上的持仓模式:双向持仓或单向持仓。 + +**权重:** +30 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +---------- | ------ | -------- | ----------------- +recvWindow | LONG | NO | +timestamp | LONG | YES | + + +## 更改联合保证金模式(TRADE) + +> **响应:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +`` +POST /fapi/v3/multiAssetsMargin (HMAC SHA256) +`` + +变换用户在 ***所有symbol*** 合约上的联合保证金模式:开启或关闭联合保证金模式。 + +**权重:** +1 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +---------- | ------ | -------- | ----------------- +multiAssetsMargin | STRING | YES | "true": 联合保证金模式开启;"false": 联合保证金模式关闭 +recvWindow | LONG | NO | +timestamp | LONG | YES | + + + +## 查询联合保证金模式(USER_DATA) + +> **响应:** + +```javascript +{ + "multiAssetsMargin": true // "true": 联合保证金模式开启;"false": 联合保证金模式关闭 +} +``` + +`` +GET /fapi/v3/multiAssetsMargin (HMAC SHA256) +`` + +查询用户目前在 ***所有symbol*** 合约上的联合保证金模式。 + +**权重:** +30 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +---------- | ------ | -------- | ----------------- +recvWindow | LONG | NO | +timestamp | LONG | YES | + + +## 下单 (TRADE) + + +> **响应:** + +```javascript +{ + "clientOrderId": "testOrder", // 用户自定义的订单号 + "cumQty": "0", + "cumQuote": "0", // 成交金额 + "executedQty": "0", // 成交量 + "orderId": 22542179, // 系统订单号 + "avgPrice": "0.00000", // 平均成交价 + "origQty": "10", // 原始委托数量 + "price": "0", // 委托价格 + "reduceOnly": false, // 仅减仓 + "side": "SELL", // 买卖方向 + "positionSide": "SHORT", // 持仓方向 + "status": "NEW", // 订单状态 + "stopPrice": "0", // 触发价,对`TRAILING_STOP_MARKET`无效 + "closePosition": false, // 是否条件全平仓 + "symbol": "BTCUSDT", // 交易对 + "timeInForce": "GTC", // 有效方法 + "type": "TRAILING_STOP_MARKET", // 订单类型 + "origType": "TRAILING_STOP_MARKET", // 触发前订单类型 + "activatePrice": "9020", // 跟踪止损激活价格, 仅`TRAILING_STOP_MARKET` 订单返回此字段 + "priceRate": "0.3", // 跟踪止损回调比例, 仅`TRAILING_STOP_MARKET` 订单返回此字段 + "updateTime": 1566818724722, // 更新时间 + "workingType": "CONTRACT_PRICE", // 条件价格触发类型 + "priceProtect": false // 是否开启条件单触发保护 +} +``` + +`` +POST /fapi/v3/order (HMAC SHA256) +`` + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +---------------- | ------- | -------- | --- +symbol | STRING | YES | 交易对 +side | ENUM | YES | 买卖方向 `SELL`, `BUY` +positionSide | ENUM | NO | 持仓方向,单向持仓模式下非必填,默认且仅可填`BOTH`;在双向持仓模式下必填,且仅可选择 `LONG` 或 `SHORT` +type | ENUM | YES | 订单类型 `LIMIT`, `MARKET`, `STOP`, `TAKE_PROFIT`, `STOP_MARKET`, `TAKE_PROFIT_MARKET`, `TRAILING_STOP_MARKET` +reduceOnly | STRING | NO | `true`, `false`; 非双开模式下默认`false`;双开模式下不接受此参数; 使用`closePosition`不支持此参数。 +quantity | DECIMAL | NO | 下单数量,使用`closePosition`不支持此参数。 +price | DECIMAL | NO | 委托价格 +newClientOrderId | STRING | NO | 用户自定义的订单号,不可以重复出现在挂单中。如空缺系统会自动赋值。必须满足正则规则 `^[\.A-Z\:/a-z0-9_-]{1,36}$` +stopPrice | DECIMAL | NO | 触发价, 仅 `STOP`, `STOP_MARKET`, `TAKE_PROFIT`, `TAKE_PROFIT_MARKET` 需要此参数 +closePosition | STRING | NO | `true`, `false`;触发后全部平仓,仅支持`STOP_MARKET`和`TAKE_PROFIT_MARKET`;不与`quantity`合用;自带只平仓效果,不与`reduceOnly` 合用 +activationPrice | DECIMAL | NO | 追踪止损激活价格,仅`TRAILING_STOP_MARKET` 需要此参数, 默认为下单当前市场价格(支持不同`workingType`) +callbackRate | DECIMAL | NO | 追踪止损回调比例,可取值范围[0.1, 5],其中 1代表1% ,仅`TRAILING_STOP_MARKET` 需要此参数 +timeInForce | ENUM | NO | 有效方法 +workingType | ENUM | NO | stopPrice 触发类型: `MARK_PRICE`(标记价格), `CONTRACT_PRICE`(合约最新价). 默认 `CONTRACT_PRICE` +priceProtect | STRING | NO | 条件单触发保护:"TRUE","FALSE", 默认"FALSE". 仅 `STOP`, `STOP_MARKET`, `TAKE_PROFIT`, `TAKE_PROFIT_MARKET` 需要此参数 +newOrderRespType | ENUM | NO | "ACK", "RESULT", 默认 "ACK" +recvWindow | LONG | NO | +timestamp | LONG | YES | + +根据 order `type`的不同,某些参数强制要求,具体如下: + +Type | 强制要求的参数 +----------------------------------- | ---------------------------------- +`LIMIT` | `timeInForce`, `quantity`, `price` +`MARKET` | `quantity` +`STOP`, `TAKE_PROFIT` | `quantity`, `price`, `stopPrice` +`STOP_MARKET`, `TAKE_PROFIT_MARKET` | `stopPrice` +`TRAILING_STOP_MARKET` | `callbackRate` + + + +* 条件单的触发必须: + + * 如果订单参数`priceProtect`为true: + * 达到触发价时,`MARK_PRICE`(标记价格)与`CONTRACT_PRICE`(合约最新价)之间的价差不能超过改symbol触发保护阈值 + * 触发保护阈值请参考接口`GET /fapi/v3/exchangeInfo` 返回内容相应symbol中"triggerProtect"字段 + + * `STOP`, `STOP_MARKET` 止损单: + * 买入: 最新合约价格/标记价格高于等于触发价`stopPrice` + * 卖出: 最新合约价格/标记价格低于等于触发价`stopPrice` + * `TAKE_PROFIT`, `TAKE_PROFIT_MARKET` 止盈单: + * 买入: 最新合约价格/标记价格低于等于触发价`stopPrice` + * 卖出: 最新合约价格/标记价格高于等于触发价`stopPrice` + + * `TRAILING_STOP_MARKET` 跟踪止损单: + * 买入: 当合约价格/标记价格区间最低价格低于激活价格`activationPrice`,且最新合约价格/标记价高于等于最低价设定回调幅度。 + * 卖出: 当合约价格/标记价格区间最高价格高于激活价格`activationPrice`,且最新合约价格/标记价低于等于最高价设定回调幅度。 + +* `TRAILING_STOP_MARKET` 跟踪止损单如果遇到报错 ``{"code": -2021, "msg": "Order would immediately trigger."}`` +表示订单不满足以下条件: + * 买入: 指定的`activationPrice` 必须小于 latest price + * 卖出: 指定的`activationPrice` 必须大于 latest price + +* `newOrderRespType` 如果传 `RESULT`: + * `MARKET` 订单将直接返回成交结果; + * 配合使用特殊 `timeInForce` 的 `LIMIT` 订单将直接返回成交或过期拒绝结果。 + +* `STOP_MARKET`, `TAKE_PROFIT_MARKET` 配合 `closePosition`=`true`: + * 条件单触发依照上述条件单触发逻辑 + * 条件触发后,平掉当时持有所有多头仓位(若为卖单)或当时持有所有空头仓位(若为买单) + * 不支持 `quantity` 参数 + * 自带只平仓属性,不支持`reduceOnly`参数 + * 双开模式下,`LONG`方向上不支持`BUY`; `SHORT` 方向上不支持`SELL` + + +## 测试下单接口 (TRADE) + + +> **响应:** + +```javascript +字段与下单接口一致,但均为无效值 +``` + + +`` +POST /fapi/v3/order/test (HMAC SHA256) +`` + +用于测试订单请求,但不会提交到撮合引擎 + +**权重:** +1 + +**参数:** + +参考 `POST /fapi/v3/order` + + + +## 批量下单 (TRADE) + + +> **响应:** + +```javascript +[ + { + "clientOrderId": "testOrder", // 用户自定义的订单号 + "cumQty": "0", + "cumQuote": "0", // 成交金额 + "executedQty": "0", // 成交量 + "orderId": 22542179, // 系统订单号 + "avgPrice": "0.00000", // 平均成交价 + "origQty": "10", // 原始委托数量 + "price": "0", // 委托价格 + "reduceOnly": false, // 仅减仓 + "side": "SELL", // 买卖方向 + "positionSide": "SHORT", // 持仓方向 + "status": "NEW", // 订单状态 + "stopPrice": "0", // 触发价,对`TRAILING_STOP_MARKET`无效 + "closePosition": false, // 是否条件全平仓 + "symbol": "BTCUSDT", // 交易对 + "timeInForce": "GTC", // 有效方法 + "type": "TRAILING_STOP_MARKET", // 订单类型 + "origType": "TRAILING_STOP_MARKET", // 触发前订单类型 + "activatePrice": "9020", // 跟踪止损激活价格, 仅`TRAILING_STOP_MARKET` 订单返回此字段 + "priceRate": "0.3", // 跟踪止损回调比例, 仅`TRAILING_STOP_MARKET` 订单返回此字段 + "updateTime": 1566818724722, // 更新时间 + "workingType": "CONTRACT_PRICE", // 条件价格触发类型 + "priceProtect": false // 是否开启条件单触发保护 + }, + { + "code": -2022, + "msg": "ReduceOnly Order is rejected." + } +] +``` + +`` +POST /fapi/v3/batchOrders (HMAC SHA256) +`` + +**权重:** +5 + +**参数:** + + +名称 | 类型 | 是否必需 | 描述 +---------------- | ------- | -------- | ---- +batchOrders | list | YES | 订单列表,最多支持5个订单 +recvWindow | LONG | NO +timestamp | LONG | YES + +**其中``batchOrders``应以list of JSON格式填写订单参数** + +名称 | 类型 | 是否必需 | 描述 +---------------- | ------- | -------- | ---- +symbol | STRING | YES | 交易对 +side | ENUM | YES | 买卖方向 `SELL`, `BUY` +positionSide | ENUM | NO | 持仓方向,单向持仓模式下非必填,默认且仅可填`BOTH`;在双向持仓模式下必填,且仅可选择 `LONG` 或 `SHORT` +type | ENUM | YES | 订单类型 `LIMIT`, `MARKET`, `STOP`, `TAKE_PROFIT`, `STOP_MARKET`, `TAKE_PROFIT_MARKET`, `TRAILING_STOP_MARKET` +reduceOnly | STRING | NO | `true`, `false`; 非双开模式下默认`false`;双开模式下不接受此参数。 +quantity | DECIMAL | YES | 下单数量 +price | DECIMAL | NO | 委托价格 +newClientOrderId | STRING | NO | 用户自定义的订单号,不可以重复出现在挂单中。如空缺系统会自动赋值. 必须满足正则规则 `^[\.A-Z\:/a-z0-9_-]{1,36}$` +stopPrice | DECIMAL | NO | 触发价, 仅 `STOP`, `STOP_MARKET`, `TAKE_PROFIT`, `TAKE_PROFIT_MARKET` 需要此参数 +activationPrice | DECIMAL | NO | 追踪止损激活价格,仅`TRAILING_STOP_MARKET` 需要此参数, 默认为下单当前市场价格(支持不同`workingType`) +callbackRate | DECIMAL | NO | 追踪止损回调比例,可取值范围[0.1, 4],其中 1代表1% ,仅`TRAILING_STOP_MARKET` 需要此参数 +timeInForce | ENUM | NO | 有效方法 +workingType | ENUM | NO | stopPrice 触发类型: `MARK_PRICE`(标记价格), `CONTRACT_PRICE`(合约最新价). 默认 `CONTRACT_PRICE` +priceProtect | STRING | NO | 条件单触发保护:"TRUE","FALSE", 默认"FALSE". 仅 `STOP`, `STOP_MARKET`, `TAKE_PROFIT`, `TAKE_PROFIT_MARKET` 需要此参数 +newOrderRespType | ENUM | NO | "ACK", "RESULT", 默认 "ACK" + + +* 具体订单条件规则,与普通下单一致 +* 批量下单采取并发处理,不保证订单撮合顺序 +* 批量下单的返回内容顺序,与订单列表顺序一致 + + + + +## 查询订单 (USER_DATA) + + +> **响应:** + +```javascript +{ + "avgPrice": "0.00000", // 平均成交价 + "clientOrderId": "abc", // 用户自定义的订单号 + "cumQuote": "0", // 成交金额 + "executedQty": "0", // 成交量 + "orderId": 1573346959, // 系统订单号 + "origQty": "0.40", // 原始委托数量 + "origType": "TRAILING_STOP_MARKET", // 触发前订单类型 + "price": "0", // 委托价格 + "reduceOnly": false, // 是否仅减仓 + "side": "BUY", // 买卖方向 + "positionSide": "SHORT", // 持仓方向 + "status": "NEW", // 订单状态 + "stopPrice": "9300", // 触发价,对`TRAILING_STOP_MARKET`无效 + "closePosition": false, // 是否条件全平仓 + "symbol": "BTCUSDT", // 交易对 + "time": 1579276756075, // 订单时间 + "timeInForce": "GTC", // 有效方法 + "type": "TRAILING_STOP_MARKET", // 订单类型 + "activatePrice": "9020", // 跟踪止损激活价格, 仅`TRAILING_STOP_MARKET` 订单返回此字段 + "priceRate": "0.3", // 跟踪止损回调比例, 仅`TRAILING_STOP_MARKET` 订单返回此字段 + "updateTime": 1579276756075, // 更新时间 + "workingType": "CONTRACT_PRICE", // 条件价格触发类型 + "priceProtect": false // 是否开启条件单触发保护 +} +``` + +`` +GET /fapi/v3/order (HMAC SHA256) +`` + +查询订单状态 + +* 请注意,如果订单满足如下条件,不会被查询到: + * 订单的最终状态为 `CANCELED` 或者 `EXPIRED`, **并且** + * 订单没有任何的成交记录, **并且** + * 订单生成时间 + 7天 < 当前时间 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +----------------- | ------ | -------- | ---- +symbol | STRING | YES | 交易对 +orderId | LONG | NO | 系统订单号 +origClientOrderId | STRING | NO | 用户自定义的订单号 +recvWindow | LONG | NO | +timestamp | LONG | YES | + +注意: + +* 至少需要发送 `orderId` 与 `origClientOrderId`中的一个 + + +## 撤销订单 (TRADE) + +> **响应:** + +```javascript +{ + "clientOrderId": "myOrder1", // 用户自定义的订单号 + "cumQty": "0", + "cumQuote": "0", // 成交金额 + "executedQty": "0", // 成交量 + "orderId": 283194212, // 系统订单号 + "origQty": "11", // 原始委托数量 + "price": "0", // 委托价格 + "reduceOnly": false, // 仅减仓 + "side": "BUY", // 买卖方向 + "positionSide": "SHORT", // 持仓方向 + "status": "CANCELED", // 订单状态 + "stopPrice": "9300", // 触发价,对`TRAILING_STOP_MARKET`无效 + "closePosition": false, // 是否条件全平仓 + "symbol": "BTCUSDT", // 交易对 + "timeInForce": "GTC", // 有效方法 + "origType": "TRAILING_STOP_MARKET", // 触发前订单类型 + "type": "TRAILING_STOP_MARKET", // 订单类型 + "activatePrice": "9020", // 跟踪止损激活价格, 仅`TRAILING_STOP_MARKET` 订单返回此字段 + "priceRate": "0.3", // 跟踪止损回调比例, 仅`TRAILING_STOP_MARKET` 订单返回此字段 + "updateTime": 1571110484038, // 更新时间 + "workingType": "CONTRACT_PRICE", // 条件价格触发类型 + "priceProtect": false // 是否开启条件单触发保护 +} +``` + +`` +DELETE /fapi/v3/order (HMAC SHA256) +`` + +**权重:** +1 + +**Parameters:** + +名称 | 类型 | 是否必需 | 描述 +----------------- | ------ | -------- | ------------------ +symbol | STRING | YES | 交易对 +orderId | LONG | NO | 系统订单号 +origClientOrderId | STRING | NO | 用户自定义的订单号 +recvWindow | LONG | NO | +timestamp | LONG | YES | + +`orderId` 与 `origClientOrderId` 必须至少发送一个 + + +## 撤销全部订单 (TRADE) + +> **响应:** + +```javascript +{ + "code": "200", + "msg": "The operation of cancel all open order is done." +} +``` + +`` +DELETE /fapi/v3/allOpenOrders (HMAC SHA256) +`` + +**权重:** +1 + +**Parameters:** + + 名称 | 类型 | 是否必需 | 描述 +---------- | ------ | -------- | ------ +symbol | STRING | YES | 交易对 +recvWindow | LONG | NO | +timestamp | LONG | YES | + + +## 批量撤销订单 (TRADE) + +> **响应:** + +```javascript +[ + { + "clientOrderId": "myOrder1", // 用户自定义的订单号 + "cumQty": "0", + "cumQuote": "0", // 成交金额 + "executedQty": "0", // 成交量 + "orderId": 283194212, // 系统订单号 + "origQty": "11", // 原始委托数量 + "price": "0", // 委托价格 + "reduceOnly": false, // 仅减仓 + "side": "BUY", // 买卖方向 + "positionSide": "SHORT", // 持仓方向 + "status": "CANCELED", // 订单状态 + "stopPrice": "9300", // 触发价,对`TRAILING_STOP_MARKET`无效 + "closePosition": false, // 是否条件全平仓 + "symbol": "BTCUSDT", // 交易对 + "timeInForce": "GTC", // 有效方法 + "origType": "TRAILING_STOP_MARKET", // 触发前订单类型 + "type": "TRAILING_STOP_MARKET", // 订单类型 + "activatePrice": "9020", // 跟踪止损激活价格, 仅`TRAILING_STOP_MARKET` 订单返回此字段 + "priceRate": "0.3", // 跟踪止损回调比例, 仅`TRAILING_STOP_MARKET` 订单返回此字段 + "updateTime": 1571110484038, // 更新时间 + "workingType": "CONTRACT_PRICE", // 条件价格触发类型 + "priceProtect": false // 是否开启条件单触发保护 + }, + { + "code": -2011, + "msg": "Unknown order sent." + } +] +``` + +`` +DELETE /fapi/v3/batchOrders (HMAC SHA256) +`` + +**权重:** +1 + +**Parameters:** + + 名称 | 类型 | 是否必需 | 描述 +--------------------- | -------------- | -------- | ---------------- +symbol | STRING | YES | 交易对 +orderIdList | LIST\ | NO | 系统订单号, 最多支持10个订单
比如`[1234567,2345678]` +origClientOrderIdList | LIST\ | NO | 用户自定义的订单号, 最多支持10个订单
比如`["my_id_1","my_id_2"]` 需要encode双引号。逗号后面没有空格。 +recvWindow | LONG | NO | +timestamp | LONG | YES | + +`orderIdList` 与 `origClientOrderIdList` 必须至少发送一个,不可同时发送 + + +## 倒计时撤销所有订单 (TRADE) + +> **响应:** + +```javascript +{ + "symbol": "BTCUSDT", + "countdownTime": "100000" +} +``` + + +`` +POST /fapi/v3/countdownCancelAll (HMAC SHA256) +`` + +**权重:** +10 + +**Parameters:** + + 名称 | 类型 | 是否必需 | 描述 +--------------------- | -------------- | -------- | ---------------- +symbol | STRING | YES | +countdownTime | LONG | YES | 倒计时。 1000 表示 1 秒; 0 表示取消倒计时撤单功能。 +recvWindow | LONG | NO | +timestamp | LONG | YES | + +* 该接口可以被用于确保在倒计时结束时撤销指定symbol上的所有挂单。 在使用这个功能时,接口应像心跳一样在倒计时内被反复调用,以便可以取消既有的倒计时并开始新的倒数计时设置。 + +* 用法示例: + 以30s的间隔重复此接口,每次倒计时countdownTime设置为120000(120s)。 + 如果在120秒内未再次调用此接口,则您指定symbol上的所有挂单都会被自动撤销。 + 如果在120秒内以将countdownTime设置为0,则倒数计时器将终止,自动撤单功能取消。 + +* 系统会**大约每10毫秒**检查一次所有倒计时情况,因此请注意,使用此功能时应考虑足够的冗余。 +我们不建议将倒记时设置得太精确或太小。 + + + + + +## 查询当前挂单 (USER_DATA) + +> **响应:** + +```javascript + +{ + "avgPrice": "0.00000", // 平均成交价 + "clientOrderId": "abc", // 用户自定义的订单号 + "cumQuote": "0", // 成交金额 + "executedQty": "0", // 成交量 + "orderId": 1917641, // 系统订单号 + "origQty": "0.40", // 原始委托数量 + "origType": "TRAILING_STOP_MARKET", // 触发前订单类型 + "price": "0", // 委托价格 + "reduceOnly": false, // 是否仅减仓 + "side": "BUY", // 买卖方向 + "status": "NEW", // 订单状态 + "positionSide": "SHORT", // 持仓方向 + "stopPrice": "9300", // 触发价,对`TRAILING_STOP_MARKET`无效 + "closePosition": false, // 是否条件全平仓 + "symbol": "BTCUSDT", // 交易对 + "time": 1579276756075, // 订单时间 + "timeInForce": "GTC", // 有效方法 + "type": "TRAILING_STOP_MARKET", // 订单类型 + "activatePrice": "9020", // 跟踪止损激活价格, 仅`TRAILING_STOP_MARKET` 订单返回此字段 + "priceRate": "0.3", // 跟踪止损回调比例, 仅`TRAILING_STOP_MARKET` 订单返回此字段 + "updateTime": 1579276756075, // 更新时间 + "workingType": "CONTRACT_PRICE", // 条件价格触发类型 + "priceProtect": false // 是否开启条件单触发保护 +} +``` + +`` +GET /fapi/v3/openOrder (HMAC SHA256) +`` + +请小心使用不带symbol参数的调用 + +**权重: 1** + + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +---------- | ------ | -------- | ------ +symbol | STRING | YES | 交易对 +orderId | LONG | NO | 系统订单号 +origClientOrderId | STRING | NO | 用户自定义的订单号 +recvWindow | LONG | NO | +timestamp | LONG | YES | + +* `orderId` 与 `origClientOrderId` 中的一个为必填参数 +* 查询的订单如果已经成交或取消,将返回报错 "Order does not exist." + + +## 查看当前全部挂单 (USER_DATA) + +> **响应:** + +```javascript +[ + { + "avgPrice": "0.00000", // 平均成交价 + "clientOrderId": "abc", // 用户自定义的订单号 + "cumQuote": "0", // 成交金额 + "executedQty": "0", // 成交量 + "orderId": 1917641, // 系统订单号 + "origQty": "0.40", // 原始委托数量 + "origType": "TRAILING_STOP_MARKET", // 触发前订单类型 + "price": "0", // 委托价格 + "reduceOnly": false, // 是否仅减仓 + "side": "BUY", // 买卖方向 + "positionSide": "SHORT", // 持仓方向 + "status": "NEW", // 订单状态 + "stopPrice": "9300", // 触发价,对`TRAILING_STOP_MARKET`无效 + "closePosition": false, // 是否条件全平仓 + "symbol": "BTCUSDT", // 交易对 + "time": 1579276756075, // 订单时间 + "timeInForce": "GTC", // 有效方法 + "type": "TRAILING_STOP_MARKET", // 订单类型 + "activatePrice": "9020", // 跟踪止损激活价格, 仅`TRAILING_STOP_MARKET` 订单返回此字段 + "priceRate": "0.3", // 跟踪止损回调比例, 仅`TRAILING_STOP_MARKET` 订单返回此字段 + "updateTime": 1579276756075, // 更新时间 + "workingType": "CONTRACT_PRICE", // 条件价格触发类型 + "priceProtect": false // 是否开启条件单触发保护 + } +] +``` + +`` +GET /fapi/v3/openOrders (HMAC SHA256) +`` + +请小心使用不带symbol参数的调用 + +**权重:** +- 带symbol ***1*** +- 不带 ***40*** + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +---------- | ------ | -------- | ------ +symbol | STRING | NO | 交易对 +recvWindow | LONG | NO | +timestamp | LONG | YES | + +* 不带symbol参数,会返回所有交易对的挂单 + + + +## 查询所有订单(包括历史订单) (USER_DATA) + + +> **响应:** + +```javascript +[ + { + "avgPrice": "0.00000", // 平均成交价 + "clientOrderId": "abc", // 用户自定义的订单号 + "cumQuote": "0", // 成交金额 + "executedQty": "0", // 成交量 + "orderId": 1917641, // 系统订单号 + "origQty": "0.40", // 原始委托数量 + "origType": "TRAILING_STOP_MARKET", // 触发前订单类型 + "price": "0", // 委托价格 + "reduceOnly": false, // 是否仅减仓 + "side": "BUY", // 买卖方向 + "positionSide": "SHORT", // 持仓方向 + "status": "NEW", // 订单状态 + "stopPrice": "9300", // 触发价,对`TRAILING_STOP_MARKET`无效 + "closePosition": false, // 是否条件全平仓 + "symbol": "BTCUSDT", // 交易对 + "time": 1579276756075, // 订单时间 + "timeInForce": "GTC", // 有效方法 + "type": "TRAILING_STOP_MARKET", // 订单类型 + "activatePrice": "9020", // 跟踪止损激活价格, 仅`TRAILING_STOP_MARKET` 订单返回此字段 + "priceRate": "0.3", // 跟踪止损回调比例, 仅`TRAILING_STOP_MARKET` 订单返回此字段 + "updateTime": 1579276756075, // 更新时间 + "workingType": "CONTRACT_PRICE", // 条件价格触发类型 + "priceProtect": false // 是否开启条件单触发保护 + } +] +``` + +`` +GET /fapi/v3/allOrders (HMAC SHA256) +`` + +* 请注意,如果订单满足如下条件,不会被查询到: + * 订单的最终状态为 `CANCELED` 或者 `EXPIRED`, **并且** + * 订单没有任何的成交记录, **并且** + * 订单生成时间 + 7天 < 当前时间 + +**权重:** +5 + +**Parameters:** + + 名称 | 类型 | 是否必需 | 描述 +---------- | ------ | -------- | ----------------------------------------------- +symbol | STRING | YES | 交易对 +orderId | LONG | NO | 只返回此orderID及之后的订单,缺省返回最近的订单 +startTime | LONG | NO | 起始时间 +endTime | LONG | NO | 结束时间 +limit | INT | NO | 返回的结果集数量 默认值:500 最大值:1000 +recvWindow | LONG | NO | +timestamp | LONG | YES | + +* 查询时间范围最大不得超过7天 +* 默认查询最近7天内的数据 + + + +## 账户余额v3 (USER_DATA) + +> **响应:** + +```javascript +[ + { + "accountAlias": "SgsR", // 账户唯一识别码 + "asset": "USDT", // 资产 + "balance": "122607.35137903", // 总余额 + "crossWalletBalance": "23.72469206", // 全仓余额 + "crossUnPnl": "0.00000000" // 全仓持仓未实现盈亏 + "availableBalance": "23.72469206", // 下单可用余额 + "maxWithdrawAmount": "23.72469206", // 最大可转出余额 + "marginAvailable": true, // 是否可用作联合保证金 + "updateTime": 1617939110373 + } +] +``` + +`` +GET /fapi/v3/balance (HMAC SHA256) +`` + +**Weight:** +5 + +**Parameters:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +recvWindow | LONG | NO | +timestamp | LONG | YES + + + + +## 账户信息v3 (USER_DATA) + +> **响应:** + +```javascript + +{ + "feeTier": 0, // 手续费等级 + "canTrade": true, // 是否可以交易 + "canDeposit": true, // 是否可以入金 + "canWithdraw": true, // 是否可以出金 + "updateTime": 0, + "totalInitialMargin": "0.00000000", // 但前所需起始保证金总额(存在逐仓请忽略), 仅计算usdt资产 + "totalMaintMargin": "0.00000000", // 维持保证金总额, 仅计算usdt资产 + "totalWalletBalance": "23.72469206", // 账户总余额, 仅计算usdt资产 + "totalUnrealizedProfit": "0.00000000", // 持仓未实现盈亏总额, 仅计算usdt资产 + "totalMarginBalance": "23.72469206", // 保证金总余额, 仅计算usdt资产 + "totalPositionInitialMargin": "0.00000000", // 持仓所需起始保证金(基于最新标记价格), 仅计算usdt资产 + "totalOpenOrderInitialMargin": "0.00000000", // 当前挂单所需起始保证金(基于最新标记价格), 仅计算usdt资产 + "totalCrossWalletBalance": "23.72469206", // 全仓账户余额, 仅计算usdt资产 + "totalCrossUnPnl": "0.00000000", // 全仓持仓未实现盈亏总额, 仅计算usdt资产 + "availableBalance": "23.72469206", // 可用余额, 仅计算usdt资产 + "maxWithdrawAmount": "23.72469206" // 最大可转出余额, 仅计算usdt资产 + "assets": [ + { + "asset": "USDT", //资产 + "walletBalance": "23.72469206", //余额 + "unrealizedProfit": "0.00000000", // 未实现盈亏 + "marginBalance": "23.72469206", // 保证金余额 + "maintMargin": "0.00000000", // 维持保证金 + "initialMargin": "0.00000000", // 当前所需起始保证金 + "positionInitialMargin": "0.00000000", // 持仓所需起始保证金(基于最新标记价格) + "openOrderInitialMargin": "0.00000000", // 当前挂单所需起始保证金(基于最新标记价格) + "crossWalletBalance": "23.72469206", //全仓账户余额 + "crossUnPnl": "0.00000000" // 全仓持仓未实现盈亏 + "availableBalance": "23.72469206", // 可用余额 + "maxWithdrawAmount": "23.72469206", // 最大可转出余额 + "marginAvailable": true, // 是否可用作联合保证金 + "updateTime": 1625474304765 //更新时间 + }, + { + "asset": "BUSD", //资产 + "walletBalance": "103.12345678", //余额 + "unrealizedProfit": "0.00000000", // 未实现盈亏 + "marginBalance": "103.12345678", // 保证金余额 + "maintMargin": "0.00000000", // 维持保证金 + "initialMargin": "0.00000000", // 当前所需起始保证金 + "positionInitialMargin": "0.00000000", // 持仓所需起始保证金(基于最新标记价格) + "openOrderInitialMargin": "0.00000000", // 当前挂单所需起始保证金(基于最新标记价格) + "crossWalletBalance": "103.12345678", //全仓账户余额 + "crossUnPnl": "0.00000000" // 全仓持仓未实现盈亏 + "availableBalance": "103.12345678", // 可用余额 + "maxWithdrawAmount": "103.12345678", // 最大可转出余额 + "marginAvailable": true, // 否可用作联合保证金 + "updateTime": 0 // 更新时间 + } + ], + "positions": [ // 头寸,将返回所有市场symbol。 + //根据用户持仓模式展示持仓方向,即单向模式下只返回BOTH持仓情况,双向模式下只返回 LONG 和 SHORT 持仓情况 + { + "symbol": "BTCUSDT", // 交易对 + "initialMargin": "0", // 当前所需起始保证金(基于最新标记价格) + "maintMargin": "0", //维持保证金 + "unrealizedProfit": "0.00000000", // 持仓未实现盈亏 + "positionInitialMargin": "0", // 持仓所需起始保证金(基于最新标记价格) + "openOrderInitialMargin": "0", // 当前挂单所需起始保证金(基于最新标记价格) + "leverage": "100", // 杠杆倍率 + "isolated": true, // 是否是逐仓模式 + "entryPrice": "0.00000", // 持仓成本价 + "maxNotional": "250000", // 当前杠杆下用户可用的最大名义价值 + "positionSide": "BOTH", // 持仓方向 + "positionAmt": "0", // 持仓数量 + "updateTime": 0 // 更新时间 + } + ] +} +``` + + +`` +GET /fapi/v3/account (HMAC SHA256) +`` + +**权重:** +5 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +recvWindow | LONG | NO | +timestamp | LONG | YES | + + + + +## 调整开仓杠杆 (TRADE) + +> **响应:** + +```javascript +{ + "leverage": 21, // 杠杆倍数 + "maxNotionalValue": "1000000", // 当前杠杆倍数下允许的最大名义价值 + "symbol": "BTCUSDT" // 交易对 +} +``` + +`` +POST /fapi/v3/leverage (HMAC SHA256) +`` + +调整用户在指定symbol合约的开仓杠杆。 + +**权重:** +1 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +---------- | ------ | -------- | --------------------------- +symbol | STRING | YES | 交易对 +leverage | INT | YES | 目标杠杆倍数:1 到 125 整数 +recvWindow | LONG | NO | +timestamp | LONG | YES | + + +## 变换逐全仓模式 (TRADE) + +> **响应:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +`` +POST /fapi/v3/marginType (HMAC SHA256) +`` + +变换用户在指定symbol合约上的保证金模式:逐仓或全仓。 + +**权重:** +1 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +---------- | ------ | -------- | ----------------- +symbol | STRING | YES | 交易对 +marginType | ENUM | YES | 保证金模式 ISOLATED(逐仓), CROSSED(全仓) +recvWindow | LONG | NO | +timestamp | LONG | YES | + + +## 调整逐仓保证金 (TRADE) + +> **响应:** + +```javascript +{ + "amount": 100.0, + "code": 200, + "msg": "Successfully modify position margin.", + "type": 1 +} +``` + +`` +POST /fapi/v3/positionMargin (HMAC SHA256) +`` + +针对逐仓模式下的仓位,调整其逐仓保证金资金。 + +**权重:** +1 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +---------- | ------- | -------- | ------------------------------------ +symbol | STRING | YES | 交易对 +positionSide| ENUM | NO | 持仓方向,单向持仓模式下非必填,默认且仅可填`BOTH`;在双向持仓模式下必填,且仅可选择 `LONG` 或 `SHORT` +amount | DECIMAL | YES | 保证金资金 +type | INT | YES | 调整方向 1: 增加逐仓保证金,2: 减少逐仓保证金 +recvWindow | LONG | NO | +timestamp | LONG | YES | + +* 只针对逐仓symbol 与 positionSide(如有) + + +## 逐仓保证金变动历史 (TRADE) + +> **响应:** + +```javascript +[ + { + "amount": "23.36332311", // 数量 + "asset": "USDT", // 资产 + "symbol": "BTCUSDT", // 交易对 + "time": 1578047897183, // 时间 + "type": 1, // 调整方向 + "positionSide": "BOTH" // 持仓方向 + }, + { + "amount": "100", + "asset": "USDT", + "symbol": "BTCUSDT", + "time": 1578047900425, + "type": 1, + "positionSide": "LONG" + } +] +``` + +`` +GET /fapi/v3/positionMargin/history (HMAC SHA256) +`` + + + +**权重:** +1 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +---------- | ------ | -------- | ------------------------------------ +symbol | STRING | YES | 交易对 +type | INT | NO | 调整方向 1: 增加逐仓保证金,2: 减少逐仓保证金 +startTime | LONG | NO | 起始时间 +endTime | LONG | NO | 结束时间 +limit | INT | NO | 返回的结果集数量 默认值: 500 +recvWindow | LONG | NO | +timestamp | LONG | YES | + + + + +## 用户持仓风险v3 (USER_DATA) + +> **响应:** + +> 单向持仓模式下: + +```javascript +[ + { + "entryPrice": "0.00000", // 开仓均价 + "marginType": "isolated", // 逐仓模式或全仓模式 + "isAutoAddMargin": "false", + "isolatedMargin": "0.00000000", // 逐仓保证金 + "leverage": "10", // 当前杠杆倍数 + "liquidationPrice": "0", // 参考强平价格 + "markPrice": "6679.50671178", // 当前标记价格 + "maxNotionalValue": "20000000", // 当前杠杆倍数允许的名义价值上限 + "positionAmt": "0.000", // 头寸数量,符号代表多空方向, 正数为多,负数为空 + "symbol": "BTCUSDT", // 交易对 + "unRealizedProfit": "0.00000000", // 持仓未实现盈亏 + "positionSide": "BOTH", // 持仓方向 + "updateTime": 1625474304765 // 更新时间 + } +] +``` + +> 双向持仓模式下: + +```javascript +[ + { + "entryPrice": "6563.66500", // 开仓均价 + "marginType": "isolated", // 逐仓模式或全仓模式 + "isAutoAddMargin": "false", + "isolatedMargin": "15517.54150468", // 逐仓保证金 + "leverage": "10", // 当前杠杆倍数 + "liquidationPrice": "5930.78", // 参考强平价格 + "markPrice": "6679.50671178", // 当前标记价格 + "maxNotionalValue": "20000000", // 当前杠杆倍数允许的名义价值上限 + "positionAmt": "20.000", // 头寸数量,符号代表多空方向, 正数为多,负数为空 + "symbol": "BTCUSDT", // 交易对 + "unRealizedProfit": "2316.83423560" // 持仓未实现盈亏 + "positionSide": "LONG", // 持仓方向 + "updateTime": 1625474304765 // 更新时间 + }, + { + "entryPrice": "0.00000", // 开仓均价 + "marginType": "isolated", // 逐仓模式或全仓模式 + "isAutoAddMargin": "false", + "isolatedMargin": "5413.95799991", // 逐仓保证金 + "leverage": "10", // 当前杠杆倍数 + "liquidationPrice": "7189.95", // 参考强平价格 + "markPrice": "6679.50671178", // 当前标记价格 + "maxNotionalValue": "20000000", // 当前杠杆倍数允许的名义价值上限 + "positionAmt": "-10.000", // 头寸数量,符号代表多空方向, 正数为多,负数为空 + "symbol": "BTCUSDT", // 交易对 + "unRealizedProfit": "-1156.46711780" // 持仓未实现盈亏 + "positionSide": "SHORT", // 持仓方向 + "updateTime": 1625474304765 //更新时间 + } +] +``` + +`` +GET /fapi/v3/positionRisk (HMAC SHA256) +`` + +**权重:** +5 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +---------- | ---- | -------- | ---- +symbol | STRING | NO | +recvWindow | LONG | NO | +timestamp | LONG | YES | + + +**注意** +请与账户推送信息`ACCOUNT_UPDATE`配合使用,以满足您的及时性和准确性需求。 + + + + +## 账户成交历史 (USER_DATA) + + +> **响应:** + +```javascript +[ + { + "buyer": false, // 是否是买方 + "commission": "-0.07819010", // 手续费 + "commissionAsset": "USDT", // 手续费计价单位 + "id": 698759, // 交易ID + "maker": false, // 是否是挂单方 + "orderId": 25851813, // 订单编号 + "price": "7819.01", // 成交价 + "qty": "0.002", // 成交量 + "quoteQty": "15.63802", // 成交额 + "realizedPnl": "-0.91539999", // 实现盈亏 + "side": "SELL", // 买卖方向 + "positionSide": "SHORT", // 持仓方向 + "symbol": "BTCUSDT", // 交易对 + "time": 1569514978020 // 时间 + } +] +``` + +`` +GET /fapi/v3/userTrades (HMAC SHA256) +`` + +获取某交易对的成交历史 + +**权重:** +5 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +---------- | ------ | -------- | -------------------------------------------- +symbol | STRING | YES | 交易对 +startTime | LONG | NO | 起始时间 +endTime | LONG | NO | 结束时间 +fromId | LONG | NO | 返回该fromId及之后的成交,缺省返回最近的成交 +limit | INT | NO | 返回的结果集数量 默认值:500 最大值:1000. +recvWindow | LONG | NO | +timestamp | LONG | YES | + +* 如果`startTime` 和 `endTime` 均未发送, 只会返回最近7天的数据。 +* startTime 和 endTime 的最大间隔为7天 + + +## 获取账户损益资金流水(USER_DATA) + +> **响应:** + +```javascript +[ + { + "symbol": "", // 交易对,仅针对涉及交易对的资金流 + "incomeType": "TRANSFER", // 资金流类型 + "income": "-0.37500000", // 资金流数量,正数代表流入,负数代表流出 + "asset": "USDT", // 资产内容 + "info":"TRANSFER", // 备注信息,取决于流水类型 + "time": 1570608000000, // 时间 + "tranId":"9689322392", // 划转ID + "tradeId":"" // 引起流水产生的原始交易ID + }, + { + "symbol": "BTCUSDT", + "incomeType": "COMMISSION", + "income": "-0.01000000", + "asset": "USDT", + "info":"COMMISSION", + "time": 1570636800000, + "tranId":"9689322392", + "tradeId":"2059192" + } +] +``` + +`` +GET /fapi/v3/income (HMAC SHA256) +`` + +**权重:** +30 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +---------- | ------ | -------- | ----------------------------------------------------------------------------------------------- +symbol | STRING | NO | 交易对 +incomeType | STRING | NO | 收益类型 "TRANSFER","WELCOME_BONUS", "REALIZED_PNL","FUNDING_FEE", "COMMISSION", "INSURANCE_CLEAR", and "MARKET_MERCHANT_RETURN_REWARD" +startTime | LONG | NO | 起始时间 +endTime | LONG | NO | 结束时间 +limit | INT | NO | 返回的结果集数量 默认值:100 最大值:1000 +recvWindow | LONG | NO | +timestamp | LONG | YES | + +* 如果`startTime` 和 `endTime` 均未发送, 只会返回最近7天的数据。 +* 如果`incomeType`没有发送,返回所有类型账户损益资金流水。 +* "trandId" 在相同用户的同一种收益流水类型中是唯一的。 + + +## 杠杆分层标准 (USER_DATA) + + +> **响应:** + +```javascript +[ + { + "symbol": "ETHUSDT", + "brackets": [ + { + "bracket": 1, // 层级 + "initialLeverage": 75, // 该层允许的最高初始杠杆倍数 + "notionalCap": 10000, // 该层对应的名义价值上限 + "notionalFloor": 0, // 该层对应的名义价值下限 + "maintMarginRatio": 0.0065, // 该层对应的维持保证金率 + "cum":0 // 速算数 + }, + ] + } +] +``` + +> **或** (若发送symbol) + +```javascript + +{ + "symbol": "ETHUSDT", + "brackets": [ + { + "bracket": 1, + "initialLeverage": 75, + "notionalCap": 10000, + "notionalFloor": 0, + "maintMarginRatio": 0.0065, + "cum":0 + }, + ] +} +``` + + +`` +GET /fapi/v3/leverageBracket +`` + + +**权重:** 1 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +------ | ------ | -------- | ------ +symbol | STRING | NO +recvWindow | LONG | NO | +timestamp | LONG | YES | + + + +## 持仓ADL队列估算 (USER_DATA) + + +> **响应:** + +```javascript +[ + { + "symbol": "ETHUSDT", + "adlQuantile": + { + // 对于全仓状态下的双向持仓模式的交易对,会返回 "LONG", "SHORT" 和 "HEDGE", 其中"HEDGE"的存在仅作为标记;如果多空均有持仓的情况下,"LONG"和"SHORT"应返回共同计算后相同的队列分数。 + "LONG": 3, + "SHORT": 3, + "HEDGE": 0 // HEDGE 仅作为指示出现,请忽略数值 + } + }, + { + "symbol": "BTCUSDT", + "adlQuantile": + { + // 对于单向持仓模式或者是逐仓状态下的双向持仓模式的交易对,会返回 "LONG", "SHORT" 和 "BOTH" 分别表示不同持仓方向上持仓的adl队列分数 + "LONG": 1, // 双开模式下多头持仓的ADL队列估算分 + "SHORT": 2, // 双开模式下空头持仓的ADL队列估算分 + "BOTH": 0 // 单开模式下持仓的ADL队列估算分 + } + } + ] +``` + +`` +GET /fapi/v3/adlQuantile +`` + + +**权重:** 5 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +------ | ------ | -------- | ------ +symbol | STRING | NO +recvWindow|LONG|NO| +timestamp|LONG|YES| + +* 每30秒更新数据 + +* 队列分数0,1,2,3,4,分数越高说明在ADL队列中的位置越靠前 + +* 对于单向持仓模式或者是逐仓状态下的双向持仓模式的交易对,会返回 "LONG", "SHORT" 和 "BOTH" 分别表示不同持仓方向上持仓的adl队列分数 + +* 对于全仓状态下的双向持仓模式的交易对,会返回 "LONG", "SHORT" 和 "HEDGE", 其中"HEDGE"的存在仅作为标记;其中如果多空均有持仓的情况下,"LONG"和"SHORT"返回共同计算后相同的队列分数。 + + +## 用户强平单历史 (USER_DATA) + + +> **响应:** + +```javascript +[ + { + "orderId": 6071832819, + "symbol": "BTCUSDT", + "status": "FILLED", + "clientOrderId": "autoclose-1596107620040000020", + "price": "10871.09", + "avgPrice": "10913.21000", + "origQty": "0.001", + "executedQty": "0.001", + "cumQuote": "10.91321", + "timeInForce": "IOC", + "type": "LIMIT", + "reduceOnly": false, + "closePosition": false, + "side": "SELL", + "positionSide": "BOTH", + "stopPrice": "0", + "workingType": "CONTRACT_PRICE", + "origType": "LIMIT", + "time": 1596107620044, + "updateTime": 1596107620087 + } + { + "orderId": 6072734303, + "symbol": "BTCUSDT", + "status": "FILLED", + "clientOrderId": "adl_autoclose", + "price": "11023.14", + "avgPrice": "10979.82000", + "origQty": "0.001", + "executedQty": "0.001", + "cumQuote": "10.97982", + "timeInForce": "GTC", + "type": "LIMIT", + "reduceOnly": false, + "closePosition": false, + "side": "BUY", + "positionSide": "SHORT", + "stopPrice": "0", + "workingType": "CONTRACT_PRICE", + "origType": "LIMIT", + "time": 1596110725059, + "updateTime": 1596110725071 + } +] +``` + + +`` +GET /fapi/v3/forceOrders +`` + + +**权重:** 带symbol 20, 不带symbol 50 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +------------- | ------ | -------- | ---------------------------------------- +symbol | STRING | NO | +autoCloseType | ENUM | NO | "LIQUIDATION": 强平单, "ADL": ADL减仓单. +startTime | LONG | NO | +endTime | LONG | NO | +limit | INT | NO | Default 50; max 100. +recvWindow | LONG | NO | +timestamp | LONG | YES | + +* 如果没有传 "autoCloseType", 强平单和ADL减仓单都会被返回 +* 如果没有传"startTime", 只会返回"endTime"之前7天内的数据 + + + +## 用户手续费率 (USER_DATA) + +> **响应:** + +```javascript +{ + "symbol": "BTCUSDT", + "makerCommissionRate": "0.0002", // 0.02% + "takerCommissionRate": "0.0004" // 0.04% +} +``` + +`` +GET /fapi/v3/commissionRate (HMAC SHA256) +`` + +**权重:** +20 + + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES +recvWindow | LONG | NO +timestamp | LONG | YES + + + + + + +# Websocket 账户信息推送 + + +* 本篇所列出REST接口的baseurl **https://fapi.asterdex.com** +* 用于订阅账户数据的 `listenKey` 从创建时刻起有效期为60分钟 +* 可以通过`PUT`一个`listenKey`延长60分钟有效期 +* 可以通过`DELETE`一个 `listenKey` 立即关闭当前数据流,并使该`listenKey` 无效 +* 在具有有效`listenKey`的帐户上执行`POST`将返回当前有效的`listenKey`并将其有效期延长60分钟 +* 本篇所列出的websocket接口baseurl: **wss://fstream.asterdex.com** +* 订阅账户数据流的stream名称为 **/ws/\** +* 每个链接有效期不超过24小时,请妥善处理断线重连。 +* 账户数据流的消息**不保证**严格时间序; **请使用 E 字段进行排序** +* 考虑到剧烈行情下, RESTful接口可能存在查询延迟,我们强烈建议您优先从Websocket user data stream推送的消息来获取订单,仓位等信息。 + + +## 生成listenKey (USER_STREAM) + + +> **响应:** + +```javascript +{ + "listenKey": "pqia91ma19a5s61cv6a81va65sdf19v8a65a1a5s61cv6a81va65sdf19v8a65a1" +} +``` + +`` +POST /fapi/v3/listenKey +`` + +创建一个新的user data stream,返回值为一个listenKey,即websocket订阅的stream名称。如果该帐户具有有效的`listenKey`,则将返回该`listenKey`并将其有效期延长60分钟。 + +**权重:** +1 + +**参数:** + +None + + +## 延长listenKey有效期 (USER_STREAM) + + +> **响应:** + +```javascript +{} +``` + +`` +PUT /fapi/v3/listenKey +`` + +有效期延长至本次调用后60分钟 + +**权重:** +1 + +**参数:** + +None + + + +## 关闭listenKey (USER_STREAM) + +> **响应:** + +```javascript +{} +``` + +`` +DELETE /fapi/v3/listenKey +`` + +关闭某账户数据流 + +**权重:** +1 + +**参数:** + +None + + + +## listenKey 过期推送 + +> **Payload:** + +```javascript +{ + 'e': 'listenKeyExpired', // 事件类型 + 'E': 1576653824250 // 事件时间 +} +``` + +当前连接使用的有效listenKey过期时,user data stream 将会推送此事件。 + +**注意:** + +* 此事件与websocket连接中断没有必然联系 +* 只有正在连接中的有效`listenKey`过期时才会收到此消息 +* 收到此消息后user data stream将不再更新,直到用户使用新的有效的`listenKey` + + + + +## 追加保证金通知 + +> **Payload:** + +```javascript +{ + "e":"MARGIN_CALL", // 事件类型 + "E":1587727187525, // 事件时间 + "cw":"3.16812045", // 除去逐仓仓位保证金的钱包余额, 仅在全仓 margin call 情况下推送此字段 + "p":[ // 涉及持仓 + { + "s":"ETHUSDT", // symbol + "ps":"LONG", // 持仓方向 + "pa":"1.327", // 仓位 + "mt":"CROSSED", // 保证金模式 + "iw":"0", // 若为逐仓,仓位保证金 + "mp":"187.17127", // 标记价格 + "up":"-1.166074", // 未实现盈亏 + "mm":"1.614445" // 持仓需要的维持保证金 + } + ] +} + +``` + + +* 当用户持仓风险过高,会推送此消息。 +* 此消息仅作为风险指导信息,不建议用于投资策略。 +* 在大波动市场行情下,不排除此消息发出的同时用户仓位已被强平的可能。 + + + + +## Balance和Position更新推送 + +> **Payload:** + +```javascript +{ + "e": "ACCOUNT_UPDATE", // 事件类型 + "E": 1564745798939, // 事件时间 + "T": 1564745798938 , // 撮合时间 + "a": // 账户更新事件 + { + "m":"ORDER", // 事件推出原因 + "B":[ // 余额信息 + { + "a":"USDT", // 资产名称 + "wb":"122624.12345678", // 钱包余额 + "cw":"100.12345678", // 除去逐仓仓位保证金的钱包余额 + "bc":"50.12345678" // 除去盈亏与交易手续费以外的钱包余额改变量 + }, + { + "a":"BUSD", + "wb":"1.00000000", + "cw":"0.00000000", + "bc":"-49.12345678" + } + ], + "P":[ + { + "s":"BTCUSDT", // 交易对 + "pa":"0", // 仓位 + "ep":"0.00000", // 入仓价格 + "cr":"200", // (费前)累计实现损益 + "up":"0", // 持仓未实现盈亏 + "mt":"isolated", // 保证金模式 + "iw":"0.00000000", // 若为逐仓,仓位保证金 + "ps":"BOTH" // 持仓方向 + }, + { + "s":"BTCUSDT", + "pa":"20", + "ep":"6563.66500", + "cr":"0", + "up":"2850.21200", + "mt":"isolated", + "iw":"13200.70726908", + "ps":"LONG" + }, + { + "s":"BTCUSDT", + "pa":"-10", + "ep":"6563.86000", + "cr":"-45.04000000", + "up":"-1423.15600", + "mt":"isolated", + "iw":"6570.42511771", + "ps":"SHORT" + } + ] + } +} +``` + +账户更新事件的 event type 固定为 `ACCOUNT_UPDATE` + +* 当账户信息有变动时,会推送此事件: + * 仅当账户信息有变动时(包括资金、仓位、保证金模式等发生变化),才会推送此事件; + * 订单状态变化没有引起账户和持仓变化的,不会推送此事件; + * 每次因持仓变动推送的position 信息,仅包含当前持仓不为0或逐仓仓位保证金不为0的symbol position。 + +* "FUNDING FEE" 引起的资金余额变化,仅推送简略事件: + * 当用户某**全仓**持仓发生"FUNDING FEE"时,事件`ACCOUNT_UPDATE`将只会推送相关的用户资产余额信息`B`(仅推送FUNDING FEE 发生相关的资产余额信息),而不会推送任何持仓信息`P`。 + * 当用户某**逐仓**仓持仓发生"FUNDING FEE"时,事件`ACCOUNT_UPDATE`将只会推送相关的用户资产余额信息`B`(仅推送"FUNDING FEE"所使用的资产余额信息),和相关的持仓信息`P`(仅推送这笔"FUNDING FEE"发生所在的持仓信息),其余持仓信息不会被推送。 + +* 字段"m"代表了事件推出的原因,包含了以下可能类型: + * DEPOSIT + * WITHDRAW + * ORDER + * FUNDING_FEE + * WITHDRAW_REJECT + * ADJUSTMENT + * INSURANCE_CLEAR + * ADMIN_DEPOSIT + * ADMIN_WITHDRAW + * MARGIN_TRANSFER + * MARGIN_TYPE_CHANGE + * ASSET_TRANSFER + * OPTIONS_PREMIUM_FEE + * OPTIONS_SETTLE_PROFIT + * AUTO_EXCHANGE + +* 字段"bc"代表了钱包余额的改变量,即 balance change,但注意其不包含仓位盈亏及交易手续费。 + +## 订单/交易 更新推送 + +> **Payload:** + +```javascript +{ + + "e":"ORDER_TRADE_UPDATE", // 事件类型 + "E":1568879465651, // 事件时间 + "T":1568879465650, // 撮合时间 + "o":{ + "s":"BTCUSDT", // 交易对 + "c":"TEST", // 客户端自定订单ID + // 特殊的自定义订单ID: + // "autoclose-"开头的字符串: 系统强平订单 + // "adl_autoclose": ADL自动减仓订单 + "S":"SELL", // 订单方向 + "o":"TRAILING_STOP_MARKET", // 订单类型 + "f":"GTC", // 有效方式 + "q":"0.001", // 订单原始数量 + "p":"0", // 订单原始价格 + "ap":"0", // 订单平均价格 + "sp":"7103.04", // 条件订单触发价格,对追踪止损单无效 + "x":"NEW", // 本次事件的具体执行类型 + "X":"NEW", // 订单的当前状态 + "i":8886774, // 订单ID + "l":"0", // 订单末次成交量 + "z":"0", // 订单累计已成交量 + "L":"0", // 订单末次成交价格 + "N": "USDT", // 手续费资产类型 + "n": "0", // 手续费数量 + "T":1568879465651, // 成交时间 + "t":0, // 成交ID + "b":"0", // 买单净值 + "a":"9.91", // 卖单净值 + "m": false, // 该成交是作为挂单成交吗? + "R":false , // 是否是只减仓单 + "wt": "CONTRACT_PRICE", // 触发价类型 + "ot": "TRAILING_STOP_MARKET", // 原始订单类型 + "ps":"LONG" // 持仓方向 + "cp":false, // 是否为触发平仓单; 仅在条件订单情况下会推送此字段 + "AP":"7476.89", // 追踪止损激活价格, 仅在追踪止损单时会推送此字段 + "cr":"5.0", // 追踪止损回调比例, 仅在追踪止损单时会推送此字段 + "rp":"0" // 该交易实现盈亏 + + } + +} +``` + + +当有新订单创建、订单有新成交或者新的状态变化时会推送此类事件 +事件类型统一为 `ORDER_TRADE_UPDATE` + +**订单方向** + +* BUY 买入 +* SELL 卖出 + +**订单类型** + +* MARKET 市价单 +* LIMIT 限价单 +* STOP 止损单 +* TAKE_PROFIT 止盈单 +* LIQUIDATION 强平单 + +**本次事件的具体执行类型** + +* NEW +* CANCELED 已撤 +* CALCULATED +* EXPIRED 订单失效 +* TRADE 交易 + + +**订单状态** + +* NEW +* PARTIALLY_FILLED +* FILLED +* CANCELED +* EXPIRED +* NEW_INSURANCE 风险保障基金(强平) +* NEW_ADL 自动减仓序列(强平) + +**有效方式:** + +* GTC +* IOC +* FOK +* GTX + + +## 杠杆倍数等账户配置 更新推送 + +> **Payload:** + +```javascript +{ + "e":"ACCOUNT_CONFIG_UPDATE", // 事件类型 + "E":1611646737479, // 事件时间 + "T":1611646737476, // 撮合时间 + "ac":{ + "s":"BTCUSDT", // 交易对 + "l":25 // 杠杆倍数 + + } +} + +``` + +> **Or** + +```javascript +{ + "e":"ACCOUNT_CONFIG_UPDATE", // 事件类型 + "E":1611646737479, // 事件时间 + "T":1611646737476, // 撮合时间 + "ai":{ // 用户账户配置 + "j":true // 联合保证金状态 + } +} +``` + +当账户配置发生变化时会推送此类事件类型统一为`ACCOUNT_CONFIG_UPDATE ` + +当交易对杠杆倍数发生变化时推送消息体会包含对象`ac`表示交易对账户配置,其中`s`代表具体的交易对,`l`代表杠杆倍数 + +当用户联合保证金状态发生变化时推送消息体会包含对象`ai`表示用户账户配置,其中`j`代表用户联合保证金状态 + + + +# 错误代码 + +> error JSON payload: + +```javascript +{ + "code":-1121, + "msg":"Invalid symbol." +} +``` + +错误由两部分组成:错误代码和消息。 代码是通用的,但是消息可能会有所不同。 + + +## 10xx - 常规服务器或网络问题 +> -1000 UNKNOWN + * An unknown error occured while processing the request. + * 处理请求时发生未知错误。 + +> -1001 DISCONNECTED + * Internal error; unable to process your request. Please try again. + * 内部错误; 无法处理您的请求。 请再试一次. + +> -1002 UNAUTHORIZED + * You are not authorized to execute this request. + * 您无权执行此请求。 + +> -1003 TOO_MANY_REQUESTS + * Too many requests queued. + * 排队的请求过多。 + * Too many requests; please use the websocket for live updates. + * 请求权重过多; 请使用websocket获取最新更新。 + * Too many requests; current limit is %s requests per minute. Please use the websocket for live updates to avoid polling the API. + * 请求权重过多; 当前限制为每分钟%s请求权重。 请使用websocket进行实时更新,以避免轮询API。 + * Way too many requests; IP banned until %s. Please use the websocket for live updates to avoid bans. + * 请求权重过多; IP被禁止,直到%s。 请使用websocket进行实时更新,以免被禁。 + +> -1004 DUPLICATE_IP + * This IP is already on the white list + * IP地址已经在白名单 + +> -1005 NO_SUCH_IP + * No such IP has been white listed + * 白名单上没有此IP地址 + +> -1006 UNEXPECTED_RESP + * An unexpected response was received from the message bus. Execution status unknown. + * 从消息总线收到意外的响应。执行状态未知。 + +> -1007 TIMEOUT + * Timeout waiting for response from backend server. Send status unknown; execution status unknown. + * 等待后端服务器响应超时。 发送状态未知; 执行状态未知。 + +> -1014 UNKNOWN_ORDER_COMPOSITION + * Unsupported order combination. + * 不支持当前的下单参数组合 + +> -1015 TOO_MANY_ORDERS + * Too many new orders. + * 新订单太多。 + * Too many new orders; current limit is %s orders per %s. + * 新订单太多; 当前限制为每%s %s个订单。 + +> -1016 SERVICE_SHUTTING_DOWN + * This service is no longer available. + * 该服务不可用。 + +> -1020 UNSUPPORTED_OPERATION + * This operation is not supported. + * 不支持此操作。 + +> -1021 INVALID_TIMESTAMP + * Timestamp for this request is outside of the recvWindow. + * 此请求的时间戳在recvWindow之外。 + * Timestamp for this request was 1000ms ahead of the server's time. + * 此请求的时间戳比服务器时间提前1000毫秒。 + +> -1022 INVALID_SIGNATURE + * Signature for this request is not valid. + * 此请求的签名无效。 + +> -1023 START_TIME_GREATER_THAN_END_TIME + * Start time is greater than end time. + * 参数里面的开始时间在结束时间之后 + + +## 11xx - Request issues +> -1100 ILLEGAL_CHARS + * Illegal characters found in a parameter. + * 在参数中发现非法字符。 + * Illegal characters found in parameter '%s'; legal range is '%s'. + * 在参数`%s`中发现非法字符; 合法范围是`%s`。 + +> -1101 TOO_MANY_PARAMETERS + * Too many parameters sent for this endpoint. + * 为此端点发送的参数太多。 + * Too many parameters; expected '%s' and received '%s'. + * 参数太多;预期为`%s`并收到了`%s`。 + * Duplicate values for a parameter detected. + * 检测到的参数值重复。 + +> -1102 MANDATORY_PARAM_EMPTY_OR_MALFORMED + * A mandatory parameter was not sent, was empty/null, or malformed. + * 未发送强制性参数,该参数为空/空或格式错误。 + * Mandatory parameter '%s' was not sent, was empty/null, or malformed. + * 强制参数`%s`未发送,为空/空或格式错误。 + * Param '%s' or '%s' must be sent, but both were empty/null! + * 必须发送参数`%s`或`%s`,但两者均为空! + +> -1103 UNKNOWN_PARAM + * An unknown parameter was sent. + * 发送了未知参数。 + +> -1104 UNREAD_PARAMETERS + * Not all sent parameters were read. + * 并非所有发送的参数都被读取。 + * Not all sent parameters were read; read '%s' parameter(s) but was sent '%s'. + * 并非所有发送的参数都被读取; 读取了`%s`参数,但被发送了`%s`。 + +> -1105 PARAM_EMPTY + * A parameter was empty. + * 参数为空。 + * Parameter '%s' was empty. + * 参数`%s`为空。 + +> -1106 PARAM_NOT_REQUIRED + * A parameter was sent when not required. + * 发送了不需要的参数。 + * Parameter '%s' sent when not required. + * 发送了不需要参数`%s`。 + +> -1111 BAD_PRECISION + * Precision is over the maximum defined for this asset. + * 精度超过为此资产定义的最大值。 + +> -1112 NO_DEPTH + * No orders on book for symbol. + * 交易对没有挂单。 + +> -1114 TIF_NOT_REQUIRED + * TimeInForce parameter sent when not required. + * 发送的`TimeInForce`参数不需要。 + +> -1115 INVALID_TIF + * Invalid timeInForce. + * 无效的`timeInForce` + +> -1116 INVALID_ORDER_TYPE + * Invalid orderType. + * 无效订单类型。 + +> -1117 INVALID_SIDE + * Invalid side. + * 无效买卖方向。 + +> -1118 EMPTY_NEW_CL_ORD_ID + * New client order ID was empty. + * 新的客户订单ID为空。 + +> -1119 EMPTY_ORG_CL_ORD_ID + * Original client order ID was empty. + * 客户自定义的订单ID为空。 + +> -1120 BAD_INTERVAL + * Invalid interval. + * 无效时间间隔。 + +> -1121 BAD_SYMBOL + * Invalid symbol. + * 无效的交易对。 + +> -1125 INVALID_LISTEN_KEY + * This listenKey does not exist. + * 此`listenKey`不存在。 + +> -1127 MORE_THAN_XX_HOURS + * Lookup interval is too big. + * 查询间隔太大。 + * More than %s hours between startTime and endTime. + * 从开始时间到结束时间之间超过`%s`小时。 + +> -1128 OPTIONAL_PARAMS_BAD_COMBO + * Combination of optional parameters invalid. + * 可选参数组合无效。 + +> -1130 INVALID_PARAMETER + * Invalid data sent for a parameter. + * 发送的参数为无效数据。 + * Data sent for parameter '%s' is not valid. + * 发送参数`%s`的数据无效。 + +> -1136 INVALID_NEW_ORDER_RESP_TYPE + * Invalid newOrderRespType. + * 无效的 newOrderRespType。 + + +## 20xx - Processing Issues +> -2010 NEW_ORDER_REJECTED + * NEW_ORDER_REJECTED + * 新订单被拒绝 + +> -2011 CANCEL_REJECTED + * CANCEL_REJECTED + * 取消订单被拒绝 + +> -2013 NO_SUCH_ORDER + * Order does not exist. + * 订单不存在。 + +> -2014 BAD_API_KEY_FMT + * API-key format invalid. + * API-key 格式无效。 + +> -2015 REJECTED_MBX_KEY + * Invalid API-key, IP, or permissions for action. + * 无效的API密钥,IP或操作权限。 + +> -2016 NO_TRADING_WINDOW + * No trading window could be found for the symbol. Try ticker/24hrs instead. + * 找不到该交易对的交易窗口。 尝试改为24小时自动报价。 + +> -2018 BALANCE_NOT_SUFFICIENT + * Balance is insufficient. + * 余额不足 + +> -2019 MARGIN_NOT_SUFFICIEN + * Margin is insufficient. + * 杠杆账户余额不足 + +> -2020 UNABLE_TO_FILL + * Unable to fill. + * 无法成交 + +> -2021 ORDER_WOULD_IMMEDIATELY_TRIGGER + * Order would immediately trigger. + * 订单可能被立刻触发 + +> -2022 REDUCE_ONLY_REJECT + * ReduceOnly Order is rejected. + * `ReduceOnly`订单被拒绝 + +> -2023 USER_IN_LIQUIDATION + * User in liquidation mode now. + * 用户正处于被强平模式 + +> -2024 POSITION_NOT_SUFFICIENT + * Position is not sufficient. + * 持仓不足 + +> -2025 MAX_OPEN_ORDER_EXCEEDED + * Reach max open order limit. + * 挂单量达到上限 + +> -2026 REDUCE_ONLY_ORDER_TYPE_NOT_SUPPORTED + * This OrderType is not supported when reduceOnly. + * 当前订单类型不支持`reduceOnly` + +> -2027 MAX_LEVERAGE_RATIO + * Exceeded the maximum allowable position at current leverage. + * 挂单或持仓超出当前初始杠杆下的最大值 + +> -2028 MIN_LEVERAGE_RATIO + * Leverage is smaller than permitted: insufficient margin balance. + * 调整初始杠杆过低,导致可用余额不足 + +## 40xx - Filters and other Issues +> -4000 INVALID_ORDER_STATUS + * Invalid order status. + * 订单状态不正确 + +> -4001 PRICE_LESS_THAN_ZERO + * Price less than 0. + * 价格小于0 + +> -4002 PRICE_GREATER_THAN_MAX_PRICE + * Price greater than max price. + * 价格超过最大值 + +> -4003 QTY_LESS_THAN_ZERO + * Quantity less than zero. + * 数量小于0 + +> -4004 QTY_LESS_THAN_MIN_QTY + * Quantity less than min quantity. + * 数量小于最小值 + +> -4005 QTY_GREATER_THAN_MAX_QTY + * Quantity greater than max quantity. + * 数量大于最大值 + +> -4006 STOP_PRICE_LESS_THAN_ZERO + * Stop price less than zero. + * 触发价小于最小值 + +> -4007 STOP_PRICE_GREATER_THAN_MAX_PRICE + * Stop price greater than max price. + * 触发价大于最大值 + +> -4008 TICK_SIZE_LESS_THAN_ZERO + * Tick size less than zero. + * 价格精度小于0 + +> -4009 MAX_PRICE_LESS_THAN_MIN_PRICE + * Max price less than min price. + * 最大价格小于最小价格 + +> -4010 MAX_QTY_LESS_THAN_MIN_QTY + * Max qty less than min qty. + * 最大数量小于最小数量 + +> -4011 STEP_SIZE_LESS_THAN_ZERO + * Step size less than zero. + * 步进值小于0 + +> -4012 MAX_NUM_ORDERS_LESS_THAN_ZERO + * Max num orders less than zero. + * 最大订单量小于0 + +> -4013 PRICE_LESS_THAN_MIN_PRICE + * Price less than min price. + * 价格小于最小价格 + +> -4014 PRICE_NOT_INCREASED_BY_TICK_SIZE + * Price not increased by tick size. + * 价格增量不是价格精度的倍数。 + +> -4015 INVALID_CL_ORD_ID_LEN + * Client order id is not valid. + * 客户订单ID有误。 + * Client order id length should not be more than 36 chars + * 客户订单ID长度应该不多于36字符 + +> -4016 PRICE_HIGHTER_THAN_MULTIPLIER_UP + * Price is higher than mark price multiplier cap. + +> -4017 MULTIPLIER_UP_LESS_THAN_ZERO + * Multiplier up less than zero. + * 价格上限小于0 + +> -4018 MULTIPLIER_DOWN_LESS_THAN_ZERO + * Multiplier down less than zero. + * 价格下限小于0 + +> -4019 COMPOSITE_SCALE_OVERFLOW + * Composite scale too large. + +> -4020 TARGET_STRATEGY_INVALID + * Target strategy invalid for orderType '%s',reduceOnly '%b'. + * 目标策略值不适合`%s`订单状态, 只减仓`%b`。 + +> -4021 INVALID_DEPTH_LIMIT + * Invalid depth limit. + * 深度信息的`limit`值不正确。 + * '%s' is not valid depth limit. + * `%s`不是合理的深度信息的`limit`值。 + +> -4022 WRONG_MARKET_STATUS + * market status sent is not valid. + * 发送的市场状态不正确。 + +> -4023 QTY_NOT_INCREASED_BY_STEP_SIZE + * Qty not increased by step size. + * 数量的递增值不是步进值的倍数。 + +> -4024 PRICE_LOWER_THAN_MULTIPLIER_DOWN + * Price is lower than mark price multiplier floor. + +> -4025 MULTIPLIER_DECIMAL_LESS_THAN_ZERO + * Multiplier decimal less than zero. + +> -4026 COMMISSION_INVALID + * Commission invalid. + * 收益值不正确 + * `%s` less than zero. + * `%s`少于0 + * `%s` absolute value greater than `%s` + * `%s`绝对值大于`%s` + +> -4027 INVALID_ACCOUNT_TYPE + * Invalid account type. + * 账户类型不正确。 + +> -4028 INVALID_LEVERAGE + * Invalid leverage + * 杠杆倍数不正确 + * Leverage `%s` is not valid + * 杠杆`%s`不正确 + * Leverage `%s` already exist with `%s` + * 杠杆`%s`已经存在于`%s` + +> -4029 INVALID_TICK_SIZE_PRECISION + * Tick size precision is invalid. + * 价格精度小数点位数不正确。 + +> -4030 INVALID_STEP_SIZE_PRECISION + * Step size precision is invalid. + * 步进值小数点位数不正确。 + +> -4031 INVALID_WORKING_TYPE + * Invalid parameter working type + * 不正确的参数类型 + * Invalid parameter working type: `%s` + * 不正确的参数类型: `%s` + +> -4032 EXCEED_MAX_CANCEL_ORDER_SIZE + * Exceed maximum cancel order size. + * 超过可以取消的最大订单量。 + * Invalid parameter working type: `%s` + * 不正确的参数类型: `%s` + +> -4033 INSURANCE_ACCOUNT_NOT_FOUND + * Insurance account not found. + * 风险保障基金账号没找到。 + +> -4044 INVALID_BALANCE_TYPE + * Balance Type is invalid. + * 余额类型不正确。 + +> -4045 MAX_STOP_ORDER_EXCEEDED + * Reach max stop order limit. + * 达到止损单的上限。 + +> -4046 NO_NEED_TO_CHANGE_MARGIN_TYPE + * No need to change margin type. + * 不需要切换仓位模式。 + +> -4047 THERE_EXISTS_OPEN_ORDERS + * Margin type cannot be changed if there exists open orders. + * 如果有挂单,仓位模式不能切换。 + +> -4048 THERE_EXISTS_QUANTITY + * Margin type cannot be changed if there exists position. + * 如果有仓位,仓位模式不能切换。 + +> -4049 ADD_ISOLATED_MARGIN_REJECT + * Add margin only support for isolated position. + +> -4050 CROSS_BALANCE_INSUFFICIENT + * Cross balance insufficient. + * 全仓余额不足。 + +> -4051 ISOLATED_BALANCE_INSUFFICIENT + * Isolated balance insufficient. + * 逐仓余额不足。 + +> -4052 NO_NEED_TO_CHANGE_AUTO_ADD_MARGIN + * No need to change auto add margin. + +> -4053 AUTO_ADD_CROSSED_MARGIN_REJECT + * Auto add margin only support for isolated position. + * 自动增加保证金只适用于逐仓。 + +> -4054 ADD_ISOLATED_MARGIN_NO_POSITION_REJECT + * Cannot add position margin: position is 0. + * 不能增加逐仓保证金: 持仓为0 + +> -4055 AMOUNT_MUST_BE_POSITIVE + * Amount must be positive. + * 数量必须是正整数 + +> -4056 INVALID_API_KEY_TYPE + * Invalid api key type. + * API key的类型不正确 + +> -4057 INVALID_RSA_PUBLIC_KEY + * Invalid api public key + * API key不正确 + +> -4058 MAX_PRICE_TOO_LARGE + * maxPrice and priceDecimal too large,please check. + * maxPrice和priceDecimal太大,请检查。 + +> -4059 NO_NEED_TO_CHANGE_POSITION_SIDE + * No need to change position side. + * 无需变更仓位方向 + +> -4060 INVALID_POSITION_SIDE + * Invalid position side. + * 仓位方向不正确。 + +> -4061 POSITION_SIDE_NOT_MATCH + * Order's position side does not match user's setting. + * 订单的持仓方向和用户设置不一致。 + +> -4062 REDUCE_ONLY_CONFLICT + * Invalid or improper reduceOnly value. + * 仅减仓的设置不正确。 + +> -4063 INVALID_OPTIONS_REQUEST_TYPE + * Invalid options request type + * 无效的期权请求类型 + +> -4064 INVALID_OPTIONS_TIME_FRAME + * Invalid options time frame + * 无效的期权时间窗口 + +> -4065 INVALID_OPTIONS_AMOUNT + * Invalid options amount + * 无效的期权数量 + +> -4066 INVALID_OPTIONS_EVENT_TYPE + * Invalid options event type + * 无效的期权事件类型 + +> -4067 POSITION_SIDE_CHANGE_EXISTS_OPEN_ORDERS + * Position side cannot be changed if there exists open orders. + * 如果有挂单,无法修改仓位方向。 + +> -4068 POSITION_SIDE_CHANGE_EXISTS_QUANTITY + * Position side cannot be changed if there exists position. + * 如果有仓位, 无法修改仓位方向。 + +> -4069 INVALID_OPTIONS_PREMIUM_FEE + * Invalid options premium fee + * 无效的期权费 + +> -4070 INVALID_CL_OPTIONS_ID_LEN + * Client options id is not valid. + * 客户的期权ID不合法 + * Client options id length should be less than 32 chars + * 客户的期权ID长度应该小于32个字符 + +> -4071 INVALID_OPTIONS_DIRECTION + * Invalid options direction + * 期权的方向无效 + +> -4072 OPTIONS_PREMIUM_NOT_UPDATE + * premium fee is not updated, reject order + * 期权费没有更新 + +> -4073 OPTIONS_PREMIUM_INPUT_LESS_THAN_ZERO + * input premium fee is less than 0, reject order + * 输入的期权费小于0 + +> -4074 OPTIONS_AMOUNT_BIGGER_THAN_UPPER + * Order amount is bigger than upper boundary or less than 0, reject order + +> -4075 OPTIONS_PREMIUM_OUTPUT_ZERO + * output premium fee is less than 0, reject order + +> -4076 OPTIONS_PREMIUM_TOO_DIFF + * original fee is too much higher than last fee + * 期权的费用比之前的费用高 + +> -4077 OPTIONS_PREMIUM_REACH_LIMIT + * place order amount has reached to limit, reject order + * 下单的数量达到上限 + +> -4078 OPTIONS_COMMON_ERROR + * options internal error + * 期权内部系统错误 + +> -4079 INVALID_OPTIONS_ID + * invalid options id + * invalid options id: %s + * duplicate options id %d for user %d + * 期权ID无效 + +> -4080 OPTIONS_USER_NOT_FOUND + * user not found + * user not found with id: %s + * 用户找不到 + +> -4081 OPTIONS_NOT_FOUND + * options not found + * options not found with id: %s + * 期权找不到 + +> -4082 INVALID_BATCH_PLACE_ORDER_SIZE + * Invalid number of batch place orders. + * Invalid number of batch place orders: %s + * 批量下单的数量不正确 + +> -4083 PLACE_BATCH_ORDERS_FAIL + * Fail to place batch orders. + * 无法批量下单 + +> -4084 UPCOMING_METHOD + * Method is not allowed currently. Upcoming soon. + * 方法不支持 + +> -4085 INVALID_NOTIONAL_LIMIT_COEF + * Invalid notional limit coefficient + * 期权的有限系数不正确 + +> -4086 INVALID_PRICE_SPREAD_THRESHOLD + * Invalid price spread threshold + * 无效的价差阀值 + +> -4087 REDUCE_ONLY_ORDER_PERMISSION + * User can only place reduce only order + * 用户只能下仅减仓订单 + +> -4088 NO_PLACE_ORDER_PERMISSION + * User can not place order currently + * 用户当前不能下单 + +> -4104 INVALID_CONTRACT_TYPE + * Invalid contract type + * 无效的合约类型 + +> -4114 INVALID_CLIENT_TRAN_ID_LEN + * clientTranId is not valid + * clientTranId不正确 + * Client tran id length should be less than 64 chars + * 客户的tranId长度应该小于64个字符 + +> -4115 DUPLICATED_CLIENT_TRAN_ID + * clientTranId is duplicated + * clientTranId重复 + * Client tran id should be unique within 7 days + * 客户的tranId应在7天内唯一 + +> -4118 REDUCE_ONLY_MARGIN_CHECK_FAILED + * ReduceOnly Order Failed. Please check your existing position and open orders + * 仅减仓订单失败。请检查现有的持仓和挂单 + +> -4131 MARKET_ORDER_REJECT + * The counterparty's best price does not meet the PERCENT_PRICE filter limit + * 交易对手的最高价格未达到PERCENT_PRICE过滤器限制 + +> -4135 INVALID_ACTIVATION_PRICE + * Invalid activation price + * 无效的激活价格 + +> -4137 QUANTITY_EXISTS_WITH_CLOSE_POSITION + * Quantity must be zero with closePosition equals true + * 数量必须为0,当closePosition为true时 + +> -4138 REDUCE_ONLY_MUST_BE_TRUE + * Reduce only must be true with closePosition equals true + * Reduce only 必须为true,当closePosition为true时 + +> -4139 ORDER_TYPE_CANNOT_BE_MKT + * Order type can not be market if it's unable to cancel + * 订单类型不能为市价单如果不能取消 + +> -4140 INVALID_OPENING_POSITION_STATUS + * Invalid symbol status for opening position + * 无效的交易对状态 + +> -4141 SYMBOL_ALREADY_CLOSED + * Symbol is closed + * 交易对已下架 + +> -4142 STRATEGY_INVALID_TRIGGER_PRICE + * REJECT: take profit or stop order will be triggered immediately + * 拒绝:止盈止损单将立即被触发 + +> -4144 INVALID_PAIR + * Invalid pair + * 无效的pair + +> -4161 ISOLATED_LEVERAGE_REJECT_WITH_POSITION + * Leverage reduction is not supported in Isolated Margin Mode with open positions + * 逐仓仓位模式下无法降低杠杆 + +> -4164 MIN_NOTIONAL + * Order's notional must be no smaller than 5.0 (unless you choose reduce only) + * 订单的名义价值不可以小于5,除了使用reduce only + * Order's notional must be no smaller than %s (unless you choose reduce only) + * 订单的名义价值不可以小于`%s`,除了使用reduce only + +> -4165 INVALID_TIME_INTERVAL + * Invalid time interval + * 无效的间隔 + * Maximum time interval is %s days + * 最大的时间间隔为 `%s` 天 + +> -4183 PRICE_HIGHTER_THAN_STOP_MULTIPLIER_UP + * Price is higher than stop price multiplier cap. + * 止盈止损订单价格不应高于触发价与报价乘数上限的乘积 + * Limit price can't be higher than %s. + * 止盈止损订单价格不应高于 `%s` + +> -4184 PRICE_LOWER_THAN_STOP_MULTIPLIER_DOWN + * Price is lower than stop price multiplier floor. + * 止盈止损订单价格不应低于触发价与报价乘数下限的乘积 + * Limit price can't be lower than %s. + * 止盈止损订单价格不应低于 `%s` + diff --git a/aster-finance-future-api.md b/aster-finance-futures-api.md similarity index 99% rename from aster-finance-future-api.md rename to aster-finance-futures-api.md index effe0f5..0746110 100644 --- a/aster-finance-future-api.md +++ b/aster-finance-futures-api.md @@ -72,7 +72,7 @@ - [Get Current Multi-Assets Mode (USER_DATA)](#get-current-multi-assets-mode-user_data) - [New Order (TRADE)](#new-order--trade) - [Place Multiple Orders (TRADE)](#place-multiple-orders--trade) - - [Transfer Between Futures And Spot (TRADE)](#transfer-between-futures-and-spot--trade) + - [Transfer Between Futures And Spot (USER_DATA)](#transfer-between-futures-and-spot-user_data) - [Query Order (USER_DATA)](#query-order-user_data) - [Cancel Order (TRADE)](#cancel-order-trade) - [Cancel All Open Orders (TRADE)](#cancel-all-open-orders-trade) @@ -2463,7 +2463,7 @@ newOrderRespType | ENUM | NO | "ACK", "RESULT", default "ACK" * Batch orders are processed concurrently, and the order of matching is not guaranteed. * The order of returned contents for batch orders is the same as the order of the order list. -## Transfer Between Futures And Spot (TRADE) +## Transfer Between Futures And Spot (USER_DATA) > **Response:** @@ -2475,7 +2475,7 @@ newOrderRespType | ENUM | NO | "ACK", "RESULT", default "ACK" ``` `` -POST /fapi/v1/asset/wallet/transfer (HMAC SHA256) +POST /fapi/v1/asset/wallet/transfer (HMAC SHA256) `` **Weight:** diff --git a/aster-finance-future-api_CN.md b/aster-finance-futures-api_CN.md similarity index 100% rename from aster-finance-future-api_CN.md rename to aster-finance-futures-api_CN.md diff --git a/aster-finance-spot-api.md b/aster-finance-spot-api.md index 848f52e..9c96310 100644 --- a/aster-finance-spot-api.md +++ b/aster-finance-spot-api.md @@ -780,8 +780,8 @@ Each K-line represents a trading pair. The open time of each K-line can be regar "firstId": 28385, // first id "lastId": 28460, // last id "count": 76, // count - "baseAsset": "CDL", //base asset - "quoteAsset": "FORM" //quote asset + "baseAsset": "BTC", //base asset + "quoteAsset": "USDT" //quote asset } ``` diff --git a/aster-finance-spot-api_CN.md b/aster-finance-spot-api_CN.md index ea14d72..d702289 100644 --- a/aster-finance-spot-api_CN.md +++ b/aster-finance-spot-api_CN.md @@ -819,8 +819,8 @@ limit | INT | NO | 默认 500; 最大 1500. "firstId": 28385, // 首笔成交id "lastId": 28460, // 末笔成交id "count": 76, // 成交笔数 - "baseAsset": "CDL", //基础代币 - "quoteAsset": "FORM" //报价代币 + "baseAsset": "BTC", //基础代币 + "quoteAsset": "USDT" //报价代币 } ``` From 19a5c16cd9bd6aa9887f29febc5a21ced2c42098 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Tue, 16 Sep 2025 14:08:42 +0800 Subject: [PATCH 012/131] v3 change url to prod --- README.md | 4 ++ aster-finance-futures-api-v3.md | 10 +-- aster-finance-futures-api-v3_CN.md | 10 +-- v3-demo/requirements.txt | 4 ++ v3-demo/tx.py | 99 ++++++++++++++++++++++++++++++ 5 files changed, 117 insertions(+), 10 deletions(-) create mode 100644 v3-demo/requirements.txt create mode 100644 v3-demo/tx.py diff --git a/README.md b/README.md index c4e7c68..a4ad5df 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,10 @@ [Aster Finance Futures API V3 文档](./aster-finance-futures-api-v3_CN.md) +# Aster Finance Futures API V3 DEMO + +[Aster Finance Futures API V3 DEMO](./v3-demo/tx.py) + # API Documentation for Aster Finance Spot [Aster Finance Spot API Document](./aster-finance-spot-api.md) diff --git a/aster-finance-futures-api-v3.md b/aster-finance-futures-api-v3.md index fe2daf4..9d63a0c 100644 --- a/aster-finance-futures-api-v3.md +++ b/aster-finance-futures-api-v3.md @@ -348,14 +348,14 @@ my_dict = {'symbol': 'SANDUSDT', 'positionSide': 'BOTH', 'type': 'LIMIT', 'side' my_dict['user'] = user my_dict['signer'] = signer my_dict['signature'] = '0x'+signed_message.signature.hex() - url ='http://127.0.0.1:9081/fapi/v3/order' + url ='https://fapi.asterdex.com/fapi/v3/order' headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'PythonApp/1.0' } res = requests.post(url,data=my_dict,headers=headers) print(url) - #curl -X POST 'http://127.0.0.1:9081/fapi/v3/order' -d 'symbol=SANDUSDT&positionSide=BOTH&type=LIMIT&side=BUY&timeInForce=GTC&quantity=190&price=0.28694&recvWindow=50000×tamp=1749545309665&nonce=1748310859508867&user=0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e&signer=0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0&signature=0x0337dd720a21543b80ff861cd3c26646b75b3a6a4b5d45805d4c1d6ad6fc33e65f0722778dd97525466560c69fbddbe6874eb4ed6f5fa7e576e486d9b5da67f31b' + #curl -X POST 'https://fapi.asterdex.com/fapi/v3/order' -d 'symbol=SANDUSDT&positionSide=BOTH&type=LIMIT&side=BUY&timeInForce=GTC&quantity=190&price=0.28694&recvWindow=50000×tamp=1749545309665&nonce=1748310859508867&user=0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e&signer=0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0&signature=0x0337dd720a21543b80ff861cd3c26646b75b3a6a4b5d45805d4c1d6ad6fc33e65f0722778dd97525466560c69fbddbe6874eb4ed6f5fa7e576e486d9b5da67f31b' ``` ## Example of POST /fapi/v3/order @@ -467,11 +467,11 @@ from eth_account import Account my_dict['signer'] = signer my_dict['signature'] = '0x'+signed_message.signature.hex() - url ='http://127.0.0.1:9081/fapi/v3/order' + url ='https://fapi.asterdex.com/fapi/v3/order' res = requests.get(url, params=my_dict) print(url) - #curl -X GET 'http://127.0.0.1:9081/fapi/v3/order?symbol=SANDUSDT&side=BUY&type=LIMIT&orderId=2194215&recvWindow=50000×tamp=1749545309665&nonce=1748310859508867&user=0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e&signer=0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0&signature=0x4f5e36e91f0d4cf5b29b6559ebc2c808d3c808ebb13b2bcaaa478b98fb4195642c7473f0d1aa101359aaf278126af1a53bcb482fb05003bfb6bdc03de03c63151b' + #curl -X GET 'https://fapi.asterdex.com/fapi/v3/order?symbol=SANDUSDT&side=BUY&type=LIMIT&orderId=2194215&recvWindow=50000×tamp=1749545309665&nonce=1748310859508867&user=0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e&signer=0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0&signature=0x4f5e36e91f0d4cf5b29b6559ebc2c808d3c808ebb13b2bcaaa478b98fb4195642c7473f0d1aa101359aaf278126af1a53bcb482fb05003bfb6bdc03de03c63151b' ``` ## python script @@ -497,7 +497,7 @@ from web3 import Web3 user = '0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e' signer='0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0' priKey = "0x4fd0a42218f3eae43a6ce26d22544e986139a01e5b34a62db53757ffca81bae1" -host = 'http://127.0.0.1:9081' +host = 'https://fapi.asterdex.com' placeOrder = {'url': '/fapi/v3/order', 'method': 'POST', 'params':{'symbol': 'SANDUSDT', 'positionSide': 'BOTH', 'type': 'LIMIT', 'side': 'BUY', 'timeInForce': 'GTC', 'quantity': "30", 'price': 0.325,'reduceOnly': True}} diff --git a/aster-finance-futures-api-v3_CN.md b/aster-finance-futures-api-v3_CN.md index f05681e..73324c4 100644 --- a/aster-finance-futures-api-v3_CN.md +++ b/aster-finance-futures-api-v3_CN.md @@ -328,14 +328,14 @@ long microsecond = now.getEpochSecond() * 1000000 + now.getNano() / 1000; my_dict['user'] = user my_dict['signer'] = signer my_dict['signature'] = '0x'+signed_message.signature.hex() - url ='http://127.0.0.1:9081/fapi/v3/order' + url ='https://fapi.asterdex.com/fapi/v3/order' headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'PythonApp/1.0' } res = requests.post(url,data=my_dict,headers=headers) print(url) - #curl -X POST 'http://127.0.0.1:9081/fapi/v3/order' -d 'symbol=SANDUSDT&positionSide=BOTH&type=LIMIT&side=BUY&timeInForce=GTC&quantity=190&price=0.28694&recvWindow=50000×tamp=1749545309665&nonce=1748310859508867&user=0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e&signer=0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0&signature=0x0337dd720a21543b80ff861cd3c26646b75b3a6a4b5d45805d4c1d6ad6fc33e65f0722778dd97525466560c69fbddbe6874eb4ed6f5fa7e576e486d9b5da67f31b' + #curl -X POST 'https://fapi.asterdex.com/fapi/v3/order' -d 'symbol=SANDUSDT&positionSide=BOTH&type=LIMIT&side=BUY&timeInForce=GTC&quantity=190&price=0.28694&recvWindow=50000×tamp=1749545309665&nonce=1748310859508867&user=0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e&signer=0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0&signature=0x0337dd720a21543b80ff861cd3c26646b75b3a6a4b5d45805d4c1d6ad6fc33e65f0722778dd97525466560c69fbddbe6874eb4ed6f5fa7e576e486d9b5da67f31b' ``` @@ -439,11 +439,11 @@ my_dict = {'symbol':'SANDUSDT','side':"SELL","type":'LIMIT','orderId':2194215} my_dict['signer'] = signer my_dict['signature'] = '0x'+signed_message.signature.hex() - url ='http://127.0.0.1:9081/fapi/v3/order' + url ='https://fapi.asterdex.com/fapi/v3/order' res = requests.get(url, params=my_dict) print(url) - #curl -X GET 'http://127.0.0.1:9081/fapi/v3/order?symbol=SANDUSDT&side=BUY&type=LIMIT&orderId=2194215&recvWindow=50000×tamp=1749545309665&nonce=1748310859508867&user=0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e&signer=0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0&signature=0x4f5e36e91f0d4cf5b29b6559ebc2c808d3c808ebb13b2bcaaa478b98fb4195642c7473f0d1aa101359aaf278126af1a53bcb482fb05003bfb6bdc03de03c63151b' + #curl -X GET 'https://fapi.asterdex.com/fapi/v3/order?symbol=SANDUSDT&side=BUY&type=LIMIT&orderId=2194215&recvWindow=50000×tamp=1749545309665&nonce=1748310859508867&user=0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e&signer=0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0&signature=0x4f5e36e91f0d4cf5b29b6559ebc2c808d3c808ebb13b2bcaaa478b98fb4195642c7473f0d1aa101359aaf278126af1a53bcb482fb05003bfb6bdc03de03c63151b' ``` ## 完整python脚本示例 @@ -467,7 +467,7 @@ from web3 import Web3 user = '0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e' signer='0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0' priKey = "0x4fd0a42218f3eae43a6ce26d22544e986139a01e5b34a62db53757ffca81bae1" -host = 'http://127.0.0.1:9081' +host = 'https://fapi.asterdex.com' placeOrder = {'url': '/fapi/v3/order', 'method': 'POST', 'params':{'symbol': 'SANDUSDT', 'positionSide': 'BOTH', 'type': 'LIMIT', 'side': 'BUY', 'timeInForce': 'GTC', 'quantity': "30", 'price': 0.325,'reduceOnly': True}} diff --git a/v3-demo/requirements.txt b/v3-demo/requirements.txt new file mode 100644 index 0000000..dd7d83a --- /dev/null +++ b/v3-demo/requirements.txt @@ -0,0 +1,4 @@ +eth-account~=0.13.7 +eth-abi~=5.2.0 +web3~=7.11.0 +requests~=2.32.3 diff --git a/v3-demo/tx.py b/v3-demo/tx.py new file mode 100644 index 0000000..a0ae4ee --- /dev/null +++ b/v3-demo/tx.py @@ -0,0 +1,99 @@ + +#Python 3.9.6 +# eth-account~=0.13.7 +# eth-abi~=5.2.0 +# web3~=7.11.0 +# requests~=2.32.3 +# pip install -r requirements.txt + +import json +import math +import time +import requests + +from eth_abi import encode +from eth_account import Account +from eth_account.messages import encode_defunct +from web3 import Web3 + +user = '0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e' +signer='0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0' +priKey = "0x4fd0a42218f3eae43a6ce26d22544e986139a01e5b34a62db53757ffca81bae1" + +host = 'https://fapi.asterdex.com' + +placeOrder = {'url': '/fapi/v3/order', 'method': 'POST', + 'params':{'symbol': 'SANDUSDT', 'positionSide': 'BOTH', 'type': 'LIMIT', 'side': 'BUY', + 'timeInForce': 'GTC', 'quantity': "30", 'price': 0.325,'reduceOnly': True}} +getOrder = {'url':'/fapi/v3/order','method':'GET','params':{'symbol':'SANDUSDT','side':"BUY","type":'LIMIT','orderId':2194215}} + +def call(api): + nonce = math.trunc(time.time() * 1000000) + my_dict = api['params'] + send(api['url'],api['method'],sign(my_dict,nonce)) + +def sign(my_dict,nonce): + my_dict = {key: value for key, value in my_dict.items() if value is not None} + my_dict['recvWindow'] = 50000 + my_dict['timestamp'] = int(round(time.time()*1000)) + msg = trim_param(my_dict,nonce) + signable_msg = encode_defunct(hexstr=msg) + signed_message = Account.sign_message(signable_message=signable_msg, private_key=priKey) + my_dict['nonce'] = nonce + my_dict['user'] = user + my_dict['signer'] = signer + my_dict['signature'] = '0x'+signed_message.signature.hex() + + print(my_dict['signature']) + return my_dict + +def trim_param(my_dict,nonce) -> str: + _trim_dict(my_dict) + json_str = json.dumps(my_dict, sort_keys=True).replace(' ', '').replace('\'','\"') + print(json_str) + encoded = encode(['string', 'address', 'address', 'uint256'], [json_str, user, signer, nonce]) + print(encoded.hex()) + keccak_hex =Web3.keccak(encoded).hex() + print(keccak_hex) + return keccak_hex + +def _trim_dict(my_dict) : + for key in my_dict: + value = my_dict[key] + if isinstance(value, list): + new_value = [] + for item in value: + if isinstance(item, dict): + new_value.append(json.dumps(_trim_dict(item))) + else: + new_value.append(str(item)) + my_dict[key] = json.dumps(new_value) + continue + if isinstance(value, dict): + my_dict[key] = json.dumps(_trim_dict(value)) + continue + my_dict[key] = str(value) + + return my_dict + +def send(url, method, my_dict): + url = host + url + print(url) + print(my_dict) + if method == 'POST': + headers = { + 'Content-Type': 'application/x-www-form-urlencoded', + 'User-Agent': 'PythonApp/1.0' + } + res = requests.post(url, data=my_dict, headers=headers) + print(res.text) + if method == 'GET': + res = requests.get(url, params=my_dict) + print(res.text) + if method == 'DELETE': + res = requests.delete(url, data=my_dict) + print(res.text) + +if __name__ == '__main__': + # call(placeOrder) + call(getOrder) From a1dada4d5cdd9a1f241e3c745f0d72b6dd25fb92 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Fri, 19 Sep 2025 10:35:44 +0800 Subject: [PATCH 013/131] use apiwallet --- aster-finance-futures-api-v3.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/aster-finance-futures-api-v3.md b/aster-finance-futures-api-v3.md index 9d63a0c..8a09567 100644 --- a/aster-finance-futures-api-v3.md +++ b/aster-finance-futures-api-v3.md @@ -219,7 +219,7 @@ It is recommended to use a small recvWindow of 5000 or less! * After converting the API parameters to strings, sort them by their key values in ASCII order to generate the final string. Note: All parameter values must be treated as strings during the signing process. * After generating the string, combine it with the authentication signature parameters user, signer, and nonce, then use Web3’s ABI parameter encoding to generate the bytecode. * After generating the bytecode, use the Keccak algorithm to generate the hash. -* Use the private key of the derived address to sign the hash using web3’s ECDSA signature algorithm, generating the final signature. +* Use the private key of **API wallet address** to sign the hash using web3’s ECDSA signature algorithm, generating the final signature. ### Timing Security From 81f130dc11ad7c905d1aba50c56ada083e101b0b Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Wed, 24 Sep 2025 15:48:57 +0800 Subject: [PATCH 014/131] add api guide --- aster-finance-futures-api-v3.md | 1 + aster-finance-futures-api-v3_CN.md | 1 + 2 files changed, 2 insertions(+) diff --git a/aster-finance-futures-api-v3.md b/aster-finance-futures-api-v3.md index 8a09567..40c4350 100644 --- a/aster-finance-futures-api-v3.md +++ b/aster-finance-futures-api-v3.md @@ -114,6 +114,7 @@ ## General API Information * This API may require the user's AGENT. To learn how to create an AGENT, please refer toSome endpoints will require an API Key. Please refer to [this page](https://www.asterdex.com/) +* To create an agent please [click here](https://www.asterdex.com/en/api-wallet) and switch to `Pro API` at the top * The base endpoint is: **https://fapi.asterdex.com** * All endpoints return either a JSON object or array. * Data is returned in **ascending** order. Oldest first, newest last. diff --git a/aster-finance-futures-api-v3_CN.md b/aster-finance-futures-api-v3_CN.md index 73324c4..a34f5dd 100644 --- a/aster-finance-futures-api-v3_CN.md +++ b/aster-finance-futures-api-v3_CN.md @@ -113,6 +113,7 @@ ## Rest 基本信息 * 接口可能需要用户的AGENT,如何创建AGENT请参考[这里](https://www.asterdex.com/) +* agent创建请[点击这里](https://www.asterdex.com/zh-CN/api-wallet) 并且切换到API管理上方的`专业API` * 本篇列出REST接口的baseurl **https://fapi.asterdex.com** * 所有接口的响应都是JSON格式 * 响应中如有数组,数组元素以时间升序排列,越早的数据越提前。 From ee484d3483f8fdccb72feb1a200b02232fcd6aca Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Mon, 29 Sep 2025 15:22:29 +0800 Subject: [PATCH 015/131] apiv3 url --- aster-finance-futures-api-v3.md | 4 ++-- aster-finance-futures-api-v3_CN.md | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/aster-finance-futures-api-v3.md b/aster-finance-futures-api-v3.md index 40c4350..fdc5f93 100644 --- a/aster-finance-futures-api-v3.md +++ b/aster-finance-futures-api-v3.md @@ -113,8 +113,8 @@ ## General API Information -* This API may require the user's AGENT. To learn how to create an AGENT, please refer toSome endpoints will require an API Key. Please refer to [this page](https://www.asterdex.com/) -* To create an agent please [click here](https://www.asterdex.com/en/api-wallet) and switch to `Pro API` at the top +* This API may require the user's AGENT. +* To create an AGENT please [click here](https://www.asterdex.com/en/api-wallet) and switch to `Pro API` at the top * The base endpoint is: **https://fapi.asterdex.com** * All endpoints return either a JSON object or array. * Data is returned in **ascending** order. Oldest first, newest last. diff --git a/aster-finance-futures-api-v3_CN.md b/aster-finance-futures-api-v3_CN.md index a34f5dd..8954424 100644 --- a/aster-finance-futures-api-v3_CN.md +++ b/aster-finance-futures-api-v3_CN.md @@ -112,8 +112,8 @@ ## Rest 基本信息 -* 接口可能需要用户的AGENT,如何创建AGENT请参考[这里](https://www.asterdex.com/) -* agent创建请[点击这里](https://www.asterdex.com/zh-CN/api-wallet) 并且切换到API管理上方的`专业API` +* 接口可能需要用户的AGENT +* AGENT创建请[点击这里](https://www.asterdex.com/zh-CN/api-wallet) 并且切换到API管理上方的`专业API` * 本篇列出REST接口的baseurl **https://fapi.asterdex.com** * 所有接口的响应都是JSON格式 * 响应中如有数组,数组元素以时间升序排列,越早的数据越提前。 From 615578940aa736f949f1691b2c4d3a60d865e5a3 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Mon, 29 Sep 2025 15:41:55 +0800 Subject: [PATCH 016/131] apiv3 add create url --- aster-finance-futures-api-v3.md | 10 +++++----- aster-finance-futures-api-v3_CN.md | 11 ++++++----- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/aster-finance-futures-api-v3.md b/aster-finance-futures-api-v3.md index fdc5f93..239fe52 100644 --- a/aster-finance-futures-api-v3.md +++ b/aster-finance-futures-api-v3.md @@ -247,11 +247,11 @@ if (timestamp < (serverTime + 1000) && (serverTime - timestamp) <= recvWindow){ #### The following parameters are API registration details. The values for user, signer, and privateKey are for demonstration purposes only (the privateKey corresponds to the signer). -| Key | Value | -| ---------- | ------------------------------------------------------------------ | -| user | 0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e | -| signer | 0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0 | -| privateKey | 0x4fd0a42218f3eae43a6ce26d22544e986139a01e5b34a62db53757ffca81bae1 | +| Key | Value | Desc +| ---------- | ------------------------------------------------------------------ | ---------- | +| user | 0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e |Login wallet address | +| signer | 0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0 |[Click Here](https://www.asterdex.com/en/api-wallet) | +| privateKey | 0x4fd0a42218f3eae43a6ce26d22544e986139a01e5b34a62db53757ffca81bae1 |[Click Here](https://www.asterdex.com/en/api-wallet) | #### The nonce parameter is the current system time in microseconds. If it exceeds the system time or lags behind it by more than 5 seconds, the request is considered invalid. diff --git a/aster-finance-futures-api-v3_CN.md b/aster-finance-futures-api-v3_CN.md index 8954424..edc124e 100644 --- a/aster-finance-futures-api-v3_CN.md +++ b/aster-finance-futures-api-v3_CN.md @@ -230,11 +230,12 @@ signature | 签名 #### 示例 : 以下参数为api注册信息,user,signer,privateKey仅供示范(privateKey为signer的私钥) -Key | Value ------------- | ------------ -user | 0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e -signer | 0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0 -privateKey | 0x4fd0a42218f3eae43a6ce26d22544e986139a01e5b34a62db53757ffca81bae1 + +Key | Value | Desc +------------ | ------------ | ------------ +user | 0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e | 登陆钱包地址 +signer | 0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0 | [点击这里获取](https://www.asterdex.com/zh-CN/api-wallet) +privateKey | 0x4fd0a42218f3eae43a6ce26d22544e986139a01e5b34a62db53757ffca81bae1 | [点击这里获取](https://www.asterdex.com/zh-CN/api-wallet) #### 示例 : nonce参数为当前系统微秒值,超过系统时间,或者落后系统时间超过5s为非法请求 ```python From 5a28f856faf5f18c808f14dda44ac5e0ddbad883 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Tue, 30 Sep 2025 20:24:10 +0800 Subject: [PATCH 017/131] add spotcancelall --- aster-finance-spot-api.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/aster-finance-spot-api.md b/aster-finance-spot-api.md index 9c96310..4a5d982 100644 --- a/aster-finance-spot-api.md +++ b/aster-finance-spot-api.md @@ -1139,6 +1139,36 @@ Retrieve all current open orders for trading pairs. Use calls without a trading ] ``` +## Cancel All Open Orders (TRADE) + +> **Response** + +```javascript +{ + "code": 200, + "msg": "The operation of cancel all open order is done." +} +``` + +`` +DEL /api/v1/allOpenOrders (HMAC SHA256) +`` + +**Weight:** +- ***1*** + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +orderIdList | STRING | NO | orderid array string +origClientOrderIdList | STRING | NO | clientOrderId array string +recvWindow | LONG | NO | +timestamp | LONG | YES | + + + `GET /api/v1/allOrders (HMAC SHA256)` Retrieve all account orders; active, canceled, or completed. From cc5ca871caf43aea1fbe8e0fa0f6de5047224d2b Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Wed, 1 Oct 2025 11:14:31 +0800 Subject: [PATCH 018/131] v3 go demo --- README.md | 8 +- v3-demo/main.go | 347 ++++++++++++++++++++++++++++++++++++++++++++++++ v3-demo/tx.py | 5 + 3 files changed, 358 insertions(+), 2 deletions(-) create mode 100644 v3-demo/main.go diff --git a/README.md b/README.md index a4ad5df..2e2047c 100644 --- a/README.md +++ b/README.md @@ -14,9 +14,13 @@ [Aster Finance Futures API V3 文档](./aster-finance-futures-api-v3_CN.md) -# Aster Finance Futures API V3 DEMO +# Aster Finance Futures API V3 PYTHON DEMO -[Aster Finance Futures API V3 DEMO](./v3-demo/tx.py) +[Aster Finance Futures API V3 PYTHON DEMO](./v3-demo/tx.py) + +# Aster Finance Futures API V3 GO DEMO + +[Aster Finance Futures API V3 GO DEMO](./v3-demo/main.go) # API Documentation for Aster Finance Spot diff --git a/v3-demo/main.go b/v3-demo/main.go new file mode 100644 index 0000000..54b8b6c --- /dev/null +++ b/v3-demo/main.go @@ -0,0 +1,347 @@ +package main + +import ( + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "math/big" + "net/http" + "net/url" + "sort" + "strconv" + "strings" + "time" + + "github.com/ethereum/go-ethereum/accounts/abi" + "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/crypto" +) + +//go version go1.24.1 darwin/arm64 +var ( + //your main wallet address (eoa) + //你的登陆钱包地址(erc20) + user = "*****" + //please get these parameters from https://www.asterdex.com/en/api-wallet + //下面这些参数在这里生成配置 https://www.asterdex.com/zh-CN/api-wallet + signer = "*******" + priKeyHex = "********" + + //请求的域名 + host = "https://fapi.asterdex.com" + cli = &http.Client{ + Timeout: 15 * time.Second, + } +) + +var placeOrder = map[string]interface{}{ + "url": "/fapi/v3/order", + "method": "POST", + "params": map[string]interface{}{ + "symbol": "BTCUSDT", + "positionSide": "BOTH", + "type": "LIMIT", + "side": "BUY", + "timeInForce": "GTC", + "quantity": "0.01", + "price": "110000.2", + }, +} + +var getOrder = map[string]interface{}{ + "url": "/fapi/v3/order", + "method": "GET", + "params": map[string]interface{}{ + "symbol": "SANDUSDT", + "orderId": "2194215", + "side": "BUY", + "type": "LIMIT", + }, +} + +func main() { + //get an order + if err := call(getOrder); err != nil { + fmt.Println("call failed:", err) + } + //place an order + if err := call(placeOrder); err != nil { + fmt.Println("call failed:", err) + } +} + +func call(api map[string]interface{}) error { + nonce := genNonce() + fmt.Println("nonce:", nonce) + // 复制一份 params,以免修改全局模板 + params := cloneInterface(api["params"]) + paramsMap, ok := params.(map[string]interface{}) + if !ok { + return errors.New("params must be map[string]interface{}") + } + + // sign 会修改 paramsMap(加入 user, signer, signature, timestamp, recvWindow) + if err := sign(paramsMap, nonce); err != nil { + return err + } + + // 发送请求 + urlPath, _ := api["url"].(string) + method, _ := api["method"].(string) + fullUrl := strings.TrimRight(host, "/") + urlPath + respBody, statusCode, err := send(fullUrl, method, paramsMap) + if err != nil { + return err + } + fmt.Printf("HTTP %d response: %s\n", statusCode, respBody) + return nil +} + +// sign 将在 params 中添加 timestamp, recvWindow, user, signer, signature +func sign(params map[string]interface{}, nonce uint64) error { + // 添加 recvWindow 和 timestamp (毫秒) + params["recvWindow"] = "50000" + timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10) + //params["timestamp"] = "1759212310710" + params["timestamp"] = timestamp + + // 先做确定性的序列化(递归按 key 排序) + trimmed, err := normalizeAndStringify(params) + if err != nil { + return err + } + // trimmed 是 string,作为第一个 ABI 参数 + // 构造 ABI: (string, address, address, uint256) + argString := trimmed + fmt.Println(argString) + addrUser := common.HexToAddress(user) + addrSigner := common.HexToAddress(signer) + nonceBig := new(big.Int).SetUint64(nonce) + + // 定义 abi types + tString, err := abi.NewType("string", "", nil) + if err != nil { + return err + } + tAddress, err := abi.NewType("address", "", nil) + if err != nil { + return err + } + tUint256, err := abi.NewType("uint256", "", nil) + if err != nil { + return err + } + arguments := abi.Arguments{ + {Type: tString}, + {Type: tAddress}, + {Type: tAddress}, + {Type: tUint256}, + } + + // Pack + packed, err := arguments.Pack(argString, addrUser, addrSigner, nonceBig) + if err != nil { + return fmt.Errorf("abi pack error: %w", err) + } + + fmt.Println(hex.EncodeToString(packed)) + + // keccak256 + hash := crypto.Keccak256(packed) + + fmt.Println(hex.EncodeToString(hash)) + + prefixedMsg := fmt.Sprintf("\x19Ethereum Signed Message:\n%d%s", len(hash), hash) + + // 2. keccak256 哈希 + msgHash := crypto.Keccak256Hash([]byte(prefixedMsg)) + // Load private key + privKey, err := crypto.HexToECDSA(strings.TrimPrefix(priKeyHex, "0x")) + if err != nil { + return fmt.Errorf("invalid private key: %w", err) + } + + // Sign the hash (returns 65 bytes: R(32)|S(32)|V(1)) + sig, err := crypto.Sign(msgHash.Bytes(), privKey) + if err != nil { + return fmt.Errorf("sign error: %w", err) + } + + // crypto.Sign returns v as 0/1 in last byte — convert to 27/28 + if len(sig) != 65 { + return fmt.Errorf("unexpected signature length: %d", len(sig)) + } + sig[64] += 27 + + // hex-encode with 0x prefix + sigHex := "0x" + hex.EncodeToString(sig) + + // 将 user、signer、signature 插入 params + params["user"] = user + params["signer"] = signer + params["signature"] = sigHex + + //把 nonce 也放回 params + params["nonce"] = nonce + + fmt.Println("signature:", hex.EncodeToString(sig)) + + return nil +} + +// send HTTP 请求:POST -> body JSON; GET/DELETE -> params放 querystring +func send(fullUrl string, method string, params map[string]interface{}) (string, int, error) { + method = strings.ToUpper(method) + switch method { + case "POST": + form := url.Values{} + for k, v := range params { + form.Set(k, fmt.Sprintf("%v", v)) // interface{} -> string + } + req, err := http.NewRequest("POST", fullUrl, strings.NewReader(form.Encode())) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + resp, err := cli.Do(req) + if err != nil { + return "", 0, err + } + defer resp.Body.Close() + body, _ := io.ReadAll(resp.Body) + return string(body), resp.StatusCode, nil + case "GET", "DELETE": + // 把 params 放到 querystring(递归转成 key=val 的方式;此处做最简单的 flat 化) + q := url.Values{} + flattenParams("", params, &q) + u, _ := url.Parse(fullUrl) + u.RawQuery = q.Encode() + fmt.Println(u.String()) + req, _ := http.NewRequest(method, u.String(), nil) + resp, err := cli.Do(req) + if err != nil { + return "", 0, err + } + defer resp.Body.Close() + body, _ := io.ReadAll(resp.Body) + return string(body), resp.StatusCode, nil + default: + return "", 0, fmt.Errorf("unsupported http method: %s", method) + } +} + +// flattenParams 将 map 递归展平成 query params +func flattenParams(prefix string, v interface{}, q *url.Values) { + switch val := v.(type) { + case map[string]interface{}: + // 保持 key 排序,确定性 + keys := make([]string, 0, len(val)) + for k := range val { + keys = append(keys, k) + } + sort.Strings(keys) + for _, k := range keys { + nk := k + if prefix != "" { + nk = prefix + "." + k + } + flattenParams(nk, val[k], q) + } + case []interface{}: + for i, item := range val { + nk := fmt.Sprintf("%s[%d]", prefix, i) + flattenParams(nk, item, q) + } + case string: + q.Add(prefix, val) + case bool: + q.Add(prefix, fmt.Sprintf("%v", val)) + case float64: + // JSON decode 默认数值为 float64 + q.Add(prefix, fmt.Sprintf("%v", val)) + case nil: + // skip nil + default: + // 尝试格式化为 string + q.Add(prefix, fmt.Sprintf("%v", val)) + } +} + +// normalizeAndStringify 对 map 做确定性序列化(按 key 排序),返回 string +func normalizeAndStringify(v interface{}) (string, error) { + // 先把 v 变成一个 deterministic structure,然后 json.Marshal + norm, err := normalize(v) + if err != nil { + return "", err + } + bs, err := json.Marshal(norm) + if err != nil { + return "", err + } + return string(bs), nil +} + +// normalize 将 map/array 中的键按字母序排序并递归处理 +func normalize(v interface{}) (interface{}, error) { + switch val := v.(type) { + case map[string]interface{}: + keys := make([]string, 0, len(val)) + for k := range val { + keys = append(keys, k) + } + sort.Strings(keys) + //out := make([]interface{}, 0, len(keys)) + // 为了保证 JSON 有键名,我们重建为 map 并按顺序添加 + newMap := make(map[string]interface{}, len(keys)) + for _, k := range keys { + nv, err := normalize(val[k]) + if err != nil { + return nil, err + } + newMap[k] = nv + } + // 返回按 key 排序的 map(Marshal 时 map 的顺序并不保证,但我们已按 key 插入;若你需要绝对保证,请把结果改为 []kv 的形式) + return newMap, nil + case map[interface{}]interface{}: + // unlikely in JSON-decoded, 但处理一下 + keys := make([]string, 0, len(val)) + for k := range val { + keys = append(keys, fmt.Sprint(k)) + } + sort.Strings(keys) + newMap := make(map[string]interface{}, len(keys)) + for _, k := range keys { + newMap[k] = val[k] + } + return normalize(newMap) + case []interface{}: + out := make([]interface{}, 0, len(val)) + for _, it := range val { + nv, err := normalize(it) + if err != nil { + return nil, err + } + out = append(out, nv) + } + return out, nil + default: + // 基本类型直接返回 + return val, nil + } +} + +// cloneInterface 做浅拷贝(仅用于顶层 params) +func cloneInterface(v interface{}) interface{} { + // 通过 json marshal/unmarshal 做深拷贝(简单可靠) + bs, err := json.Marshal(v) + if err != nil { + return v + } + var out interface{} + _ = json.Unmarshal(bs, &out) + return out +} + +func genNonce() uint64 { + micro := time.Now().UnixMicro() + return uint64(micro) +} diff --git a/v3-demo/tx.py b/v3-demo/tx.py index a0ae4ee..ce386cd 100644 --- a/v3-demo/tx.py +++ b/v3-demo/tx.py @@ -16,7 +16,12 @@ from eth_account.messages import encode_defunct from web3 import Web3 +#your main wallet address (eoa) +#你的登陆钱包地址(erc20) user = '0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e' + +#please get these parameters from https://www.asterdex.com/en/api-wallet +#下面这些参数在这里生成配置 https://www.asterdex.com/zh-CN/api-wallet signer='0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0' priKey = "0x4fd0a42218f3eae43a6ce26d22544e986139a01e5b34a62db53757ffca81bae1" From 2363ab9b033a7b02eca2957d3218faf0996956c6 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Fri, 3 Oct 2025 10:37:43 +0800 Subject: [PATCH 019/131] get all orders for spot --- aster-finance-spot-api.md | 53 ++++++++++++++++++------------------ aster-finance-spot-api_CN.md | 43 +++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 27 deletions(-) diff --git a/aster-finance-spot-api.md b/aster-finance-spot-api.md index 4a5d982..f1497ac 100644 --- a/aster-finance-spot-api.md +++ b/aster-finance-spot-api.md @@ -1112,33 +1112,6 @@ Retrieve all current open orders for trading pairs. Use calls without a trading * If the symbol parameter is not provided, it will return the order books for all trading pairs. -## Query all orders (USER\_DATA) - -**Response** - -```javascript -[ - { - "orderId": 349661, - "symbol": "BNBUSDT", - "status": "NEW", - "clientOrderId": "LzypgiMwkf3TQ8wwvLo8RA", - "price": "1.10000000", - "avgPrice": "0.0000000000000000", - "origQty": "5",   - "executedQty": "0", - "cumQuote": "0", - "timeInForce": "GTC", - "type": "LIMIT", - "side": "BUY", - "stopPrice": "0", - "origType": "LIMIT", - "time": 1756252940207, - "updateTime": 1756252940207, - } -] -``` - ## Cancel All Open Orders (TRADE) > **Response** @@ -1168,6 +1141,32 @@ recvWindow | LONG | NO | timestamp | LONG | YES | +## Query all orders (USER\_DATA) + +**Response** + +```javascript +[ + { + "orderId": 349661, + "symbol": "BNBUSDT", + "status": "NEW", + "clientOrderId": "LzypgiMwkf3TQ8wwvLo8RA", + "price": "1.10000000", + "avgPrice": "0.0000000000000000", + "origQty": "5",   + "executedQty": "0", + "cumQuote": "0", + "timeInForce": "GTC", + "type": "LIMIT", + "side": "BUY", + "stopPrice": "0", + "origType": "LIMIT", + "time": 1756252940207, + "updateTime": 1756252940207, + } +] +``` `GET /api/v1/allOrders (HMAC SHA256)` diff --git a/aster-finance-spot-api_CN.md b/aster-finance-spot-api_CN.md index d702289..3fd7663 100644 --- a/aster-finance-spot-api_CN.md +++ b/aster-finance-spot-api_CN.md @@ -1309,6 +1309,49 @@ timestamp | LONG | YES |   * 默认查询最近7天内的数据 + +`` +GET /api/v1/transactionHistory (HMAC SHA256) +`` +> **响应** + +```javascript +[ + { + "tranId": 1759115482304540227, //划转ID + "tradeId": null, //流水ID + "asset": "ASTER", //资产 + "symbol": "", //交易对 + "balanceDelta": "-500.00000000", //资金流数量,正数代表流入,负数代表流出 + "balanceInfo": "TRADE_SOURCE", //流水描述 + "time": 1759115482000, // 时间 + "type": "TRADE_SOURCE" //资金流类型 + } +] +``` + +查询交易流水 + +**权重:** +30 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +asset | STRING | NO | 资产 +type | STRING | NO | 类别 +startTime | LONG | NO | 开始时间 +endTime | LONG | NO | 结束时间 +limit | LONG | NO | 返回的结果集数量 默认值:100 最大值:1000 +recvWindow | LONG | NO | +timestamp | LONG | YES | + +注意: + +* `type` 取值 `TRADE_TARGET`,`TRADE_SOURCE`,`TRANSFER_SPOT_TO_FUTURE`,`TRANSFER_FUTURE_TO_SPOT`,`TRANSFER_SPOT_TO_SPOT`,`AIRDROP`,`DIVIDEND`,`TRANSFER_REFUND`,`INTERNAL_TRANSFER`,`TRANSFER`,`SWAP`,`COMMISSION_REBATE`,`CASH_BACK` 中的一种 +* 如果`startTime` 和 `endTime` 均未发送, 只会返回最近7天的数据。 + ## 期货现货互转 (TRADE) > **响应:** From f5c4fd446e33abf59e0aa2d4d510cf178e891777 Mon Sep 17 00:00:00 2001 From: aodyc Date: Fri, 17 Oct 2025 22:27:23 +0800 Subject: [PATCH 020/131] add api-key docs --- .gitignore | 1 + .idea/workspace.xml | 70 --------------------- README.md | 5 ++ aster-broker-api-key-registration.md | 92 ++++++++++++++++++++++++++++ 4 files changed, 98 insertions(+), 70 deletions(-) create mode 100644 .gitignore delete mode 100644 .idea/workspace.xml create mode 100644 aster-broker-api-key-registration.md diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..485dee6 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.idea diff --git a/.idea/workspace.xml b/.idea/workspace.xml deleted file mode 100644 index 8f7afdb..0000000 --- a/.idea/workspace.xml +++ /dev/null @@ -1,70 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - 1750167841562 - - - - - - - - - - true - - \ No newline at end of file diff --git a/README.md b/README.md index 2e2047c..856f478 100644 --- a/README.md +++ b/README.md @@ -38,4 +38,9 @@ [Aster 现货资产归集脚本示例](./consolidation.js) +# Aster-Broker API Key 注册 + +[Aster-Broker API Key 注册](./aster-broker-api-key-registration.md) + + diff --git a/aster-broker-api-key-registration.md b/aster-broker-api-key-registration.md new file mode 100644 index 0000000..ca0b3e3 --- /dev/null +++ b/aster-broker-api-key-registration.md @@ -0,0 +1,92 @@ +# 1. get nonce + +### request: + +```shell +curl --location 'https://www.asterdex.com/bapi/futures/v1/public/future/web3/get-nonce' \ +--header 'Content-Type: application/json' \ +--data '{ +"sourceAddr" : "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", +"type": "CREATE_API_KEY" +} +``` + +### response: +```json +{ + "code": "000000", + "message": null, + "messageDetail": null, + "data": { + "nonce": "501182" + }, + "success": true +} +``` + +# 2. sign message + +### message: + +```text +You are signing into Aster DEX 501182 +``` + +### result: + +```text +0xa4ee6b068060caeac447216b592a918b085642056248e6ff50ba22b50e8884875ead28f06cbcefcbb93d03997f807fd242354d878756f4690f791ae8dbfcde841c +``` + +# 3. create api-key + +### request: + +```shell +curl --location 'https://www.asterdex.com/bapi/futures/v1/public/future/web3/broker-create-api-key' \ +--header 'accept: */*' \ +--header 'Content-Type: application/json' \ +--data '{ +"desc": "test description", +"ip": "", +"network": "56", +"signature": "0xa4ee6b068060caeac447216b592a918b085642056248e6ff50ba22b50e8884875ead28f06cbcefcbb93d03997f807fd242354d878756f4690f791ae8dbfcde841c", +"sourceAddr": "0xE90F9596e3Bfd49e9f4c2E0eA48830DC47e6997b", +"type": "CREATE_API_KEY", +"sourceCode": "broker" +}' +``` + +### params: + +|param | type | required | description | +|------|------|----------|-------------------------------------------| +| desc | string | yes | api-key's description, should unique | +| ip | string | no | whitelist ip addresses, separated by ',' | +| network | string | yes | blockchain network, e.g. '56' for BSC | +| signature | string | yes | signature from previous step | +| sourceAddr | string | yes | the address used to sign the message | +| type | string | yes | fixed value "CREATE_API_KEY" | +| sourceCode | string | no | "ae" for aster and other value for broker | + +### response: + +```json +{ + "code": "000000", + "message": null, + "messageDetail": null, + "data": { + "apiKey": "4a2e11b243b1ad75981edf359ae02e873bf88b699196170d998d8266f5eb9f32", + "apiSecret": "72911505f67b24a8efe8f246d06c324b787d2f3f7cb8b5b80ef1698ee1486e25", + "keyId": 0, + "apiName": null + }, + "success": true +} +``` + +### note: + +1. Please keep a record of the returned apiKey and apiSecret. If you lose them, you cannot retrieve them and can only create them again. +2. api-key can't be deleted by user now. \ No newline at end of file From fb87ca11eb5b9aaeb0055172b6c5f154c93cc471 Mon Sep 17 00:00:00 2001 From: mark Date: Sat, 18 Oct 2025 11:36:41 +0800 Subject: [PATCH 021/131] AP-5852 Adding dual side and fee burn update to ACCOUNT_CONFIG_UPDATE user ws push --- aster-finance-futures-api-v3.md | 4 +++- aster-finance-futures-api-v3_CN.md | 4 +++- aster-finance-futures-api.md | 4 +++- aster-finance-futures-api_CN.md | 4 +++- 4 files changed, 12 insertions(+), 4 deletions(-) diff --git a/aster-finance-futures-api-v3.md b/aster-finance-futures-api-v3.md index 239fe52..98ef163 100644 --- a/aster-finance-futures-api-v3.md +++ b/aster-finance-futures-api-v3.md @@ -3854,7 +3854,9 @@ event type is `ORDER_TRADE_UPDATE`. "E":1611646737479, // Event Time "T":1611646737476, // Transaction Time "ai":{ // User's Account Configuration - "j":true // Multi-Assets Mode + "j":true, // Multi-Assets Mode + "f":true, // Specified token fee deduction + "d":true // Position mode: true for dual-side (hedge) mode, false for single-side (one-way) mode } } ``` diff --git a/aster-finance-futures-api-v3_CN.md b/aster-finance-futures-api-v3_CN.md index edc124e..649a3fe 100644 --- a/aster-finance-futures-api-v3_CN.md +++ b/aster-finance-futures-api-v3_CN.md @@ -4013,7 +4013,9 @@ None "E":1611646737479, // 事件时间 "T":1611646737476, // 撮合时间 "ai":{ // 用户账户配置 - "j":true // 联合保证金状态 + "j":true, // 联合保证金状态 + "f":true, // 指定币种抵扣手续费 + "d":true // 持仓模式 true 为双向持仓模式, false为单向持仓模式 } } ``` diff --git a/aster-finance-futures-api.md b/aster-finance-futures-api.md index 0746110..b98bb1c 100644 --- a/aster-finance-futures-api.md +++ b/aster-finance-futures-api.md @@ -3992,7 +3992,9 @@ event type is `ORDER_TRADE_UPDATE`. "E":1611646737479, // Event Time "T":1611646737476, // Transaction Time "ai":{ // User's Account Configuration - "j":true // Multi-Assets Mode + "j":true, // Multi-Assets Mode + "f":true, // Specified token fee deduction + "d":true // Position mode: true for dual-side (hedge) mode, false for single-side (one-way) mode } } ``` diff --git a/aster-finance-futures-api_CN.md b/aster-finance-futures-api_CN.md index 493888c..a0de164 100644 --- a/aster-finance-futures-api_CN.md +++ b/aster-finance-futures-api_CN.md @@ -3867,7 +3867,9 @@ None "E":1611646737479, // 事件时间 "T":1611646737476, // 撮合时间 "ai":{ // 用户账户配置 - "j":true // 联合保证金状态 + "j":true, // 联合保证金状态 + "f":true, // 指定币种抵扣手续费 + "d":true // 持仓模式 true 为双向持仓模式, false为单向持仓模式 } } ``` From 269cc5d7e9d79fdf509be0e5b899897f2e4ad6e2 Mon Sep 17 00:00:00 2001 From: aodyc Date: Sat, 18 Oct 2025 16:04:03 +0800 Subject: [PATCH 022/131] add new documents: 1. aster-api-key 2. aster-deposit-withdraw 3. aster-broker-deposit-withdraw --- README.md | 4 + aster-broker-api-key-registration.md | 45 +++- aster-broker-deposit-withdrawal.md | 276 +++++++++++++++++++++++ aster-deposit-withdrawal.md | 326 +++++++++++++++++++++++++++ 4 files changed, 650 insertions(+), 1 deletion(-) create mode 100644 aster-broker-deposit-withdrawal.md create mode 100644 aster-deposit-withdrawal.md diff --git a/README.md b/README.md index 856f478..df5f16a 100644 --- a/README.md +++ b/README.md @@ -42,5 +42,9 @@ [Aster-Broker API Key 注册](./aster-broker-api-key-registration.md) +# Aster 充值提现 +[Aster Deposit and Withdrawal](./aster-deposit-withdrawal.md) +# Aster-Broker 充值提现 +[Aster-Broker Deposit and Withdrawal](./aster-broker-deposit-withdrawal.md) diff --git a/aster-broker-api-key-registration.md b/aster-broker-api-key-registration.md index ca0b3e3..946cee4 100644 --- a/aster-broker-api-key-registration.md +++ b/aster-broker-api-key-registration.md @@ -38,7 +38,50 @@ You are signing into Aster DEX 501182 0xa4ee6b068060caeac447216b592a918b085642056248e6ff50ba22b50e8884875ead28f06cbcefcbb93d03997f807fd242354d878756f4690f791ae8dbfcde841c ``` -# 3. create api-key +# 3. login + +### request: +```shell +curl 'https://www.apollox.finance/bapi/futures/v1/public/future/web3/loginReturnAccount' \ + + -H 'content-type: application/json' \ + --data-raw '{ + "signature":"0xafb84ca3bd36131970636a298677be2e1de4ed81b11101e417272d23f0b7f9af174efdf954ae7a63e844c83d16a4ad391e801c6766a422e647832b5c0c8aa1591c", + "sourceAddr":"0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", + "chainId":56, + "sourceCode": "broker", + "agentCode": "ce6maa" + }' +``` + +### params: + +|param | type | required | description | +|------|------|----------|----------------------------------------| +| signature | string | yes | signature from previous step | +| sourceAddr | string | yes | the address used to sign the message | +| chainId | int | yes | blockchain network id, e.g. 56 for BSC | +| sourceCode | string | no | broker's name | +| agentCode | string | no | broker's referral code | + +### response: + +```json +{ + "code": "000000", + "message": null, + "messageDetail": null, + "data": { + "uid": 12345678, + "fuid": 12345678, + "accountId": 12345678 + }, + "success": true +} +``` + + +# 4. create api-key ### request: diff --git a/aster-broker-deposit-withdrawal.md b/aster-broker-deposit-withdrawal.md new file mode 100644 index 0000000..be0aead --- /dev/null +++ b/aster-broker-deposit-withdrawal.md @@ -0,0 +1,276 @@ +# # 1. get all deposit assets + +### request: + +```shell +curl 'https://www.asterdex.com/bapi/futures/v1/public/future/apx/deposit/assets?chainIds=56&networks=EVM' +``` + +### params: +|param | type | required | description | +|-----------|--------|----------|------------------------------------------------------------------------| +| chainIds | string | true | Chain ID, multiple IDs separated by commas | +| networks | string | false | Network type, e.g., EVM, SOLANA, multiple networks separated by commas | + +### response: + +```json +{ + "code": "000000", + "message": null, + "messageDetail": null, + "data": [ + { + "name": "ASTER", + "displayName": "ASTER", + "contractAddress": "0x000ae314e2a2172a039b26378814c252734f556a", + "decimals": 18, + "network": "EVM", + "chainId": 56, + "depositType": "normal", + "rank": 10, + "isNative": false, + "admin": null, + "bank": null, + "tokenVaultAuthority": null, + "tokenVault": null, + "tokenMint": null, + "associatedTokenProgram": null, + "tokenProgram": null, + "systemProgram": null, + "ixSysvar": null, + "priceFeed": null, + "priceFeedProgram": null, + "solVault": null + } + ], + "success": true +} +``` + +# 2. get all withdraw assets + +### request: + +```shell +curl 'https://www.asterdex.com/bapi/futures/v1/public/future/apx/withdraw/assets?chainIds=56&networks=EVM' +``` + +### params: +|param | type | required | description | +|-----------|--------|----------|------------------------------------------------------------------------| +| chainIds | string | true | Chain ID, multiple IDs separated by commas | +| networks | string | false | Network type, e.g., EVM, SOLANA, multiple networks separated by commas | + +### response: + +```json +{ + "code": "000000", + "message": null, + "messageDetail": null, + "data": [ + { + "name": "ASTER", + "displayName": "ASTER", + "contractAddress": "0x000ae314e2a2172a039b26378814c252734f556a", + "decimals": 18, + "network": "EVM", + "chainId": 56, + "withdrawType": "autoWithdraw", + "rank": 10, + "isNative": false, + "isProfit": true, + "admin": null, + "bank": null, + "tokenVaultAuthority": null, + "tokenVault": null, + "tokenMint": null, + "associatedTokenProgram": null, + "tokenProgram": null, + "systemProgram": null, + "ixSysvar": null, + "priceFeed": null, + "priceFeedProgram": null, + "solVault": null + } + ], + "success": true +} +``` + +# 3. estimate withdraw fee + +### request: + +```shell +curl 'https://www.asterdex.com/bapi/futures/v1/public/future/apx/estimate-withdraw-fee?chainId=56&network=EVM¤cy=ASTER' +``` + +### params: + +|param | type | required | description | +|------------|--------|----------|------------------------------| +| chainId | int | true | Chain ID | +| network | string | true | Network type, e.g., EVM, SOL | +| currency | string | true | Currency name, e.g., ASTER | + +### response: + +```json +{ + "code": "000000", + "message": null, + "messageDetail": null, + "data": { + "gasPrice": null, + "gasLimit": 200000, + "nativePrice": null, + "tokenPrice": 1.12357820, + "gasCost": 0.0891, + "gasUsdValue": 0.1 + }, + "success": true +} +``` + +- gasCost: Estimated withdrawal fee in token units + +# 4. withdraw signature + +* when you withdraw, you should supply a EIP712 signature. You can get the signature by signing the following message with your wallet. + +### EIP712 Domain + +```json +{ + "name": "APX", + "version": "1", + "chainId": 56, + "verifyingContract": "0xcEF2dD45Da08b37fB1c2f441d33c2eBb424866A4" +} +``` + +|field| desc | +|---|-------------------------------| +|name| fix string 'Aster' | +|version| fix string '1' | +|chainId| the chainId of withdraw chain | +|verifyingContract| contract address, see below | + +### EIP712 Types + +```json +{ + "Action": [ + {"name": "type", "type": "string"}, + {"name": "destination", "type": "address"}, + {"name": "destination Chain", "type": "string"}, + {"name": "token", "type": "string"}, + {"name": "amount", "type": "string"}, + {"name": "fee", "type": "string"}, + {"name": "nonce", "type": "uint256"} + ] +} +``` + +|field | desc | +|---------------|-------------------------------------------------------------------------------------------------------| +|type | fix string 'Withdraw' | +|destination | the receipt address, should be user's register address | +|destination Chain | the chain name of receipt address, you can see the defination of chainName below | +|token| the name of the currency user withdraw, e.g. ASTER, you can get the name from withdraw/asset API | +|amount | the amount user withdraw in token unit, eg. '1.23' | +|fee| the fee user will pay in token unit, eg. '0.01' (you can get the fee from withdraw/estimate-withdraw-fee API) | +|nonce| a unique number, use the current timestamp in milliseconds and multiply '1000' | + +### chainName definition + +|chainId| chainName | contractAddress | +|---|-----------|-----------------| +|56| BSC | 0xcEF2dD45Da08b37fB1c2f441d33c2eBb424866A4 | +|42161| Arbitrum | 0xBAd4ccc91EF0dfFfbCAb1402C519601fbAf244EF | +|1| ETH | 0xb40EEd68d7d6B3b6d6f4E93DE6239B7C53EFc786 | +|8453|Base| 0x11db0BEb34766277a1d7CAc7590b3Cf4BBf5E4eB | +|324|zkSync| 0xD6f4e33063C881cE9a98e07E13673B92a637D908 | +|169|Manta| 0xBAd4ccc91EF0dfFfbCAb1402C519601fbAf244EF | + +# 5. withdraw + +### request: + +```shell +curl -X POST "https://www.asterdex.com/bapi/futures/v1/private/future/apx/user-withdraw" -H "accept: */*" -H "x-gray-env: normal" -H "x-trace-id: fa2a5961b4a346e083f2bb0bffe39e2f" -H "Content-Type: application/json" \ +-d "{ \"accountType\": \"spot\", \"amount\": \"10.2\", \"chainId\": 97, \"currency\": \"USDT\", \"fee\": \"0.01\", \"nonce\": \"1761029928213000\", \"receiver\": \"0x4C5EdB66CC7626a1C92d5178c3E5c45409BcE6D7\", \"userSignature\": \"0xc0299efe235ec194d070163b1f92ebf5d01bd820c1c08fa9730929c7a36172a9001b99203b2f9997aa7d41b7658348704e0515f4c40e76f1892f7a5b0af31daa1c\"}" +``` + +### params: +|param | type | required | description | +|--------------|--------|----------|-----------------------------------------------------------| +| accountType | string | true | Account type, e.g., spot, perp | +| amount | string | true | Withdraw amount in token unit | +| chainId | int | true | Chain ID | +| currency | string | true | Currency name, e.g., ASTER | +| fee | string | true | Withdraw fee in token unit | +| nonce | string | true | Unique number, should be the save in signature | +| receiver | string | true | Withdraw receipt address, should be the save in signature | +| userSignature | string | true | EIP712 signature | + +### response: + +```json +{ + "code": "200", + "message": "success", + "messageDetail": null, + "data": { + "withdrawId": "1234567", + "hash": "0x9a40f0119b670fb6b155744b51981f91c4c4c8a20c333441a63853fe7d055c90" + }, + "success": true +} +``` + +|field | desc | +|-----------|--------------------------------------| +|withdrawId | the withdraw request id, a unique id | +|hash | the digest of user's signature | + +# 6. withdraw by API [futures] + +### request: + +```shell +curl 'https://fapi.asterdex.com/fapi/apx/user-withdraw?asset=USDT&amount=10.2&chainId=56&fee=0.01&nonce=1761029928213000&receiver=0x4C5EdB66CC7626a1C92d5178c3E5c45409BcE6D7&receiver=0x4C5EdB66CC7626a1C92d5178c3E5c45409BcE6D7&userSignature=0xc0299efe235ec194d070163b1f92ebf5d01bd820c1c08fa9730929c7a36172a9001b99203b2f9997aa7d41b7658348704e0515f4c40e76f1892f7a5b0af31daa1c' +``` + +### params: +| param | type | required | description | +|---------------|--------|----------|-----------------------------------------------------------| +| amount | string | true | Withdraw amount in token unit | +| chainId | int | true | Chain ID | +| asset | string | true | Currency name, e.g., ASTER | +| fee | string | true | Withdraw fee in token unit | +| nonce | string | true | Unique number, should be the save in signature | +| receiver | string | true | Withdraw receipt address, should be the save in signature | +| userSignature | string | true | EIP712 signature | + +### response: + +```json +{ + "code": "200", + "message": "success", + "messageDetail": null, + "data": { + "withdrawId": "1234567", + "hash": "0x9a40f0119b670fb6b155744b51981f91c4c4c8a20c333441a63853fe7d055c90" + }, + "success": true +} +``` + +|field | desc | +|-----------|--------------------------------------| +|withdrawId | the withdraw request id, a unique id | +|hash | the digest of user's signature | diff --git a/aster-deposit-withdrawal.md b/aster-deposit-withdrawal.md new file mode 100644 index 0000000..5e458ce --- /dev/null +++ b/aster-deposit-withdrawal.md @@ -0,0 +1,326 @@ +# 1. get all deposit assets + +### request: + +```shell +curl 'https://www.asterdex.com/bapi/futures/v1/public/future/aster/deposit/assets?chainIds=56&networks=EVM&accountType=spot' +``` + +### params: +|param | type | required | description | +|-----------|--------|----------|------------------------------------------------------------------------| +| chainIds | string | true | Chain ID, multiple IDs separated by commas | +| networks | string | false | Network type, e.g., EVM, SOLANA, multiple networks separated by commas | +| accountType | string | true | Account type, e.g., spot, perp | + +### response: + +```json +{ + "code": "000000", + "message": null, + "messageDetail": null, + "data": [ + { + "name": "ASTER", + "displayName": "ASTER", + "contractAddress": "0x000ae314e2a2172a039b26378814c252734f556a", + "decimals": 18, + "network": "EVM", + "chainId": 56, + "depositType": "normal", + "rank": 10, + "isNative": false, + "admin": null, + "bank": null, + "tokenVaultAuthority": null, + "tokenVault": null, + "tokenMint": null, + "associatedTokenProgram": null, + "tokenProgram": null, + "systemProgram": null, + "ixSysvar": null, + "priceFeed": null, + "priceFeedProgram": null, + "solVault": null + } + ], + "success": true +} +``` + +# 2. get all withdraw assets + +### request: + +```shell +curl 'https://www.asterdex.com/bapi/futures/v1/public/future/aster/withdraw/assets?chainIds=56&networks=EVM&accountType=spot' +``` + +### params: +|param | type | required | description | +|-----------|--------|----------|------------------------------------------------------------------------| +| chainIds | string | true | Chain ID, multiple IDs separated by commas | +| networks | string | false | Network type, e.g., EVM, SOLANA, multiple networks separated by commas | +| accountType | string | true | Account type, e.g., spot, perp | + +### response: + +```json +{ + "code": "000000", + "message": null, + "messageDetail": null, + "data": [ + { + "name": "ASTER", + "displayName": "ASTER", + "contractAddress": "0x000ae314e2a2172a039b26378814c252734f556a", + "decimals": 18, + "network": "EVM", + "chainId": 56, + "withdrawType": "autoWithdraw", + "rank": 10, + "isNative": false, + "isProfit": true, + "admin": null, + "bank": null, + "tokenVaultAuthority": null, + "tokenVault": null, + "tokenMint": null, + "associatedTokenProgram": null, + "tokenProgram": null, + "systemProgram": null, + "ixSysvar": null, + "priceFeed": null, + "priceFeedProgram": null, + "solVault": null + } + ], + "success": true +} +``` + +# 3. estimate withdraw fee + +### request: + +```shell +curl 'https://www.asterdex.com/bapi/futures/v1/public/future/aster/estimate-withdraw-fee?chainId=56&network=EVM¤cy=ASTER&accountType=spot' +``` + +### params: + +|param | type | required | description | +|------------|--------|----------|------------------------------| +| chainId | int | true | Chain ID | +| network | string | true | Network type, e.g., EVM, SOL | +| currency | string | true | Currency name, e.g., ASTER | +| accountType | string | true | Account type, e.g., spot, perp | + +### response: + +```json +{ + "code": "000000", + "message": null, + "messageDetail": null, + "data": { + "gasPrice": null, + "gasLimit": 200000, + "nativePrice": null, + "tokenPrice": 1.12357820, + "gasCost": 0.0891, + "gasUsdValue": 0.1 + }, + "success": true +} +``` + +- gasCost: Estimated withdrawal fee in token units + +# 4. withdraw signature + +* when you withdraw, you should supply a EIP712 signature. You can get the signature by signing the following message with your wallet. + +### EIP712 Domain + +```json +{ + "name": "Aster", + "version": "1", + "chainId": 56, + "verifyingContract": "0x0000000000000000000000000000000000000000" +} +``` + +|field|desc| +|---|---| +|name|fix string 'Aster'| +|version|fix string '1'| +|chainId|the chainId of withdraw chain| +|verifyingContract|fix address: zero address| + +### EIP712 Types + +```json +{ + "Action": [ + {"name": "type", "type": "string"}, + {"name": "destination", "type": "address"}, + {"name": "destination Chain", "type": "string"}, + {"name": "token", "type": "string"}, + {"name": "amount", "type": "string"}, + {"name": "fee", "type": "string"}, + {"name": "nonce", "type": "uint256"}, + {"name": "aster chain", "type": "string"} + ] +} +``` + +|field | desc | +|---------------|-------------------------------------------------------------------------------------------------------| +|type | fix string 'Withdraw' | +|destination | the receipt address, should be user's register address | +|destination Chain | the chain name of receipt address, you can see the defination of chainName below | +|token| the name of the currency user withdraw, e.g. ASTER, you can get the name from withdraw/asset API | +|amount | the amount user withdraw in token unit, eg. '1.23' | +|fee| the fee user will pay in token unit, eg. '0.01' (you can get the fee from withdraw/estimate-withdraw-fee API) | +|nonce| a unique number, use the current timestamp in milliseconds and multiply '1000' | +|aster chain| fix string 'Mainnet' | + +### chainName definition + +|chainId| chainName | +|---|-----------| +|56| BSC | +|42161| Arbitrum | +|1| ETH | + +# 5. withdraw + +### request: + +```shell +curl -X POST "https://www.asterdex.com/bapi/futures/v1/private/future/aster/user-withdraw" -H "accept: */*" -H "x-gray-env: normal" -H "x-trace-id: fa2a5961b4a346e083f2bb0bffe39e2f" -H "Content-Type: application/json" \ +-d "{ \"accountType\": \"spot\", \"amount\": \"10.2\", \"chainId\": 97, \"currency\": \"USDT\", \"fee\": \"0.01\", \"nonce\": \"1761029928213000\", \"receiver\": \"0x4C5EdB66CC7626a1C92d5178c3E5c45409BcE6D7\", \"userSignature\": \"0xc0299efe235ec194d070163b1f92ebf5d01bd820c1c08fa9730929c7a36172a9001b99203b2f9997aa7d41b7658348704e0515f4c40e76f1892f7a5b0af31daa1c\"}" +``` + +### params: +|param | type | required | description | +|--------------|--------|----------|-----------------------------------------------------------| +| accountType | string | true | Account type, e.g., spot, perp | +| amount | string | true | Withdraw amount in token unit | +| chainId | int | true | Chain ID | +| currency | string | true | Currency name, e.g., ASTER | +| fee | string | true | Withdraw fee in token unit | +| nonce | string | true | Unique number, should be the save in signature | +| receiver | string | true | Withdraw receipt address, should be the save in signature | +| userSignature | string | true | EIP712 signature | + +### response: + +```json +{ + "code": "200", + "message": "success", + "messageDetail": null, + "data": { + "withdrawId": "1234567", + "hash": "0x9a40f0119b670fb6b155744b51981f91c4c4c8a20c333441a63853fe7d055c90" + }, + "success": true +} +``` + +|field | desc | +|-----------|--------------------------------------| +|withdrawId | the withdraw request id, a unique id | +|hash | the digest of user's signature | + +# 6. withdraw by API [futures] + +### request: + +```shell +curl 'https://fapi.asterdex.com/fapi/aster/user-withdraw?asset=USDT&amount=10.2&chainId=56&fee=0.01&nonce=1761029928213000&receiver=0x4C5EdB66CC7626a1C92d5178c3E5c45409BcE6D7&receiver=0x4C5EdB66CC7626a1C92d5178c3E5c45409BcE6D7&userSignature=0xc0299efe235ec194d070163b1f92ebf5d01bd820c1c08fa9730929c7a36172a9001b99203b2f9997aa7d41b7658348704e0515f4c40e76f1892f7a5b0af31daa1c' +``` + +### params: +| param | type | required | description | +|---------------|--------|----------|-----------------------------------------------------------| +| amount | string | true | Withdraw amount in token unit | +| chainId | int | true | Chain ID | +| asset | string | true | Currency name, e.g., ASTER | +| fee | string | true | Withdraw fee in token unit | +| nonce | string | true | Unique number, should be the save in signature | +| receiver | string | true | Withdraw receipt address, should be the save in signature | +| userSignature | string | true | EIP712 signature | + +### response: + +```json +{ + "code": "200", + "message": "success", + "messageDetail": null, + "data": { + "withdrawId": "1234567", + "hash": "0x9a40f0119b670fb6b155744b51981f91c4c4c8a20c333441a63853fe7d055c90" + }, + "success": true +} +``` + +|field | desc | +|-----------|--------------------------------------| +|withdrawId | the withdraw request id, a unique id | +|hash | the digest of user's signature | + +# 7. withdraw by API [spot] + +### request: + +```shell +curl -XPOST 'https://sapi.asterdex.com/api/v1/aster/user-withdraw' \ +-d '{ \ + "asset": "USDT" + "amount": "10.2", + "chainId": "56" + "fee": "0.01", + "nonce": "1761029928213000" + "receiver": "0x4C5EdB66CC7626a1C92d5178c3E5c45409BcE6D7", + "userSignature": "0xc0299efe235ec194d070163b1f92ebf5d01bd820c1c08fa9730929c7a36172a9001b99203b2f9997aa7d41b7658348704e0515f4c40e76f1892f7a5b0af31daa1c" \ +}' +``` + +### params: +| param | type | required | description | +|---------------|--------|----------|-----------------------------------------------------------| +| amount | string | true | Withdraw amount in token unit | +| chainId | int | true | Chain ID | +| asset | string | true | Currency name, e.g., ASTER | +| fee | string | true | Withdraw fee in token unit | +| nonce | string | true | Unique number, should be the save in signature | +| receiver | string | true | Withdraw receipt address, should be the save in signature | +| userSignature | string | true | EIP712 signature | + +### response: + +```json +{ + "code": "200", + "message": "success", + "messageDetail": null, + "data": { + "withdrawId": "1234567", + "hash": "0x9a40f0119b670fb6b155744b51981f91c4c4c8a20c333441a63853fe7d055c90" + }, + "success": true +} +``` + +|field | desc | +|-----------|--------------------------------------| +|withdrawId | the withdraw request id, a unique id | +|hash | the digest of user's signature | \ No newline at end of file From a5a39ba116feefae9ef341f7377fb6c827e9dc2d Mon Sep 17 00:00:00 2001 From: aodyc Date: Thu, 23 Oct 2025 23:06:26 +0800 Subject: [PATCH 023/131] fix docs --- aster-broker-api-key-registration.md | 25 +++++++++++++------------ aster-broker-deposit-withdrawal.md | 4 +++- aster-deposit-withdrawal.md | 17 ++++++----------- 3 files changed, 22 insertions(+), 24 deletions(-) diff --git a/aster-broker-api-key-registration.md b/aster-broker-api-key-registration.md index 946cee4..bb6c8c4 100644 --- a/aster-broker-api-key-registration.md +++ b/aster-broker-api-key-registration.md @@ -42,27 +42,25 @@ You are signing into Aster DEX 501182 ### request: ```shell -curl 'https://www.apollox.finance/bapi/futures/v1/public/future/web3/loginReturnAccount' \ +curl -XPOST 'https://www.apollox.finance/bapi/futures/v1/public/future/web3/register-from-3party' \ -H 'content-type: application/json' \ --data-raw '{ "signature":"0xafb84ca3bd36131970636a298677be2e1de4ed81b11101e417272d23f0b7f9af174efdf954ae7a63e844c83d16a4ad391e801c6766a422e647832b5c0c8aa1591c", "sourceAddr":"0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", "chainId":56, - "sourceCode": "broker", - "agentCode": "ce6maa" + "sourceAgent": "broker" }' ``` ### params: -|param | type | required | description | -|------|------|----------|----------------------------------------| -| signature | string | yes | signature from previous step | -| sourceAddr | string | yes | the address used to sign the message | -| chainId | int | yes | blockchain network id, e.g. 56 for BSC | -| sourceCode | string | no | broker's name | -| agentCode | string | no | broker's referral code | +| param | type | required | description | +|-------------|------|----------|----------------------------------------| +| signature | string | yes | signature from previous step | +| sourceAddr | string | yes | the address used to sign the message | +| chainId | int | yes | blockchain network id, e.g. 56 for BSC | +| sourceAgent | string | no | broker's name | ### response: @@ -72,9 +70,12 @@ curl 'https://www.apollox.finance/bapi/futures/v1/public/future/web3/loginReturn "message": null, "messageDetail": null, "data": { + "apiKey": "D5M8792356G7H8J9K0L1N2B3V4C5X6Z7", + "apiSecret": "XXXXXXXX", + "keyId": 1234567, "uid": 12345678, - "fuid": 12345678, - "accountId": 12345678 + "address": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", + "apiName": "SafePal-Authorized" }, "success": true } diff --git a/aster-broker-deposit-withdrawal.md b/aster-broker-deposit-withdrawal.md index be0aead..5987812 100644 --- a/aster-broker-deposit-withdrawal.md +++ b/aster-broker-deposit-withdrawal.md @@ -241,7 +241,9 @@ curl -X POST "https://www.asterdex.com/bapi/futures/v1/private/future/apx/user-w ### request: ```shell -curl 'https://fapi.asterdex.com/fapi/apx/user-withdraw?asset=USDT&amount=10.2&chainId=56&fee=0.01&nonce=1761029928213000&receiver=0x4C5EdB66CC7626a1C92d5178c3E5c45409BcE6D7&receiver=0x4C5EdB66CC7626a1C92d5178c3E5c45409BcE6D7&userSignature=0xc0299efe235ec194d070163b1f92ebf5d01bd820c1c08fa9730929c7a36172a9001b99203b2f9997aa7d41b7658348704e0515f4c40e76f1892f7a5b0af31daa1c' +curl --location --request POST 'https://fapi.asterdex.com/fapi/apx/user-withdraw?chainId=56&asset=USDT&amount=31&fee=0.3&receiver=0xcEF2dD45Da08b37fB1c2f441d33c2eBb424866A4&nonce=1761210000000000&userSignature=0xde4ca529eef20db136eed1daf1d072083431d5279e6d6e219600cf57161c5e6d1232af3c8a8ef37ba8b5963f439ef9cc2b475fe18dcc3732dda9fb93c94a3abd1c&recvWindow=60000×tamp=1761230958410&signature=f5fd60da19be213d58914dd6f46bc400ada617fb916998dfc01dd346bfdad512' \ +--header 'Content-Type: application/json' \ +--header 'X-MBX-APIKEY: Your API KEY' ``` ### params: diff --git a/aster-deposit-withdrawal.md b/aster-deposit-withdrawal.md index 5e458ce..62d455e 100644 --- a/aster-deposit-withdrawal.md +++ b/aster-deposit-withdrawal.md @@ -243,7 +243,9 @@ curl -X POST "https://www.asterdex.com/bapi/futures/v1/private/future/aster/user ### request: ```shell -curl 'https://fapi.asterdex.com/fapi/aster/user-withdraw?asset=USDT&amount=10.2&chainId=56&fee=0.01&nonce=1761029928213000&receiver=0x4C5EdB66CC7626a1C92d5178c3E5c45409BcE6D7&receiver=0x4C5EdB66CC7626a1C92d5178c3E5c45409BcE6D7&userSignature=0xc0299efe235ec194d070163b1f92ebf5d01bd820c1c08fa9730929c7a36172a9001b99203b2f9997aa7d41b7658348704e0515f4c40e76f1892f7a5b0af31daa1c' +curl --location --request POST 'https://fapi.asterdex.com/fapi/apx/user-withdraw?chainId=56&asset=USDT&amount=31&fee=0.3&receiver=0x000ae314e2a2172a039b26378814c252734f556a&nonce=1761210000000000&userSignature=0xde4ca529eef20db136eed1daf1d072083431d5279e6d6e219600cf57161c5e6d1232af3c8a8ef37ba8b5963f439ef9cc2b475fe18dcc3732dda9fb93c94a3abd1c&recvWindow=60000×tamp=1761230958410&signature=f5fd60da19be213d58914dd6f46bc400ada610fb916998dfc01dd346bfdad512' \ +--header 'Content-Type: application/json' \ +--header 'X-MBX-APIKEY: Your API KEY' ``` ### params: @@ -282,16 +284,9 @@ curl 'https://fapi.asterdex.com/fapi/aster/user-withdraw?asset=USDT&amount=10.2& ### request: ```shell -curl -XPOST 'https://sapi.asterdex.com/api/v1/aster/user-withdraw' \ --d '{ \ - "asset": "USDT" - "amount": "10.2", - "chainId": "56" - "fee": "0.01", - "nonce": "1761029928213000" - "receiver": "0x4C5EdB66CC7626a1C92d5178c3E5c45409BcE6D7", - "userSignature": "0xc0299efe235ec194d070163b1f92ebf5d01bd820c1c08fa9730929c7a36172a9001b99203b2f9997aa7d41b7658348704e0515f4c40e76f1892f7a5b0af31daa1c" \ -}' +curl --location --request POST 'https://sapi.asterdex.com/api/v1/aster/user-withdraw?chainId=56&asset=ASTER&amount=1&fee=0.095&receiver=0x000ae314e2a2172a039b26378814c252734f556a&nonce=1761222960000000&userSignature=0x39051cc68de0fefb8e823259d3f7014fc787a8008b65d2a89d70defc48c3f91b35a4a819718c22ffcaeb143c8e1735621a0768d7c69e45ad8fbcf9bd315988423b&recvWindow=60000×tamp=1761230958410&signature=f5fd60da19be213d58914dd6f46bc400ada610fb916998dfc01dd346bfdad51' \ +--header 'Content-Type: application/json' \ +--header 'X-MBX-APIKEY: Your API KEY' ``` ### params: From 21417bce447f53c13daf90074283696593ea1c4b Mon Sep 17 00:00:00 2001 From: aodyc Date: Mon, 27 Oct 2025 16:43:46 +0800 Subject: [PATCH 024/131] fix path --- aster-deposit-withdrawal.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/aster-deposit-withdrawal.md b/aster-deposit-withdrawal.md index 62d455e..e69ef7c 100644 --- a/aster-deposit-withdrawal.md +++ b/aster-deposit-withdrawal.md @@ -243,7 +243,7 @@ curl -X POST "https://www.asterdex.com/bapi/futures/v1/private/future/aster/user ### request: ```shell -curl --location --request POST 'https://fapi.asterdex.com/fapi/apx/user-withdraw?chainId=56&asset=USDT&amount=31&fee=0.3&receiver=0x000ae314e2a2172a039b26378814c252734f556a&nonce=1761210000000000&userSignature=0xde4ca529eef20db136eed1daf1d072083431d5279e6d6e219600cf57161c5e6d1232af3c8a8ef37ba8b5963f439ef9cc2b475fe18dcc3732dda9fb93c94a3abd1c&recvWindow=60000×tamp=1761230958410&signature=f5fd60da19be213d58914dd6f46bc400ada610fb916998dfc01dd346bfdad512' \ +curl --location --request POST 'https://fapi.asterdex.com/fapi/aster/user-withdraw?chainId=56&asset=USDT&amount=31&fee=0.3&receiver=0x000ae314e2a2172a039b26378814c252734f556a&nonce=1761210000000000&userSignature=0xde4ca529eef20db136eed1daf1d072083431d5279e6d6e219600cf57161c5e6d1232af3c8a8ef37ba8b5963f439ef9cc2b475fe18dcc3732dda9fb93c94a3abd1c&recvWindow=60000×tamp=1761230958410&signature=f5fd60da19be213d58914dd6f46bc400ada610fb916998dfc01dd346bfdad512' \ --header 'Content-Type: application/json' \ --header 'X-MBX-APIKEY: Your API KEY' ``` From 05c1637a1f291745fd005d2c012d7d294497a0ec Mon Sep 17 00:00:00 2001 From: aodyc Date: Mon, 27 Oct 2025 21:08:42 +0800 Subject: [PATCH 025/131] remove useless --- README.md | 7 - aster-broker-api-key-registration.md | 136 ------------- aster-broker-deposit-withdrawal.md | 278 --------------------------- 3 files changed, 421 deletions(-) delete mode 100644 aster-broker-api-key-registration.md delete mode 100644 aster-broker-deposit-withdrawal.md diff --git a/README.md b/README.md index df5f16a..bfb4638 100644 --- a/README.md +++ b/README.md @@ -38,13 +38,6 @@ [Aster 现货资产归集脚本示例](./consolidation.js) -# Aster-Broker API Key 注册 - -[Aster-Broker API Key 注册](./aster-broker-api-key-registration.md) - # Aster 充值提现 [Aster Deposit and Withdrawal](./aster-deposit-withdrawal.md) -# Aster-Broker 充值提现 - -[Aster-Broker Deposit and Withdrawal](./aster-broker-deposit-withdrawal.md) diff --git a/aster-broker-api-key-registration.md b/aster-broker-api-key-registration.md deleted file mode 100644 index bb6c8c4..0000000 --- a/aster-broker-api-key-registration.md +++ /dev/null @@ -1,136 +0,0 @@ -# 1. get nonce - -### request: - -```shell -curl --location 'https://www.asterdex.com/bapi/futures/v1/public/future/web3/get-nonce' \ ---header 'Content-Type: application/json' \ ---data '{ -"sourceAddr" : "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", -"type": "CREATE_API_KEY" -} -``` - -### response: -```json -{ - "code": "000000", - "message": null, - "messageDetail": null, - "data": { - "nonce": "501182" - }, - "success": true -} -``` - -# 2. sign message - -### message: - -```text -You are signing into Aster DEX 501182 -``` - -### result: - -```text -0xa4ee6b068060caeac447216b592a918b085642056248e6ff50ba22b50e8884875ead28f06cbcefcbb93d03997f807fd242354d878756f4690f791ae8dbfcde841c -``` - -# 3. login - -### request: -```shell -curl -XPOST 'https://www.apollox.finance/bapi/futures/v1/public/future/web3/register-from-3party' \ - - -H 'content-type: application/json' \ - --data-raw '{ - "signature":"0xafb84ca3bd36131970636a298677be2e1de4ed81b11101e417272d23f0b7f9af174efdf954ae7a63e844c83d16a4ad391e801c6766a422e647832b5c0c8aa1591c", - "sourceAddr":"0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", - "chainId":56, - "sourceAgent": "broker" - }' -``` - -### params: - -| param | type | required | description | -|-------------|------|----------|----------------------------------------| -| signature | string | yes | signature from previous step | -| sourceAddr | string | yes | the address used to sign the message | -| chainId | int | yes | blockchain network id, e.g. 56 for BSC | -| sourceAgent | string | no | broker's name | - -### response: - -```json -{ - "code": "000000", - "message": null, - "messageDetail": null, - "data": { - "apiKey": "D5M8792356G7H8J9K0L1N2B3V4C5X6Z7", - "apiSecret": "XXXXXXXX", - "keyId": 1234567, - "uid": 12345678, - "address": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", - "apiName": "SafePal-Authorized" - }, - "success": true -} -``` - - -# 4. create api-key - -### request: - -```shell -curl --location 'https://www.asterdex.com/bapi/futures/v1/public/future/web3/broker-create-api-key' \ ---header 'accept: */*' \ ---header 'Content-Type: application/json' \ ---data '{ -"desc": "test description", -"ip": "", -"network": "56", -"signature": "0xa4ee6b068060caeac447216b592a918b085642056248e6ff50ba22b50e8884875ead28f06cbcefcbb93d03997f807fd242354d878756f4690f791ae8dbfcde841c", -"sourceAddr": "0xE90F9596e3Bfd49e9f4c2E0eA48830DC47e6997b", -"type": "CREATE_API_KEY", -"sourceCode": "broker" -}' -``` - -### params: - -|param | type | required | description | -|------|------|----------|-------------------------------------------| -| desc | string | yes | api-key's description, should unique | -| ip | string | no | whitelist ip addresses, separated by ',' | -| network | string | yes | blockchain network, e.g. '56' for BSC | -| signature | string | yes | signature from previous step | -| sourceAddr | string | yes | the address used to sign the message | -| type | string | yes | fixed value "CREATE_API_KEY" | -| sourceCode | string | no | "ae" for aster and other value for broker | - -### response: - -```json -{ - "code": "000000", - "message": null, - "messageDetail": null, - "data": { - "apiKey": "4a2e11b243b1ad75981edf359ae02e873bf88b699196170d998d8266f5eb9f32", - "apiSecret": "72911505f67b24a8efe8f246d06c324b787d2f3f7cb8b5b80ef1698ee1486e25", - "keyId": 0, - "apiName": null - }, - "success": true -} -``` - -### note: - -1. Please keep a record of the returned apiKey and apiSecret. If you lose them, you cannot retrieve them and can only create them again. -2. api-key can't be deleted by user now. \ No newline at end of file diff --git a/aster-broker-deposit-withdrawal.md b/aster-broker-deposit-withdrawal.md deleted file mode 100644 index 5987812..0000000 --- a/aster-broker-deposit-withdrawal.md +++ /dev/null @@ -1,278 +0,0 @@ -# # 1. get all deposit assets - -### request: - -```shell -curl 'https://www.asterdex.com/bapi/futures/v1/public/future/apx/deposit/assets?chainIds=56&networks=EVM' -``` - -### params: -|param | type | required | description | -|-----------|--------|----------|------------------------------------------------------------------------| -| chainIds | string | true | Chain ID, multiple IDs separated by commas | -| networks | string | false | Network type, e.g., EVM, SOLANA, multiple networks separated by commas | - -### response: - -```json -{ - "code": "000000", - "message": null, - "messageDetail": null, - "data": [ - { - "name": "ASTER", - "displayName": "ASTER", - "contractAddress": "0x000ae314e2a2172a039b26378814c252734f556a", - "decimals": 18, - "network": "EVM", - "chainId": 56, - "depositType": "normal", - "rank": 10, - "isNative": false, - "admin": null, - "bank": null, - "tokenVaultAuthority": null, - "tokenVault": null, - "tokenMint": null, - "associatedTokenProgram": null, - "tokenProgram": null, - "systemProgram": null, - "ixSysvar": null, - "priceFeed": null, - "priceFeedProgram": null, - "solVault": null - } - ], - "success": true -} -``` - -# 2. get all withdraw assets - -### request: - -```shell -curl 'https://www.asterdex.com/bapi/futures/v1/public/future/apx/withdraw/assets?chainIds=56&networks=EVM' -``` - -### params: -|param | type | required | description | -|-----------|--------|----------|------------------------------------------------------------------------| -| chainIds | string | true | Chain ID, multiple IDs separated by commas | -| networks | string | false | Network type, e.g., EVM, SOLANA, multiple networks separated by commas | - -### response: - -```json -{ - "code": "000000", - "message": null, - "messageDetail": null, - "data": [ - { - "name": "ASTER", - "displayName": "ASTER", - "contractAddress": "0x000ae314e2a2172a039b26378814c252734f556a", - "decimals": 18, - "network": "EVM", - "chainId": 56, - "withdrawType": "autoWithdraw", - "rank": 10, - "isNative": false, - "isProfit": true, - "admin": null, - "bank": null, - "tokenVaultAuthority": null, - "tokenVault": null, - "tokenMint": null, - "associatedTokenProgram": null, - "tokenProgram": null, - "systemProgram": null, - "ixSysvar": null, - "priceFeed": null, - "priceFeedProgram": null, - "solVault": null - } - ], - "success": true -} -``` - -# 3. estimate withdraw fee - -### request: - -```shell -curl 'https://www.asterdex.com/bapi/futures/v1/public/future/apx/estimate-withdraw-fee?chainId=56&network=EVM¤cy=ASTER' -``` - -### params: - -|param | type | required | description | -|------------|--------|----------|------------------------------| -| chainId | int | true | Chain ID | -| network | string | true | Network type, e.g., EVM, SOL | -| currency | string | true | Currency name, e.g., ASTER | - -### response: - -```json -{ - "code": "000000", - "message": null, - "messageDetail": null, - "data": { - "gasPrice": null, - "gasLimit": 200000, - "nativePrice": null, - "tokenPrice": 1.12357820, - "gasCost": 0.0891, - "gasUsdValue": 0.1 - }, - "success": true -} -``` - -- gasCost: Estimated withdrawal fee in token units - -# 4. withdraw signature - -* when you withdraw, you should supply a EIP712 signature. You can get the signature by signing the following message with your wallet. - -### EIP712 Domain - -```json -{ - "name": "APX", - "version": "1", - "chainId": 56, - "verifyingContract": "0xcEF2dD45Da08b37fB1c2f441d33c2eBb424866A4" -} -``` - -|field| desc | -|---|-------------------------------| -|name| fix string 'Aster' | -|version| fix string '1' | -|chainId| the chainId of withdraw chain | -|verifyingContract| contract address, see below | - -### EIP712 Types - -```json -{ - "Action": [ - {"name": "type", "type": "string"}, - {"name": "destination", "type": "address"}, - {"name": "destination Chain", "type": "string"}, - {"name": "token", "type": "string"}, - {"name": "amount", "type": "string"}, - {"name": "fee", "type": "string"}, - {"name": "nonce", "type": "uint256"} - ] -} -``` - -|field | desc | -|---------------|-------------------------------------------------------------------------------------------------------| -|type | fix string 'Withdraw' | -|destination | the receipt address, should be user's register address | -|destination Chain | the chain name of receipt address, you can see the defination of chainName below | -|token| the name of the currency user withdraw, e.g. ASTER, you can get the name from withdraw/asset API | -|amount | the amount user withdraw in token unit, eg. '1.23' | -|fee| the fee user will pay in token unit, eg. '0.01' (you can get the fee from withdraw/estimate-withdraw-fee API) | -|nonce| a unique number, use the current timestamp in milliseconds and multiply '1000' | - -### chainName definition - -|chainId| chainName | contractAddress | -|---|-----------|-----------------| -|56| BSC | 0xcEF2dD45Da08b37fB1c2f441d33c2eBb424866A4 | -|42161| Arbitrum | 0xBAd4ccc91EF0dfFfbCAb1402C519601fbAf244EF | -|1| ETH | 0xb40EEd68d7d6B3b6d6f4E93DE6239B7C53EFc786 | -|8453|Base| 0x11db0BEb34766277a1d7CAc7590b3Cf4BBf5E4eB | -|324|zkSync| 0xD6f4e33063C881cE9a98e07E13673B92a637D908 | -|169|Manta| 0xBAd4ccc91EF0dfFfbCAb1402C519601fbAf244EF | - -# 5. withdraw - -### request: - -```shell -curl -X POST "https://www.asterdex.com/bapi/futures/v1/private/future/apx/user-withdraw" -H "accept: */*" -H "x-gray-env: normal" -H "x-trace-id: fa2a5961b4a346e083f2bb0bffe39e2f" -H "Content-Type: application/json" \ --d "{ \"accountType\": \"spot\", \"amount\": \"10.2\", \"chainId\": 97, \"currency\": \"USDT\", \"fee\": \"0.01\", \"nonce\": \"1761029928213000\", \"receiver\": \"0x4C5EdB66CC7626a1C92d5178c3E5c45409BcE6D7\", \"userSignature\": \"0xc0299efe235ec194d070163b1f92ebf5d01bd820c1c08fa9730929c7a36172a9001b99203b2f9997aa7d41b7658348704e0515f4c40e76f1892f7a5b0af31daa1c\"}" -``` - -### params: -|param | type | required | description | -|--------------|--------|----------|-----------------------------------------------------------| -| accountType | string | true | Account type, e.g., spot, perp | -| amount | string | true | Withdraw amount in token unit | -| chainId | int | true | Chain ID | -| currency | string | true | Currency name, e.g., ASTER | -| fee | string | true | Withdraw fee in token unit | -| nonce | string | true | Unique number, should be the save in signature | -| receiver | string | true | Withdraw receipt address, should be the save in signature | -| userSignature | string | true | EIP712 signature | - -### response: - -```json -{ - "code": "200", - "message": "success", - "messageDetail": null, - "data": { - "withdrawId": "1234567", - "hash": "0x9a40f0119b670fb6b155744b51981f91c4c4c8a20c333441a63853fe7d055c90" - }, - "success": true -} -``` - -|field | desc | -|-----------|--------------------------------------| -|withdrawId | the withdraw request id, a unique id | -|hash | the digest of user's signature | - -# 6. withdraw by API [futures] - -### request: - -```shell -curl --location --request POST 'https://fapi.asterdex.com/fapi/apx/user-withdraw?chainId=56&asset=USDT&amount=31&fee=0.3&receiver=0xcEF2dD45Da08b37fB1c2f441d33c2eBb424866A4&nonce=1761210000000000&userSignature=0xde4ca529eef20db136eed1daf1d072083431d5279e6d6e219600cf57161c5e6d1232af3c8a8ef37ba8b5963f439ef9cc2b475fe18dcc3732dda9fb93c94a3abd1c&recvWindow=60000×tamp=1761230958410&signature=f5fd60da19be213d58914dd6f46bc400ada617fb916998dfc01dd346bfdad512' \ ---header 'Content-Type: application/json' \ ---header 'X-MBX-APIKEY: Your API KEY' -``` - -### params: -| param | type | required | description | -|---------------|--------|----------|-----------------------------------------------------------| -| amount | string | true | Withdraw amount in token unit | -| chainId | int | true | Chain ID | -| asset | string | true | Currency name, e.g., ASTER | -| fee | string | true | Withdraw fee in token unit | -| nonce | string | true | Unique number, should be the save in signature | -| receiver | string | true | Withdraw receipt address, should be the save in signature | -| userSignature | string | true | EIP712 signature | - -### response: - -```json -{ - "code": "200", - "message": "success", - "messageDetail": null, - "data": { - "withdrawId": "1234567", - "hash": "0x9a40f0119b670fb6b155744b51981f91c4c4c8a20c333441a63853fe7d055c90" - }, - "success": true -} -``` - -|field | desc | -|-----------|--------------------------------------| -|withdrawId | the withdraw request id, a unique id | -|hash | the digest of user's signature | From b95cd871b741d98b5116f6e736e4aec64bd9417a Mon Sep 17 00:00:00 2001 From: aodyc Date: Tue, 28 Oct 2025 21:27:41 +0800 Subject: [PATCH 026/131] add api-key docs --- README.md | 4 ++ aster-api-key-registration.md | 92 +++++++++++++++++++++++++++++++++++ 2 files changed, 96 insertions(+) create mode 100644 aster-api-key-registration.md diff --git a/README.md b/README.md index bfb4638..b6b0d3f 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,10 @@ [Aster Finance Spot Asset Consolidation](./consolidation.js) +# Aster Api Key + +[Aster Api Key](./aster-api-key-registration.md) + # Aster 现货资产归集脚本示例 [Aster 现货资产归集脚本示例](./consolidation.js) diff --git a/aster-api-key-registration.md b/aster-api-key-registration.md new file mode 100644 index 0000000..ca0b3e3 --- /dev/null +++ b/aster-api-key-registration.md @@ -0,0 +1,92 @@ +# 1. get nonce + +### request: + +```shell +curl --location 'https://www.asterdex.com/bapi/futures/v1/public/future/web3/get-nonce' \ +--header 'Content-Type: application/json' \ +--data '{ +"sourceAddr" : "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", +"type": "CREATE_API_KEY" +} +``` + +### response: +```json +{ + "code": "000000", + "message": null, + "messageDetail": null, + "data": { + "nonce": "501182" + }, + "success": true +} +``` + +# 2. sign message + +### message: + +```text +You are signing into Aster DEX 501182 +``` + +### result: + +```text +0xa4ee6b068060caeac447216b592a918b085642056248e6ff50ba22b50e8884875ead28f06cbcefcbb93d03997f807fd242354d878756f4690f791ae8dbfcde841c +``` + +# 3. create api-key + +### request: + +```shell +curl --location 'https://www.asterdex.com/bapi/futures/v1/public/future/web3/broker-create-api-key' \ +--header 'accept: */*' \ +--header 'Content-Type: application/json' \ +--data '{ +"desc": "test description", +"ip": "", +"network": "56", +"signature": "0xa4ee6b068060caeac447216b592a918b085642056248e6ff50ba22b50e8884875ead28f06cbcefcbb93d03997f807fd242354d878756f4690f791ae8dbfcde841c", +"sourceAddr": "0xE90F9596e3Bfd49e9f4c2E0eA48830DC47e6997b", +"type": "CREATE_API_KEY", +"sourceCode": "broker" +}' +``` + +### params: + +|param | type | required | description | +|------|------|----------|-------------------------------------------| +| desc | string | yes | api-key's description, should unique | +| ip | string | no | whitelist ip addresses, separated by ',' | +| network | string | yes | blockchain network, e.g. '56' for BSC | +| signature | string | yes | signature from previous step | +| sourceAddr | string | yes | the address used to sign the message | +| type | string | yes | fixed value "CREATE_API_KEY" | +| sourceCode | string | no | "ae" for aster and other value for broker | + +### response: + +```json +{ + "code": "000000", + "message": null, + "messageDetail": null, + "data": { + "apiKey": "4a2e11b243b1ad75981edf359ae02e873bf88b699196170d998d8266f5eb9f32", + "apiSecret": "72911505f67b24a8efe8f246d06c324b787d2f3f7cb8b5b80ef1698ee1486e25", + "keyId": 0, + "apiName": null + }, + "success": true +} +``` + +### note: + +1. Please keep a record of the returned apiKey and apiSecret. If you lose them, you cannot retrieve them and can only create them again. +2. api-key can't be deleted by user now. \ No newline at end of file From d5b1a2af002ac4b1e4c709f054e6befd54e7760f Mon Sep 17 00:00:00 2001 From: aodyc Date: Wed, 29 Oct 2025 10:06:41 +0800 Subject: [PATCH 027/131] add login docks --- aster-api-key-registration.md | 43 +++++++++++++++++++++++++++++++++-- 1 file changed, 41 insertions(+), 2 deletions(-) diff --git a/aster-api-key-registration.md b/aster-api-key-registration.md index ca0b3e3..c01adb6 100644 --- a/aster-api-key-registration.md +++ b/aster-api-key-registration.md @@ -29,7 +29,7 @@ curl --location 'https://www.asterdex.com/bapi/futures/v1/public/future/web3/get ### message: ```text -You are signing into Aster DEX 501182 +You are signing into Astherus 501182 ``` ### result: @@ -38,7 +38,46 @@ You are signing into Aster DEX 501182 0xa4ee6b068060caeac447216b592a918b085642056248e6ff50ba22b50e8884875ead28f06cbcefcbb93d03997f807fd242354d878756f4690f791ae8dbfcde841c ``` -# 3. create api-key +# 3. login + +### request: +```shell +curl -XPOST 'https://www.asterdex.com/bapi/futures/v1/public/future/web3/ae/login' \ + + -H 'content-type: application/json' \ + --data-raw '{ + "signature":"0xafb84ca3bd36131970636a298677be2e1de4ed81b11101e417272d23f0b7f9af174efdf954ae7a63e844c83d16a4ad391e801c6766a422e647832b5c0c8aa1591c", + "sourceAddr":"0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", + "chainId":56, + "agentCode": "56789" + }' +``` + +### params: + +| param | type | required | description | +|-------------|------|----------|----------------------------------------| +| signature | string | yes | signature from previous step | +| sourceAddr | string | yes | the address used to sign the message | +| chainId | int | yes | blockchain network id, e.g. 56 for BSC | +| agentCode | string | no | referral code | + +### response: + +```json +{ + "code": "000000", + "message": null, + "messageDetail": null, + "data": { + "token": "D5M8792356G7H8J9K0L1N2B3V4C5X6Z7D5621", + "uid": 12345678 + }, + "success": true +} +``` + +# 4. create api-key ### request: From 552b0552a7e0668d63fa9a8a0fc62c787d764b77 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Thu, 30 Oct 2025 10:54:03 +0800 Subject: [PATCH 028/131] add api create apikey demo --- demo/create-apikey-for-others.js | 131 +++++++++++++++++++++++++++++++ 1 file changed, 131 insertions(+) create mode 100644 demo/create-apikey-for-others.js diff --git a/demo/create-apikey-for-others.js b/demo/create-apikey-for-others.js new file mode 100644 index 0000000..6f836dc --- /dev/null +++ b/demo/create-apikey-for-others.js @@ -0,0 +1,131 @@ +const ethers = require('ethers'); +const crypto = require('crypto'); +const axios = require('axios'); + + +//需要生成apikey的账户信息 +const new_address_config = [ + { + private_key: "*", + address: '*', + }, + { + private_key: "*", + address: '*', + } +] + +//主账户的地址 apikey api_secret +const api_key = '*' +const api_secret = '*' + + +//下面的参数无需修改 +const host = 'https://sapi.asterdex.com' + +var new_address_apikey = '' +var new_address_apiSecret = '' +var use_new_apikey = false + +const spot_get_nonce = { 'url': '/api/v1/getNonce', 'method': 'POST', 'params': { 'userOperationType': 'CREATE_API_KEY' } } +const spot_create_apikey = { 'url': '/api/v1/createApiKey', 'method': 'POST', 'params': { 'userOperationType': 'CREATE_API_KEY' } } + +async function getUrl(my_dict) { + content = '' + for (let key in my_dict) { + content = content + key + '=' + my_dict[key] + '&' + } + content += 'recvWindow=5000×tamp=' + Date.now() + + return content + +} + +async function sign_v1(secretKey, message) { + const hmac = crypto.createHmac('sha256', secretKey) + .update(message) + .digest('hex'); + return hmac +} + +async function sendRequest(url, method) { + headers = {} + key = api_key + if (use_new_apikey == true) { + key = new_address_apikey + } + if (method == 'POST') { + headers = { + 'Content-Type': 'application/x-www-form-urlencoded', + 'X-MBX-APIKEY': key, + 'User-Agent': 'Node.js HTTP Client' + } + } + try { + const response = await axios({ + method: method, + url: url, + headers: headers + + }); + + return response.data; + } catch (error) { + console.error('Error:', error.response?.data || error.message); + } + + return '' +} + +async function send_v1(path, method, my_dict) { + content = await getUrl(my_dict) + secret = api_secret + if (use_new_apikey == true) { + secret = new_address_apiSecret + } + signature = await sign_v1(secret, content) + path = path + '?' + content + '&signature=' + signature + return await sendRequest(host + path, method) +} + + +async function send(config, addParams) { + path = config['url'] + method = config['method'] + my_dict = { ...config['params'], ...addParams } + return await send_v1(path, method, my_dict) +} + +async function sign(private_key, message) { + wallet = new ethers.Wallet(private_key); + const signature = await wallet.signMessage(message); + return signature +} + +async function main() { + i = 0 + for (const config of new_address_config) { + console.log('开始为账户创建apikey:', config.address); + //获取创建apikey的nonce + let nonce = await send(spot_get_nonce, {'address': config.address}) + + //给新地址创建api_key api_secret + message = 'You are signing into Astherus ${nonce}'.replace('${nonce}', nonce) + userSignature = await sign(config.private_key,message) + + //创建apikey时的描述信息 注意同一账户的desc不能重复 + var key_desc = Date.now() +'_' + i + i = i + 1 + let new_api = await send(spot_create_apikey, { 'userSignature': userSignature,'address': config.address,'desc': key_desc }) + new_address_apikey = new_api['apiKey'] + new_address_apiSecret = new_api['apiSecret'] + + console.log('new address: ',config.address) + console.log('new_address_apikey:', new_address_apikey) + console.log('new_address_apiSecret:', new_address_apiSecret) + } +} + + +main() + From e0633c1368056495bc42df8cf8f883026fd915b5 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Thu, 30 Oct 2025 19:55:09 +0800 Subject: [PATCH 029/131] api key create front and ae logi --- demo/create-apikey-front.js | 87 +++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 demo/create-apikey-front.js diff --git a/demo/create-apikey-front.js b/demo/create-apikey-front.js new file mode 100644 index 0000000..4cd980c --- /dev/null +++ b/demo/create-apikey-front.js @@ -0,0 +1,87 @@ +const ethers = require('ethers'); +const crypto = require('crypto'); +const axios = require('axios'); + +const { Wallet } = require('ethers'); + +//下面的参数无需修改 +const host = 'https://www.asterdex.com/bapi/futures/v1' +const get_nonce = { 'url': '/public/future/web3/get-nonce', 'method': 'POST', 'params': { } } +const create_apikey = { 'url': '/public/future/web3/broker-create-api-key', 'method': 'POST', 'params': { 'network': '56','type':'CREATE_API_KEY','sourceCode':'ae','ip':'' } } +const ae_login = { 'url': '/public/future/web3/ae/login', 'method': 'POST', 'params': { 'chainId': '56' } } + +async function sendRequest(url, method,body) { + headers = {} + url = host+url + console.log(url) + console.log(body) + if (method == 'POST') { + headers = { + 'Content-Type': 'application/json', + 'clientType':'web' + } + } + try { + const response = await axios({ + method: method, + data: body, + url: url, + headers: headers + + }); + + return response.data; + } catch (error) { + console.error('Error:', error.response?.data || error.message); + } + + return '' +} + + +async function send(config, addParams) { + path = config['url'] + method = config['method'] + my_dict = { ...config['params'], ...addParams } + return await sendRequest(path, method, my_dict) +} + +async function sign(private_key, message) { + wallet = new ethers.Wallet(private_key); + const signature = await wallet.signMessage(message); + return signature +} + +async function main() { + const wallet = Wallet.createRandom(); + + console.log("Address:", wallet.address); + console.log("Private Key:", wallet.privateKey); + + let nonce_res = await send(get_nonce, {'type':'CREATE_API_KEY','sourceAddr':wallet.address}) + let nonce = nonce_res['data']['nonce'] + console.log(nonce) + //给新地址创建api_key api_secret + message = 'You are signing into Astherus ${nonce}'.replace('${nonce}', nonce) + user_signature = await sign( wallet.privateKey,message) + console.log(user_signature) + let create_api_key_res = await send(create_apikey, {'signature':user_signature,'desc':'12','sourceAddr':wallet.address}) + console.log(create_api_key_res) + + + let login_nonce_res = await send(get_nonce, {'type':'LOGIN','sourceAddr':wallet.address}) + nonce = login_nonce_res['data']['nonce'] + console.log(nonce) + //地址登陆 header必传 'clientType':'web' + message = 'You are signing into Astherus ${nonce}'.replace('${nonce}', nonce) + user_signature = await sign( wallet.privateKey,message) + console.log(user_signature) + let ae_login_res = await send(ae_login, {'signature':user_signature,'sourceAddr':wallet.address}) + console.log(ae_login_res) + +} + +main() + + + From d86c3454a3a8b56ba082f13a243960d60c857c0b Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Fri, 31 Oct 2025 09:31:59 +0800 Subject: [PATCH 030/131] login first --- demo/create-apikey-front.js | 27 ++++++++++++--------------- 1 file changed, 12 insertions(+), 15 deletions(-) diff --git a/demo/create-apikey-front.js b/demo/create-apikey-front.js index 4cd980c..487b11d 100644 --- a/demo/create-apikey-front.js +++ b/demo/create-apikey-front.js @@ -13,8 +13,6 @@ const ae_login = { 'url': '/public/future/web3/ae/login', 'method': 'POST', 'par async function sendRequest(url, method,body) { headers = {} url = host+url - console.log(url) - console.log(body) if (method == 'POST') { headers = { 'Content-Type': 'application/json', @@ -58,26 +56,25 @@ async function main() { console.log("Address:", wallet.address); console.log("Private Key:", wallet.privateKey); - let nonce_res = await send(get_nonce, {'type':'CREATE_API_KEY','sourceAddr':wallet.address}) - let nonce = nonce_res['data']['nonce'] + let login_nonce_res = await send(get_nonce, {'type':'LOGIN','sourceAddr':wallet.address}) + let nonce = login_nonce_res['data']['nonce'] console.log(nonce) - //给新地址创建api_key api_secret - message = 'You are signing into Astherus ${nonce}'.replace('${nonce}', nonce) - user_signature = await sign( wallet.privateKey,message) + //地址登陆 header必传 'clientType':'web' + let message = 'You are signing into Astherus ${nonce}'.replace('${nonce}', nonce) + let user_signature = await sign( wallet.privateKey,message) console.log(user_signature) - let create_api_key_res = await send(create_apikey, {'signature':user_signature,'desc':'12','sourceAddr':wallet.address}) - console.log(create_api_key_res) - + let ae_login_res = await send(ae_login, {'signature':user_signature,'sourceAddr':wallet.address,'agentCode':'69Ae1D'}) + console.log(ae_login_res) - let login_nonce_res = await send(get_nonce, {'type':'LOGIN','sourceAddr':wallet.address}) - nonce = login_nonce_res['data']['nonce'] + let apikey_nonce_res = await send(get_nonce, {'type':'CREATE_API_KEY','sourceAddr':wallet.address}) + nonce = apikey_nonce_res['data']['nonce'] console.log(nonce) - //地址登陆 header必传 'clientType':'web' + //给新地址创建api_key api_secret message = 'You are signing into Astherus ${nonce}'.replace('${nonce}', nonce) user_signature = await sign( wallet.privateKey,message) console.log(user_signature) - let ae_login_res = await send(ae_login, {'signature':user_signature,'sourceAddr':wallet.address}) - console.log(ae_login_res) + let create_api_key_res = await send(create_apikey, {'signature':user_signature,'desc':'12','sourceAddr':wallet.address}) + console.log(create_api_key_res) } From 5a208b60e93bb44b7ac58f9ce3f815575a179095 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Fri, 31 Oct 2025 09:34:22 +0800 Subject: [PATCH 031/131] v1->v3 --- aster-finance-futures-api-v3.md | 90 ++++++++++++++++----------------- 1 file changed, 45 insertions(+), 45 deletions(-) diff --git a/aster-finance-futures-api-v3.md b/aster-finance-futures-api-v3.md index 98ef163..d1e49c1 100644 --- a/aster-finance-futures-api-v3.md +++ b/aster-finance-futures-api-v3.md @@ -857,7 +857,7 @@ Since `MARKET` orders have no price, the mark price is used. {} ``` -``GET /fapi/v1/ping`` +``GET /fapi/v3/ping`` Test connectivity to the Rest API. @@ -877,7 +877,7 @@ NONE } ``` -``GET /fapi/v1/time`` +``GET /fapi/v3/time`` Test connectivity to the Rest API and get the current server time. @@ -908,7 +908,7 @@ NONE "rateLimitType": "ORDERS" } ], - "serverTime": 1565613908500, // Ignore please. If you want to check current server time, please check via "GET /fapi/v1/time" + "serverTime": 1565613908500, // Ignore please. If you want to check current server time, please check via "GET /fapi/v3/time" "assets": [ // assets information { "asset": "BUSD", @@ -1008,7 +1008,7 @@ NONE } ``` -``GET /fapi/v1/exchangeInfo`` +``GET /fapi/v3/exchangeInfo`` Current exchange trading rules and symbol information @@ -1042,7 +1042,7 @@ NONE } ``` -``GET /fapi/v1/depth`` +``GET /fapi/v3/depth`` **Weight:** @@ -1079,7 +1079,7 @@ Adjusted based on the limit: ] ``` -``GET /fapi/v1/trades`` +``GET /fapi/v3/trades`` Get recent market trades @@ -1112,7 +1112,7 @@ Get recent market trades ] ``` -``GET /fapi/v1/historicalTrades`` +``GET /fapi/v3/historicalTrades`` Get older market historical trades. @@ -1147,7 +1147,7 @@ Get older market historical trades. ] ``` -``GET /fapi/v1/aggTrades`` +``GET /fapi/v3/aggTrades`` Get compressed, aggregate market trades. Market trades that fill at the time, from the same order, with the same price will have the quantity aggregated. @@ -1191,7 +1191,7 @@ Get compressed, aggregate market trades. Market trades that fill at the time, fr ] ``` -``GET /fapi/v1/klines`` +``GET /fapi/v3/klines`` Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time. @@ -1241,7 +1241,7 @@ Klines are uniquely identified by their open time. ] ``` -``GET /fapi/v1/indexPriceKlines`` +``GET /fapi/v3/indexPriceKlines`` Kline/candlestick bars for the index price of a pair. @@ -1292,7 +1292,7 @@ Klines are uniquely identified by their open time. ] ``` -``GET /fapi/v1/markPriceKlines`` +``GET /fapi/v3/markPriceKlines`` Kline/candlestick bars for the mark price of a symbol. @@ -1354,7 +1354,7 @@ Klines are uniquely identified by their open time. ] ``` -``GET /fapi/v1/premiumIndex`` +``GET /fapi/v3/premiumIndex`` Mark Price and Funding Rate @@ -1386,7 +1386,7 @@ Mark Price and Funding Rate ] ``` -``GET /fapi/v1/fundingRate`` +``GET /fapi/v3/fundingRate`` **Weight:** 1 @@ -1456,7 +1456,7 @@ Mark Price and Funding Rate ] ``` -``GET /fapi/v1/ticker/24hr`` +``GET /fapi/v3/ticker/24hr`` 24 hour rolling window price change statistics. **Careful** when accessing this with no symbol. @@ -1497,7 +1497,7 @@ Mark Price and Funding Rate ] ``` -``GET /fapi/v1/ticker/price`` +``GET /fapi/v3/ticker/price`` Latest price for a symbol or symbols. @@ -1543,7 +1543,7 @@ Latest price for a symbol or symbols. ] ``` -``GET /fapi/v1/ticker/bookTicker`` +``GET /fapi/v3/ticker/bookTicker`` Best price/qty on the order book for a symbol or symbols. @@ -2181,7 +2181,7 @@ Bids and asks, pushed every 250 milliseconds, 500 milliseconds, 100 milliseconds 1. Open a stream to **wss://fstream.asterdex.com/stream?streams=btcusdt@depth**. 2. Buffer the events you receive from the stream. For same price, latest received update covers the previous one. -3. Get a depth snapshot from **https://fapi.asterdex.com/fapi/v1/depth?symbol=BTCUSDT&limit=1000** . +3. Get a depth snapshot from **https://fapi.asterdex.com/fapi/v3/depth?symbol=BTCUSDT&limit=1000** . 4. Drop any event where `u` is < `lastUpdateId` in the snapshot. 5. The first processed event should have `U` <= `lastUpdateId` **AND** `u` >= `lastUpdateId` 6. While listening to the stream, each new event's `pu` should be equal to the previous event's `u`, otherwise initialize the process from step 3. @@ -2206,7 +2206,7 @@ Considering the possible data latency from RESTful endpoints during an extremely } ``` -``POST /fapi/v1/positionSide/dual (HMAC SHA256)`` +``POST /fapi/v3/positionSide/dual (HMAC SHA256)`` Change user's position mode (Hedge Mode or One-way Mode ) on ***EVERY symbol*** @@ -2231,7 +2231,7 @@ Change user's position mode (Hedge Mode or One-way Mode ) on ***EVERY symbol*** } ``` -``GET /fapi/v1/positionSide/dual (HMAC SHA256)`` +``GET /fapi/v3/positionSide/dual (HMAC SHA256)`` Get user's position mode (Hedge Mode or One-way Mode ) on ***EVERY symbol*** @@ -2256,7 +2256,7 @@ Get user's position mode (Hedge Mode or One-way Mode ) on ***EVERY symbol*** } ``` -``POST /fapi/v1/multiAssetsMargin (HMAC SHA256)`` +``POST /fapi/v3/multiAssetsMargin (HMAC SHA256)`` Change user's Multi-Assets mode (Multi-Assets Mode or Single-Asset Mode) on ***Every symbol*** @@ -2281,7 +2281,7 @@ Change user's Multi-Assets mode (Multi-Assets Mode or Single-Asset Mode) on ***E } ``` -``GET /fapi/v1/multiAssetsMargin (HMAC SHA256)`` +``GET /fapi/v3/multiAssetsMargin (HMAC SHA256)`` Get user's Multi-Assets mode (Multi-Assets Mode or Single-Asset Mode) on ***Every symbol*** @@ -2327,7 +2327,7 @@ Get user's Multi-Assets mode (Multi-Assets Mode or Single-Asset Mode) on ***Ever } ``` -``POST /fapi/v1/order (HMAC SHA256)`` +``POST /fapi/v3/order (HMAC SHA256)`` Send in a new order. @@ -2374,7 +2374,7 @@ Additional mandatory parameters based on `type`: * If parameter`priceProtect`is sent as true: * when price reaches the `stopPrice` ,the difference rate between "MARK_PRICE" and "CONTRACT_PRICE" cannot be larger than the "triggerProtect" of the symbol - * "triggerProtect" of a symbol can be got from `GET /fapi/v1/exchangeInfo` + * "triggerProtect" of a symbol can be got from `GET /fapi/v3/exchangeInfo` * `STOP`, `STOP_MARKET`: * BUY: latest price ("MARK_PRICE" or "CONTRACT_PRICE") >= `stopPrice` @@ -2440,7 +2440,7 @@ Additional mandatory parameters based on `type`: ] ``` -``POST /fapi/v1/batchOrders (HMAC SHA256)`` +``POST /fapi/v3/batchOrders (HMAC SHA256)`` **Weight:** 5 @@ -2545,7 +2545,7 @@ Notes: } ``` -``GET /fapi/v1/order (HMAC SHA256)`` +``GET /fapi/v3/order (HMAC SHA256)`` Check an order's status. @@ -2602,7 +2602,7 @@ Notes: } ``` -``DELETE /fapi/v1/order (HMAC SHA256)`` +``DELETE /fapi/v3/order (HMAC SHA256)`` Cancel an active order. @@ -2632,7 +2632,7 @@ Either `orderId` or `origClientOrderId` must be sent. } ``` -``DELETE /fapi/v1/allOpenOrders (HMAC SHA256)`` +``DELETE /fapi/v3/allOpenOrders (HMAC SHA256)`` **Weight:** 1 @@ -2682,7 +2682,7 @@ Either `orderId` or `origClientOrderId` must be sent. ] ``` -``DELETE /fapi/v1/batchOrders (HMAC SHA256)`` +``DELETE /fapi/v3/batchOrders (HMAC SHA256)`` **Weight:** 1 @@ -2712,7 +2712,7 @@ Either `orderIdList` or `origClientOrderIdList ` must be sent. Cancel all open orders of the specified symbol at the end of the specified countdown. -``POST /fapi/v1/countdownCancelAll (HMAC SHA256)`` +``POST /fapi/v3/countdownCancelAll (HMAC SHA256)`` **Weight:** 10 @@ -2765,7 +2765,7 @@ Cancel all open orders of the specified symbol at the end of the specified count } ``` -``GET /fapi/v1/openOrder (HMAC SHA256)`` +``GET /fapi/v3/openOrder (HMAC SHA256)`` **Weight:** 1 @@ -2816,7 +2816,7 @@ Cancel all open orders of the specified symbol at the end of the specified count ] ``` -``GET /fapi/v1/openOrders (HMAC SHA256)`` +``GET /fapi/v3/openOrders (HMAC SHA256)`` Get all open orders on a symbol. **Careful** when accessing this with no symbol. @@ -2867,7 +2867,7 @@ Get all open orders on a symbol. **Careful** when accessing this with no symbol. ] ``` -``GET /fapi/v1/allOrders (HMAC SHA256)`` +``GET /fapi/v3/allOrders (HMAC SHA256)`` Get all account orders; active, canceled, or filled. @@ -3032,7 +3032,7 @@ Get current account information. } ``` -``POST /fapi/v1/leverage (HMAC SHA256)`` +``POST /fapi/v3/leverage (HMAC SHA256)`` Change user's initial leverage of specific symbol market. @@ -3059,7 +3059,7 @@ Change user's initial leverage of specific symbol market. } ``` -``POST /fapi/v1/marginType (HMAC SHA256)`` +``POST /fapi/v3/marginType (HMAC SHA256)`` **Weight:** 1 @@ -3086,7 +3086,7 @@ Change user's initial leverage of specific symbol market. } ``` -``POST /fapi/v1/positionMargin (HMAC SHA256)`` +``POST /fapi/v3/positionMargin (HMAC SHA256)`` **Weight:** 1 @@ -3129,7 +3129,7 @@ Change user's initial leverage of specific symbol market. ] ``` -``GET /fapi/v1/positionMargin/history (HMAC SHA256)`` +``GET /fapi/v3/positionMargin/history (HMAC SHA256)`` **Weight:** 1 @@ -3252,7 +3252,7 @@ Please use with user data stream `ACCOUNT_UPDATE` to meet your timeliness and ac ] ``` -``GET /fapi/v1/userTrades (HMAC SHA256)`` +``GET /fapi/v3/userTrades (HMAC SHA256)`` Get trades for a specific account and symbol. @@ -3304,7 +3304,7 @@ Get trades for a specific account and symbol. ] ``` -``GET /fapi/v1/income (HMAC SHA256)`` +``GET /fapi/v3/income (HMAC SHA256)`` **Weight:** 30 @@ -3366,7 +3366,7 @@ Get trades for a specific account and symbol. } ``` -``GET /fapi/v1/leverageBracket`` +``GET /fapi/v3/leverageBracket`` **Weight:** 1 @@ -3407,7 +3407,7 @@ Get trades for a specific account and symbol. ] ``` -``GET /fapi/v1/adlQuantile`` +``GET /fapi/v3/adlQuantile`` **Weight:** 5 @@ -3480,7 +3480,7 @@ Get trades for a specific account and symbol. ] ``` -``GET /fapi/v1/forceOrders`` +``GET /fapi/v3/forceOrders`` **Weight:** 20 with symbol, 50 without symbol @@ -3511,7 +3511,7 @@ Get trades for a specific account and symbol. } ``` -``GET /fapi/v1/commissionRate (HMAC SHA256)`` +``GET /fapi/v3/commissionRate (HMAC SHA256)`` **Weight:** 20 @@ -3546,7 +3546,7 @@ Get trades for a specific account and symbol. } ``` -``POST /fapi/v1/listenKey`` +``POST /fapi/v3/listenKey`` Start a new user data stream. The stream will close after 60 minutes unless a keepalive is sent. If the account has an active `listenKey`, that `listenKey` will be returned and its validity will be extended for 60 minutes. @@ -3565,7 +3565,7 @@ None {} ``` -``PUT /fapi/v1/listenKey`` +``PUT /fapi/v3/listenKey`` Keepalive a user data stream to prevent a time out. User data streams will close after 60 minutes. It's recommended to send a ping about every 60 minutes. @@ -3584,7 +3584,7 @@ None {} ``` -``DELETE /fapi/v1/listenKey`` +``DELETE /fapi/v3/listenKey`` Close out a user data stream. From 5bd7cc6cd6bb50b2a5b294b1a2ed261e99ab59d8 Mon Sep 17 00:00:00 2001 From: aodyc Date: Fri, 7 Nov 2025 17:37:41 +0800 Subject: [PATCH 032/131] add solana withdraw api --- aster-deposit-withdrawal.md | 37 ++++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/aster-deposit-withdrawal.md b/aster-deposit-withdrawal.md index e69ef7c..e104b60 100644 --- a/aster-deposit-withdrawal.md +++ b/aster-deposit-withdrawal.md @@ -318,4 +318,39 @@ curl --location --request POST 'https://sapi.asterdex.com/api/v1/aster/user-with |field | desc | |-----------|--------------------------------------| |withdrawId | the withdraw request id, a unique id | -|hash | the digest of user's signature | \ No newline at end of file +|hash | the digest of user's signature | + +# 8. withdraw by API [futures] + +### request: + +```shell +curl --location --request POST 'https://fapi.asterdex.com/fapi/aster/user-solana-withdraw?chainId=101&asset=USDT&amount=3&fee=0.6&receiver=4wTV1YmiEkRvAtNtsSGPtUrqRYQMe5SKy2uB4Jjaxnjf&recvWindow=60000×tamp=1762440135477&signature=a773a7e83c2fe4581eb2dc0500000faa3138173ba6262316c0d83b3498dea319' \ +--header 'Content-Type: application/json' \ +--header 'X-MBX-APIKEY: Your API KEY' +``` + +### params: +| param | type | required | description | +|---------------|--------|----------|-----------------------------------------------------------| +| amount | string | true | Withdraw amount in token unit | +| chainId | int | true | fix value 101 | +| asset | string | true | Currency name, e.g., USDT | +| fee | string | true | Withdraw fee in token unit | +| receiver | string | true | Withdraw receipt address, should be the save in signature | + +### response: + +```json +{ + "code": "200", + "message": "success", + "messageDetail": null, + "data": { + "withdrawId": "1234567", + "hash": "0x9a40f0119b670fb6b155744b51981f91c4c4c8a20c333441a63853fe7d055c90" + }, + "success": true +} +``` +- hash is not the transaction hash, just a unique value \ No newline at end of file From efbb5aa2a5e285addd60171b75ce6913d010e705 Mon Sep 17 00:00:00 2001 From: aodyc Date: Tue, 18 Nov 2025 16:04:37 +0800 Subject: [PATCH 033/131] add header --- aster-api-key-registration.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/aster-api-key-registration.md b/aster-api-key-registration.md index c01adb6..2136787 100644 --- a/aster-api-key-registration.md +++ b/aster-api-key-registration.md @@ -43,7 +43,7 @@ You are signing into Astherus 501182 ### request: ```shell curl -XPOST 'https://www.asterdex.com/bapi/futures/v1/public/future/web3/ae/login' \ - + -H 'clientType: broker' \ -H 'content-type: application/json' \ --data-raw '{ "signature":"0xafb84ca3bd36131970636a298677be2e1de4ed81b11101e417272d23f0b7f9af174efdf954ae7a63e844c83d16a4ad391e801c6766a422e647832b5c0c8aa1591c", @@ -83,6 +83,7 @@ curl -XPOST 'https://www.asterdex.com/bapi/futures/v1/public/future/web3/ae/logi ```shell curl --location 'https://www.asterdex.com/bapi/futures/v1/public/future/web3/broker-create-api-key' \ +--header 'clientType: broker' \ --header 'accept: */*' \ --header 'Content-Type: application/json' \ --data '{ From e30ff74ef6c8e4cef9d4bc8712df86004b0d77e8 Mon Sep 17 00:00:00 2001 From: aodyc Date: Thu, 20 Nov 2025 12:16:01 +0800 Subject: [PATCH 034/131] change response detail --- aster-finance-futures-api-v3.md | 4 ++-- aster-finance-futures-api.md | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/aster-finance-futures-api-v3.md b/aster-finance-futures-api-v3.md index d1e49c1..5842451 100644 --- a/aster-finance-futures-api-v3.md +++ b/aster-finance-futures-api-v3.md @@ -1233,7 +1233,7 @@ Klines are uniquely identified by their open time. "0 ", // Ignore 1591256459999, // Close time "0", // Ignore - 60, // Number of bisic data + 60, // Number of Data Points "0", // Ignore "0", // Ignore "0" // Ignore @@ -1284,7 +1284,7 @@ Klines are uniquely identified by their open time. "0 ", // Ignore 1591256519999, // Close time "0", // Ignore - 60, // Number of bisic data + 60, // Number of Data Points "0", // Ignore "0", // Ignore "0" // Ignore diff --git a/aster-finance-futures-api.md b/aster-finance-futures-api.md index b98bb1c..a70b8dc 100644 --- a/aster-finance-futures-api.md +++ b/aster-finance-futures-api.md @@ -1063,7 +1063,7 @@ limit | INT | NO | Default 500; max 1500. "0 ", // Ignore 1591256459999, // Close time "0", // Ignore - 60, // Number of bisic data + 60, // Number of Data Points "0", // Ignore "0", // Ignore "0" // Ignore @@ -1116,7 +1116,7 @@ limit | INT | NO | Default 500; max 1500. "0 ", // Ignore 1591256519999, // Close time "0", // Ignore - 60, // Number of bisic data + 60, // Number of Data Points "0", // Ignore "0", // Ignore "0" // Ignore From 8a012043d45df0e08e04217cad871b90cb71d9a8 Mon Sep 17 00:00:00 2001 From: aodyc Date: Wed, 26 Nov 2025 20:25:52 +0800 Subject: [PATCH 035/131] fix some desc --- aster-deposit-withdrawal.md | 24 +++--------------------- 1 file changed, 3 insertions(+), 21 deletions(-) diff --git a/aster-deposit-withdrawal.md b/aster-deposit-withdrawal.md index e104b60..765d318 100644 --- a/aster-deposit-withdrawal.md +++ b/aster-deposit-withdrawal.md @@ -238,7 +238,7 @@ curl -X POST "https://www.asterdex.com/bapi/futures/v1/private/future/aster/user |withdrawId | the withdraw request id, a unique id | |hash | the digest of user's signature | -# 6. withdraw by API [futures] +# 6. withdraw by API [evm] [futures] ### request: @@ -263,14 +263,8 @@ curl --location --request POST 'https://fapi.asterdex.com/fapi/aster/user-withdr ```json { - "code": "200", - "message": "success", - "messageDetail": null, - "data": { "withdrawId": "1234567", "hash": "0x9a40f0119b670fb6b155744b51981f91c4c4c8a20c333441a63853fe7d055c90" - }, - "success": true } ``` @@ -279,7 +273,7 @@ curl --location --request POST 'https://fapi.asterdex.com/fapi/aster/user-withdr |withdrawId | the withdraw request id, a unique id | |hash | the digest of user's signature | -# 7. withdraw by API [spot] +# 7. withdraw by API [evm] [spot] ### request: @@ -304,14 +298,8 @@ curl --location --request POST 'https://sapi.asterdex.com/api/v1/aster/user-with ```json { - "code": "200", - "message": "success", - "messageDetail": null, - "data": { "withdrawId": "1234567", "hash": "0x9a40f0119b670fb6b155744b51981f91c4c4c8a20c333441a63853fe7d055c90" - }, - "success": true } ``` @@ -320,7 +308,7 @@ curl --location --request POST 'https://sapi.asterdex.com/api/v1/aster/user-with |withdrawId | the withdraw request id, a unique id | |hash | the digest of user's signature | -# 8. withdraw by API [futures] +# 8. withdraw by API [solana] [futures] ### request: @@ -343,14 +331,8 @@ curl --location --request POST 'https://fapi.asterdex.com/fapi/aster/user-solana ```json { - "code": "200", - "message": "success", - "messageDetail": null, - "data": { "withdrawId": "1234567", "hash": "0x9a40f0119b670fb6b155744b51981f91c4c4c8a20c333441a63853fe7d055c90" - }, - "success": true } ``` - hash is not the transaction hash, just a unique value \ No newline at end of file From a057b15efc034edb5051350dd72dd662d595eb98 Mon Sep 17 00:00:00 2001 From: aodyc Date: Tue, 2 Dec 2025 16:33:58 +0800 Subject: [PATCH 036/131] add new api --- aster-deposit-withdrawal.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/aster-deposit-withdrawal.md b/aster-deposit-withdrawal.md index 765d318..5403dde 100644 --- a/aster-deposit-withdrawal.md +++ b/aster-deposit-withdrawal.md @@ -329,6 +329,35 @@ curl --location --request POST 'https://fapi.asterdex.com/fapi/aster/user-solana ### response: +```json +{ + "withdrawId": "1234567", + "hash": "0x9a40f0119b670fb6b155744b51981f91c4c4c8a20c333441a63853fe7d055c90" +} +``` +- hash is not the transaction hash, just a unique value + +# 9. withdraw by API [solana] [spot] + +### request: + +```shell +curl --location --request POST 'https://sapi.asterdex.com/api/v1/aster/user-solana-withdraw?chainId=101&asset=USDT&amount=0.97&fee=0.5&receiver=BzsJhmtg2UtQWNw6764DkK5Y4GPjc1XMzRqAGqSziymK&recvWindow=60000×tamp=1764663883270&signature=d2fbaef40388208b47e0326fafc50798206f5b198762110ce1bf8879b5d9da22' \ +--header 'Content-Type: application/json' \ +--header 'X-MBX-APIKEY: Your API KEY' +``` + +### params: +| param | type | required | description | +|---------------|--------|----------|-----------------------------------------------------------| +| amount | string | true | Withdraw amount in token unit | +| chainId | int | true | fix value 101 | +| asset | string | true | Currency name, e.g., USDT | +| fee | string | true | Withdraw fee in token unit | +| receiver | string | true | Withdraw receipt address, should be the save in signature | + +### response: + ```json { "withdrawId": "1234567", From 0ce72ece1c9ab6207b492b0685d98069fc845bbc Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Thu, 25 Dec 2025 12:06:04 +0800 Subject: [PATCH 037/131] remove sendto --- aster-finance-spot-api.md | 37 ------------------------------------ aster-finance-spot-api_CN.md | 37 ------------------------------------ 2 files changed, 74 deletions(-) diff --git a/aster-finance-spot-api.md b/aster-finance-spot-api.md index f1497ac..6c5bbb8 100644 --- a/aster-finance-spot-api.md +++ b/aster-finance-spot-api.md @@ -1193,7 +1193,6 @@ Retrieve all account orders; active, canceled, or completed. * By default, query data is from the last 7 days. - ## Perp-spot transfer (TRADE) **Response:** @@ -1221,42 +1220,6 @@ Retrieve all account orders; active, canceled, or completed. * kindType FUTURE_SPOT(future to spot)/SPOT_FUTURE(spot to future) -## Transfer asset to other address (TRADE) - -> **Response:** - -```javascript -{ - "tranId": 21841, - "status": "SUCCESS" -} -``` - -`` -POST /api/v1/asset/sendToAddress (HMAC SHA256) -`` - -**Weight:** -5 - -**Parameters:** - - -Name | Type | Mandatory | Description ----------------- | ------- | -------- | ---- -amount | DECIMAL | YES | -asset | STRING | YES | -toAddress | STRING | YES | -clientTranId | STRING | NO | -recvWindow | LONG | NO | -timestamp | LONG | YES | - -**Note:** -* The target address must be a valid existing account and must not be the same as the sender’s account. -* The toAddress must be an EVM address. -* If clientTranId is provided, its length must be at least 20 characters. - - ## Get withdraw fee (NONE) > **Response:** ```javascript diff --git a/aster-finance-spot-api_CN.md b/aster-finance-spot-api_CN.md index 3fd7663..3da1a0a 100644 --- a/aster-finance-spot-api_CN.md +++ b/aster-finance-spot-api_CN.md @@ -1385,43 +1385,6 @@ timestamp | LONG | YES | 时间戳 注意: * kindType 取值为FUTURE_SPOT(期货转现货),SPOT_FUTURE(现货转期货) -## 转账给其他地址账户 (TRADE) - -> **响应:** - -```javascript -{ - "tranId": 21841, //交易id - "status": "SUCCESS" //状态 -} -``` - -`` -POST /api/v1/asset/sendToAddress (HMAC SHA256) -`` - -**权重:** -1 - -**参数:** - - -名称 | 类型 | 是否必需 | 描述 ----------------- | ------- | -------- | ---- -amount | DECIMAL | YES | 数量 -asset | STRING | YES | 资产 -toAddress | STRING | YES | 目标地址 -clientTranId | STRING | NO | 交易id -recvWindow | LONG | NO | -timestamp | LONG | YES | 时间戳 - -注意: -* toAddress必须存在, 且不能为发送方账户 -* toAddress为evm地址 -* clientTranId如果传入则长度最少为20 - - - ## 现货提现手续费 (NONe) > **响应** ```javascript From d491c5366a3b08e38c39ff6b55a743fbc1fbe24c Mon Sep 17 00:00:00 2001 From: aodyc Date: Thu, 25 Dec 2025 20:23:24 +0800 Subject: [PATCH 038/131] change api params --- aster-deposit-withdrawal.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/aster-deposit-withdrawal.md b/aster-deposit-withdrawal.md index 5403dde..40ad9e4 100644 --- a/aster-deposit-withdrawal.md +++ b/aster-deposit-withdrawal.md @@ -258,6 +258,9 @@ curl --location --request POST 'https://fapi.asterdex.com/fapi/aster/user-withdr | nonce | string | true | Unique number, should be the save in signature | | receiver | string | true | Withdraw receipt address, should be the save in signature | | userSignature | string | true | EIP712 signature | +|timestamp|int| true| Current timestamp in milliseconds| +|recvWindow|int| false| The number of milliseconds after timestamp the request is valid for| +|signature|string| true| HMAC SHA256 signature of the request| ### response: @@ -293,6 +296,9 @@ curl --location --request POST 'https://sapi.asterdex.com/api/v1/aster/user-with | nonce | string | true | Unique number, should be the save in signature | | receiver | string | true | Withdraw receipt address, should be the save in signature | | userSignature | string | true | EIP712 signature | +|timestamp|int| true| Current timestamp in milliseconds| +|recvWindow|int| false| The number of milliseconds after timestamp the request is valid for| +|signature|string| true| HMAC SHA256 signature of the request| ### response: @@ -326,6 +332,9 @@ curl --location --request POST 'https://fapi.asterdex.com/fapi/aster/user-solana | asset | string | true | Currency name, e.g., USDT | | fee | string | true | Withdraw fee in token unit | | receiver | string | true | Withdraw receipt address, should be the save in signature | +|timestamp|int| true| Current timestamp in milliseconds| +|recvWindow|int| false| The number of milliseconds after timestamp the request is valid for| +|signature|string| true| HMAC SHA256 signature of the request| ### response: @@ -355,6 +364,9 @@ curl --location --request POST 'https://sapi.asterdex.com/api/v1/aster/user-sola | asset | string | true | Currency name, e.g., USDT | | fee | string | true | Withdraw fee in token unit | | receiver | string | true | Withdraw receipt address, should be the save in signature | +|timestamp|int| true| Current timestamp in milliseconds| +|recvWindow|int| false| The number of milliseconds after timestamp the request is valid for| +|signature|string| true| HMAC SHA256 signature of the request| ### response: From 896ed791a08b157cdd2853a6b715683babf77866 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Thu, 8 Jan 2026 15:02:58 +0800 Subject: [PATCH 039/131] testnet doc --- README.md | 8 + aster-finance-futures-api-testnet.md | 4371 ++++++++++++++++++++++++++ aster-finance-spot-api-testnet.md | 2624 ++++++++++++++++ 3 files changed, 7003 insertions(+) create mode 100644 aster-finance-futures-api-testnet.md create mode 100644 aster-finance-spot-api-testnet.md diff --git a/README.md b/README.md index b6b0d3f..e1849c3 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,10 @@ [Aster Finance Futures API V3 文档](./aster-finance-futures-api-v3_CN.md) +# Aster Finance Futures Testnet API V3 文档 + +[Aster Finance Futures Testnet API V3 文档](./aster-finance-futures-api-testnet.md) + # Aster Finance Futures API V3 PYTHON DEMO [Aster Finance Futures API V3 PYTHON DEMO](./v3-demo/tx.py) @@ -30,6 +34,10 @@ [Aster Finance Spot API 文档](./aster-finance-spot-api_CN.md) +# Aster Finance Spot Testnet API V3 文档 + +[Aster Finance Spot Testnet API V3 文档](./aster-finance-spot-api-testnet.md) + # Aster Finance Spot Asset Consolidation [Aster Finance Spot Asset Consolidation](./consolidation.js) diff --git a/aster-finance-futures-api-testnet.md b/aster-finance-futures-api-testnet.md new file mode 100644 index 0000000..89f24cf --- /dev/null +++ b/aster-finance-futures-api-testnet.md @@ -0,0 +1,4371 @@ +> > - [General Info](#general-info) + +- [General API Information](#general-api-information) + - [HTTP Return Codes](#http-return-codes) + - [Error Codes and Messages](#error-codes-and-messages) + - [General Information on Endpoints](#general-information-on-endpoints) +- [LIMITS](#limits) + - [IP Limits](#ip-limits) + - [Order Rate Limits](#order-rate-limits) +- [API authentication type](#api-authentication-type) +- [Authentication signature payload](#authentication-signature-payload) +- [Timing Security](#timing-security) +- [Endpoints requiring signature](#endpoints-requiring-signature) + - [POST /fapi/v3/order example](#example-of-post-fapiv3order) + - [GET /fapi/v3/order example](#Eexample-of-get-fapiv3order) + - [python script](#python-script) +- [Public Endpoints Info](#public-endpoints-info) + - [Terminology](#terminology) + - [ENUM definitions](#enum-definitions) +- [Filters](#filters) + - [Symbol filters](#symbol-filters) + - [PRICE_FILTER](#price_filter) + - [LOT_SIZE](#lot_size) + - [MARKET_LOT_SIZE](#market_lot_size) + - [MAX_NUM_ORDERS](#max_num_orders) + - [MAX_NUM_ALGO_ORDERS](#max_num_algo_orders) + - [PERCENT_PRICE](#percent_price) + - [MIN_NOTIONAL](#min_notional) +- [Market Data Endpoints](#market-data-endpoints) + - [Test Connectivity](#test-connectivity) + - [Check Server Time](#check-server-time) + - [Exchange Information](#exchange-information) + - [Order Book](#order-book) + - [Recent Trades List](#recent-trades-list) + - [Old Trades Lookup (MARKET_DATA)](#old-trades-lookup-market_data) + - [Compressed/Aggregate Trades List](#compressedaggregate-trades-list) + - [Kline/Candlestick Data](#klinecandlestick-data) + - [Index Price Kline/Candlestick Data](#index-price-klinecandlestick-data) + - [Mark Price Kline/Candlestick Data](#mark-price-klinecandlestick-data) + - [Mark Price](#mark-price) + - [Get Funding Rate History](#get-funding-rate-history) + - [24hr Ticker Price Change Statistics](#24hr-ticker-price-change-statistics) + - [Symbol Price Ticker](#symbol-price-ticker) + - [Symbol Order Book Ticker](#symbol-order-book-ticker) +- [Websocket Market Streams](#websocket-market-streams) + - [Live Subscribing/Unsubscribing to streams](#live-subscribingunsubscribing-to-streams) + - [Subscribe to a stream](#subscribe-to-a-stream) + - [Unsubscribe to a stream](#unsubscribe-to-a-stream) + - [Listing Subscriptions](#listing-subscriptions) + - [Setting Properties](#setting-properties) + - [Retrieving Properties](#retrieving-properties) + - [Error Messages](#error-messages) + - [Aggregate Trade Streams](#aggregate-trade-streams) + - [Mark Price Stream](#mark-price-stream) + - [Mark Price Stream for All market](#mark-price-stream-for-all-market) + - [Kline/Candlestick Streams](#klinecandlestick-streams) + - [Individual Symbol Mini Ticker Stream](#individual-symbol-mini-ticker-stream) + - [All Market Mini Tickers Stream](#all-market-mini-tickers-stream) + - [Individual Symbol Ticker Streams](#individual-symbol-ticker-streams) + - [All Market Tickers Streams](#all-market-tickers-streams) + - [Individual Symbol Book Ticker Streams](#individual-symbol-book-ticker-streams) + - [All Book Tickers Stream](#all-book-tickers-stream) + - [Liquidation Order Streams](#liquidation-order-streams) + - [All Market Liquidation Order Streams](#all-market-liquidation-order-streams) + - [Partial Book Depth Streams](#partial-book-depth-streams) + - [Diff. Book Depth Streams](#diff-book-depth-streams) + - [How to manage a local order book correctly](#how-to-manage-a-local-order-book-correctly) +- [Account/Trades Endpoints](#accounttrades-endpoints) + - [Change Position Mode(TRADE)](#change-position-modetrade) + - [Get Current Position Mode(USER_DATA)](#get-current-position-modeuser_data) + - [Change Multi-Assets Mode (TRADE)](#change-multi-assets-mode-trade) + - [Get Current Multi-Assets Mode (USER_DATA)](#get-current-multi-assets-mode-user_data) + - [New Order (TRADE)](#new-order--trade) + - [Place Multiple Orders (TRADE)](#place-multiple-orders--trade) + - [Transfer Between Futures And Spot (USER_DATA)](#transfer-between-futures-and-spot-user_data) + - [Query Order (USER_DATA)](#query-order-user_data) + - [Cancel Order (TRADE)](#cancel-order-trade) + - [Cancel All Open Orders (TRADE)](#cancel-all-open-orders-trade) + - [Cancel Multiple Orders (TRADE)](#cancel-multiple-orders-trade) + - [Auto-Cancel All Open Orders (TRADE)](#auto-cancel-all-open-orders-trade) + - [Query Current Open Order (USER_DATA)](#query-current-open-order-user_data) + - [Current All Open Orders (USER_DATA)](#current-all-open-orders-user_data) + - [All Orders (USER_DATA)](#all-orders-user_data) + - [Futures Account Balance v3 (USER_DATA)](#futures-account-balance-v3-user_data) + - [Account Information v3 (USER_DATA)](#account-information-v3-user_data) + - [Change Initial Leverage (TRADE)](#change-initial-leverage-trade) + - [Change Margin Type (TRADE)](#change-margin-type-trade) + - [Modify Isolated Position Margin (TRADE)](#modify-isolated-position-margin-trade) + - [Get Position Margin Change History (TRADE)](#get-position-margin-change-history-trade) + - [Position Information v3 (USER_DATA)](#position-information-v3-user_data) + - [Account Trade List (USER_DATA)](#account-trade-list-user_data) + - [Get Income History(USER_DATA)](#get-income-historyuser_data) + - [Notional and Leverage Brackets (USER_DATA)](#notional-and-leverage-brackets-user_data) + - [Position ADL Quantile Estimation (USER_DATA)](#position-adl-quantile-estimation-user_data) + - [User's Force Orders (USER_DATA)](#users-force-orders-user_data) + - [User Commission Rate (USER_DATA)](#user-commission-rate-user_data) +- [User Data Streams](#user-data-streams) + - [Start User Data Stream (USER_STREAM)](#start-user-data-stream-user_stream) + - [Keepalive User Data Stream (USER_STREAM)](#keepalive-user-data-stream-user_stream) + - [Close User Data Stream (USER_STREAM)](#close-user-data-stream-user_stream) + - [Event: User Data Stream Expired](#event-user-data-stream-expired) + - [Event: Margin Call](#event-margin-call) + - [Event: Balance and Position Update](#event-balance-and-position-update) + - [Event: Order Update](#event-order-update) + - [Event: Account Configuration Update previous Leverage Update](#event-account-configuration-update-previous-leverage-update) +- [Error Codes](#error-codes) + - [10xx - General Server or Network issues](#10xx---general-server-or-network-issues) + - [11xx - Request issues](#11xx---request-issues) + - [20xx - Processing Issues](#20xx---processing-issues) + - [40xx - Filters and other Issues](#40xx---filters-and-other-issues) + +# General Info + +## General API Information + +* This API may require the user's AGENT. +* To create an AGENT please [click here](https://www.asterdex-testnet.com/en/api-wallet) and switch to `Pro API` at the top +* The base endpoint is: **https://fapi.asterdex-testnet.com** +* All endpoints return either a JSON object or array. +* Data is returned in **ascending** order. Oldest first, newest last. +* All time and timestamp related fields are in milliseconds. +* All data types adopt definition in JAVA. + +### HTTP Return Codes + +* HTTP `4XX` return codes are used for for malformed requests; + the issue is on the sender's side. +* HTTP `403` return code is used when the WAF Limit (Web Application Firewall) has been violated. +* HTTP `429` return code is used when breaking a request rate limit. +* HTTP `418` return code is used when an IP has been auto-banned for continuing to send requests after receiving `429` codes. +* HTTP `5XX` return codes are used for internal errors; the issue is on + Aster's side. +* HTTP `503` return code is used when the API successfully sent the message but not get a response within the timeout period. + It is important to **NOT** treat this as a failure operation; the execution status is + **UNKNOWN** and could have been a success. + +### Error Codes and Messages + +* Any endpoint can return an ERROR + +> ***The error payload is as follows:*** + +```javascript +{ + "code": -1121, + "msg": "Invalid symbol." +} +``` + +* Specific error codes and messages defined in [Error Codes](#error-codes). + +### General Information on Endpoints + +* For `GET` endpoints, parameters must be sent as a `query string`. +* For POST, PUT, and DELETE method APIs, send data in the request body (content type application/x-www-form-urlencoded) +* Parameters may be sent in any order. + +## LIMITS + +* The `/fapi/v3/exchangeInfo` `rateLimits` array contains objects related to the exchange's `RAW_REQUEST`, `REQUEST_WEIGHT`, and `ORDER` rate limits. These are further defined in the `ENUM definitions` section under `Rate limiters (rateLimitType)`. +* A `429` will be returned when either rate limit is violated. + + + +### IP Limits + +* Every request will contain `X-MBX-USED-WEIGHT-(intervalNum)(intervalLetter)` in the response headers which has the current used weight for the IP for all request rate limiters defined. +* Each route has a `weight` which determines for the number of requests each endpoint counts for. Heavier endpoints and endpoints that do operations on multiple symbols will have a heavier `weight`. +* When a 429 is received, it's your obligation as an API to back off and not spam the API. +* **Repeatedly violating rate limits and/or failing to back off after receiving 429s will result in an automated IP ban (HTTP status 418).** +* IP bans are tracked and **scale in duration** for repeat offenders, **from 2 minutes to 3 days**. +* **The limits on the API are based on the IPs, not the API keys.** + + + +### Order Rate Limits + +* Every order response will contain a `X-MBX-ORDER-COUNT-(intervalNum)(intervalLetter)` header which has the current order count for the account for all order rate limiters defined. +* Rejected/unsuccessful orders are not guaranteed to have `X-MBX-ORDER-COUNT-**` headers in the response. +* **The order rate limit is counted against each account**. + +**Serious trading is about timing.** Networks can be unstable and unreliable, +which can lead to requests taking varying amounts of time to reach the +servers. With `recvWindow`, you can specify that the request must be +processed within a certain number of milliseconds or be rejected by the +server. + + + +## API authentication type + +* Each API has its own authentication type, which determines what kind of authentication is required when accessing it. +* If authentication is required, a signer should be included in the request body. + +| Security Type | Description | +| ------------- | ----------------------------------------- | +| NONE | API that does not require authentication | +| TRADE | A valid signer and signature are required | +| USER_DATA | A valid signer and signature are required | +| USER_STREAM | A valid signer and signature are required | +| MARKET_DATA | A valid signer and signature are required | + +## Authentication signature payload + +| Parameter | Description | +| --------- | ---------------------------------- | +| user | Main account wallet address | +| signer | API wallet address | +| nonce | Current timestamp, in microseconds | +| signature | Signature | + +## Endpoints requiring signature +* Security Type: TRADE, USER_DATA, USER_STREAM, MARKET_DATA +* After converting the API parameters to strings, sort them by their key values in ASCII order to generate the final string. Note: All parameter values must be treated as strings during the signing process. +* After generating the string, combine it with the authentication signature parameters user, signer, and nonce, then use Web3’s ABI parameter encoding to generate the bytecode. +* After generating the bytecode, use the Keccak algorithm to generate the hash. +* Use the private key of **API wallet address** to sign the hash using web3’s ECDSA signature algorithm, generating the final signature. + +## Example of POST /fapi/v3/order + +#### All parameters are passed through the request body (Python 3.9.6) + +#### The following parameters are API registration details. The values for user, signer, and privateKey are for demonstration purposes only (the privateKey corresponds to the signer). + +| Key | Value | Desc +| ---------- | ------------------------------------------------------------------ | ---------- | +| user | 0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e |Login wallet address | +| signer | 0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0 |[Click Here](https://www.asterdex-testnet.com/en/api-wallet) | +| privateKey | 0x4fd0a42218f3eae43a6ce26d22544e986139a01e5b34a62db53757ffca81bae1 |[Click Here](https://www.asterdex-testnet.com/en/api-wallet) | + +#### The nonce parameter is the current system time in microseconds. If it exceeds the system time or lags behind it by more than 5 seconds, the request is considered invalid. + +```python +#python +nonce = math.trunc(time.time()*1000000) +print(nonce) +#1748310859508867 +``` + +```java +//java +Instant now = Instant.now(); +long microsecond = now.getEpochSecond() * 1000000 + now.getNano() / 1000; +``` +#### Example: The following parameters are business request parameters. + +```python + +typed_data = { + "types": { + "EIP712Domain": [ + {"name": "name", "type": "string"}, + {"name": "version", "type": "string"}, + {"name": "chainId", "type": "uint256"}, + {"name": "verifyingContract", "type": "address"} + ], + "Message": [ + { "name": "msg", "type": "string" } + ] + }, + "primaryType": "Message", + "domain": { + "name": "AsterSignTransaction", + "version": "1", + "chainId": 714, + "verifyingContract": "0x0000000000000000000000000000000000000000" + }, + "message": { + "msg": "$msg" + } +} +``` + +#### Example: As a query string (using Python as an example). + +> **Step 1: As a query string** + +```python +import random +import time + +import requests +from eth_account.messages import encode_typed_data +from eth_account import Account + +from eip712 import typed_data + + +def get_url(my_dict) -> str: + return '&'.join(f'{key}={str(value)}'for key, value in my_dict.items()) + +def send_by_url() : + import random + import time + + import requests + from eth_account.messages import encode_typed_data + from eth_account import Account + + test_net_end_point = 'https://fapi.asterdex-testnet.com/fapi/v3/order' + param = 'symbol=BTCUSDT&side=BUY&type=LIMIT&quantity=1&price=9000&timeInForce=GTC' + + nonce = int(time.time()) * 1_000_000 + random.randint(0, 999999) + param += '&nonce=' + str(nonce) + param += '&user=' + '0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e' + param += '&signer=' + '0xbEf084ad26b44F002C3b55DB3bf7241003dABdab' + + typed_data['message']['msg'] = param + + message = encode_typed_data(full_message=typed_data) + + private_key = "*" + signed = Account.sign_message(message, private_key=private_key) + print(signed.signature.hex()) + + url = test_net_end_point + '?' + param + '&signature=' + signed.signature.hex() + + headers = { + 'Content-Type': 'application/x-www-form-urlencoded', + 'User-Agent': 'PythonApp/1.0' + } + print(url) + res = requests.post(url, headers=headers) + + print(res.text) + +if __name__ == '__main__': + send_by_url() + + +``` + +> **Step 1: As a body** + +```python +import random +import time + +import requests +from eth_account.messages import encode_typed_data +from eth_account import Account + +from eip712 import typed_data + + +def get_url(my_dict) -> str: + return '&'.join(f'{key}={str(value)}'for key, value in my_dict.items()) + +def send_by_body() : + my_dict = {"symbol": "BTCUSDT", "positionSide": "BOTH", "type": "LIMIT", "side": "BUY", + "timeInForce": "GTC", "quantity": "0.01", "price": "81000"} + + test_net_end_point = 'https://fapi.asterdex-testnet.com/fapi/v3/order' + + nonce = int(time.time()) * 1_000_000 + random.randint(0, 999999) + my_dict['nonce'] = str(nonce) + my_dict['user'] = '0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e' + my_dict['signer'] = '0xbEf084ad26b44F002C3b55DB3bf7241003dABdab' + + content = get_url(my_dict) + + typed_data['message']['msg'] = content + + message = encode_typed_data(full_message=typed_data) + + private_key = "*" + signed = Account.sign_message(message, private_key=private_key) + print(signed.signature.hex()) + + my_dict['signature'] = signed.signature.hex() + + headers = { + 'Content-Type': 'application/x-www-form-urlencoded', + 'User-Agent': 'PythonApp/1.0' + } + print(my_dict) + res = requests.post(test_net_end_point, data=my_dict, headers=headers) + + print(res.text) + +if __name__ == '__main__': + send_by_body() +``` + + +## Public Endpoints Info + +### Terminology + +* `base asset` refers to the asset that is the `quantity` of a symbol. +* `quote asset` refers to the asset that is the `price` of a symbol. + +### ENUM definitions + +**Symbol type:** + +* FUTURE + +**Contract type (contractType):** + +* PERPETUAL + +**Contract status(contractStatus,status):** + +* PENDING_TRADING +* TRADING +* PRE_SETTLE +* SETTLING +* CLOSE + +**Order status (status):** + +* NEW +* PARTIALLY_FILLED +* FILLED +* CANCELED +* REJECTED +* EXPIRED + +**Order types (orderTypes, type):** + +* LIMIT +* MARKET +* STOP +* STOP_MARKET +* TAKE_PROFIT +* TAKE_PROFIT_MARKET +* TRAILING_STOP_MARKET + +**Order side (side):** + +* BUY +* SELL + +**Position side (positionSide):** + +* BOTH +* LONG +* SHORT + +**Time in force (timeInForce):** + +* GTC - Good Till Cancel +* IOC - Immediate or Cancel +* FOK - Fill or Kill +* GTX - Good Till Crossing (Post Only) + +**Working Type (workingType)** + +* MARK_PRICE +* CONTRACT_PRICE + +**Response Type (newOrderRespType)** + +* ACK +* RESULT + +**Kline/Candlestick chart intervals:** + +m -> minutes; h -> hours; d -> days; w -> weeks; M -> months + +* 1m +* 3m +* 5m +* 15m +* 30m +* 1h +* 2h +* 4h +* 6h +* 8h +* 12h +* 1d +* 3d +* 1w +* 1M + +**Rate limiters (rateLimitType)** + +> REQUEST_WEIGHT + +```javascript +{ + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 2400 + } +``` + +> ORDERS + +```javascript +{ + "rateLimitType": "ORDERS", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200 + } +``` + +* REQUEST_WEIGHT +* ORDERS + +**Rate limit intervals (interval)** + +* MINUTE + +## Filters + +Filters define trading rules on a symbol or an exchange. + +### Symbol filters + +#### PRICE_FILTER + +> **/exchangeInfo format:** + +```javascript +{ + "filterType": "PRICE_FILTER", + "minPrice": "0.00000100", + "maxPrice": "100000.00000000", + "tickSize": "0.00000100" + } +``` + +The `PRICE_FILTER` defines the `price` rules for a symbol. There are 3 parts: + +* `minPrice` defines the minimum `price`/`stopPrice` allowed; disabled on `minPrice` == 0. +* `maxPrice` defines the maximum `price`/`stopPrice` allowed; disabled on `maxPrice` == 0. +* `tickSize` defines the intervals that a `price`/`stopPrice` can be increased/decreased by; disabled on `tickSize` == 0. + +Any of the above variables can be set to 0, which disables that rule in the `price filter`. In order to pass the `price filter`, the following must be true for `price`/`stopPrice` of the enabled rules: + +* `price` >= `minPrice` +* `price` <= `maxPrice` +* (`price`-`minPrice`) % `tickSize` == 0 + +#### LOT_SIZE + +> **/exchangeInfo format:** + +```javascript +{ + "filterType": "LOT_SIZE", + "minQty": "0.00100000", + "maxQty": "100000.00000000", + "stepSize": "0.00100000" + } +``` + +The `LOT_SIZE` filter defines the `quantity` (aka "lots" in auction terms) rules for a symbol. There are 3 parts: + +* `minQty` defines the minimum `quantity` allowed. +* `maxQty` defines the maximum `quantity` allowed. +* `stepSize` defines the intervals that a `quantity` can be increased/decreased by. + +In order to pass the `lot size`, the following must be true for `quantity`: + +* `quantity` >= `minQty` +* `quantity` <= `maxQty` +* (`quantity`-`minQty`) % `stepSize` == 0 + +#### MARKET_LOT_SIZE + +> **/exchangeInfo format:** + +```javascript +{ + "filterType": "MARKET_LOT_SIZE", + "minQty": "0.00100000", + "maxQty": "100000.00000000", + "stepSize": "0.00100000" + } +``` + +The `MARKET_LOT_SIZE` filter defines the `quantity` (aka "lots" in auction terms) rules for `MARKET` orders on a symbol. There are 3 parts: + +* `minQty` defines the minimum `quantity` allowed. +* `maxQty` defines the maximum `quantity` allowed. +* `stepSize` defines the intervals that a `quantity` can be increased/decreased by. + +In order to pass the `market lot size`, the following must be true for `quantity`: + +* `quantity` >= `minQty` +* `quantity` <= `maxQty` +* (`quantity`-`minQty`) % `stepSize` == 0 + +#### MAX_NUM_ORDERS + +> **/exchangeInfo format:** + +```javascript +{ + "filterType": "MAX_NUM_ORDERS", + "limit": 200 + } +``` + +The `MAX_NUM_ORDERS` filter defines the maximum number of orders an account is allowed to have open on a symbol. + +Note that both "algo" orders and normal orders are counted for this filter. + +#### MAX_NUM_ALGO_ORDERS + +> **/exchangeInfo format:** + +```javascript +{ + "filterType": "MAX_NUM_ALGO_ORDERS", + "limit": 100 + } +``` + +The `MAX_NUM_ALGO_ORDERS ` filter defines the maximum number of all kinds of algo orders an account is allowed to have open on a symbol. + +The algo orders include `STOP`, `STOP_MARKET`, `TAKE_PROFIT`, `TAKE_PROFIT_MARKET`, and `TRAILING_STOP_MARKET` orders. + +#### PERCENT_PRICE + +> **/exchangeInfo format:** + +```javascript +{ + "filterType": "PERCENT_PRICE", + "multiplierUp": "1.1500", + "multiplierDown": "0.8500", + "multiplierDecimal": 4 + } +``` + +The `PERCENT_PRICE` filter defines valid range for a price based on the mark price. + +In order to pass the `percent price`, the following must be true for `price`: + +* BUY: `price` <= `markPrice` * `multiplierUp` +* SELL: `price` >= `markPrice` * `multiplierDown` + +#### MIN_NOTIONAL + +> **/exchangeInfo format:** + +```javascript +{ + "filterType": "MIN_NOTIONAL", + "notional": "1" + } +``` + +The `MIN_NOTIONAL` filter defines the minimum notional value allowed for an order on a symbol. +An order's notional value is the `price` * `quantity`. +Since `MARKET` orders have no price, the mark price is used. + +--- + +# Market Data Endpoints + +## Test Connectivity + +> **Response:** + +```javascript +{} +``` + +``GET /fapi/v3/ping`` + +Test connectivity to the Rest API. + +**Weight:** +1 + +**Parameters:** +NONE + +## Check Server Time + +> **Response:** + +```javascript +{ + "serverTime": 1499827319559 +} +``` + +``GET /fapi/v3/time`` + +Test connectivity to the Rest API and get the current server time. + +**Weight:** +1 + +**Parameters:** +NONE + +## Exchange Information + +> **Response:** + +```javascript +{ + "exchangeFilters": [], + "rateLimits": [ + { + "interval": "MINUTE", + "intervalNum": 1, + "limit": 2400, + "rateLimitType": "REQUEST_WEIGHT" + }, + { + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200, + "rateLimitType": "ORDERS" + } + ], + "serverTime": 1565613908500, // Ignore please. If you want to check current server time, please check via "GET /fapi/v3/time" + "assets": [ // assets information + { + "asset": "BUSD", + "marginAvailable": true, // whether the asset can be used as margin in Multi-Assets mode + "autoAssetExchange": 0 // auto-exchange threshold in Multi-Assets margin mode + }, + { + "asset": "USDT", + "marginAvailable": true, + "autoAssetExchange": 0 + }, + { + "asset": "BTC", + "marginAvailable": false, + "autoAssetExchange": null + } + ], + "symbols": [ + { + "symbol": "DOGEUSDT", + "pair": "DOGEUSDT", + "contractType": "PERPETUAL", + "deliveryDate": 4133404800000, + "onboardDate": 1598252400000, + "status": "TRADING", + "maintMarginPercent": "2.5000", // ignore + "requiredMarginPercent": "5.0000", // ignore + "baseAsset": "BLZ", + "quoteAsset": "USDT", + "marginAsset": "USDT", + "pricePrecision": 5, // please do not use it as tickSize + "quantityPrecision": 0, // please do not use it as stepSize + "baseAssetPrecision": 8, + "quotePrecision": 8, + "underlyingType": "COIN", + "underlyingSubType": ["STORAGE"], + "settlePlan": 0, + "triggerProtect": "0.15", // threshold for algo order with "priceProtect" + "filters": [ + { + "filterType": "PRICE_FILTER", + "maxPrice": "300", + "minPrice": "0.0001", + "tickSize": "0.0001" + }, + { + "filterType": "LOT_SIZE", + "maxQty": "10000000", + "minQty": "1", + "stepSize": "1" + }, + { + "filterType": "MARKET_LOT_SIZE", + "maxQty": "590119", + "minQty": "1", + "stepSize": "1" + }, + { + "filterType": "MAX_NUM_ORDERS", + "limit": 200 + }, + { + "filterType": "MAX_NUM_ALGO_ORDERS", + "limit": 100 + }, + { + "filterType": "MIN_NOTIONAL", + "notional": "1", + }, + { + "filterType": "PERCENT_PRICE", + "multiplierUp": "1.1500", + "multiplierDown": "0.8500", + "multiplierDecimal": 4 + } + ], + "OrderType": [ + "LIMIT", + "MARKET", + "STOP", + "STOP_MARKET", + "TAKE_PROFIT", + "TAKE_PROFIT_MARKET", + "TRAILING_STOP_MARKET" + ], + "timeInForce": [ + "GTC", + "IOC", + "FOK", + "GTX" + ], + "liquidationFee": "0.010000", // liquidation fee rate + "marketTakeBound": "0.30", // the max price difference rate( from mark price) a market order can make + } + ], + "timezone": "UTC" +} +``` + +``GET /fapi/v3/exchangeInfo`` + +Current exchange trading rules and symbol information + +**Weight:** +1 + +**Parameters:** +NONE + +## Order Book + +> **Response:** + +```javascript +{ + "lastUpdateId": 1027024, + "E": 1589436922972, // Message output time + "T": 1589436922959, // Transaction time + "bids": [ + [ + "4.00000000", // PRICE + "431.00000000" // QTY + ] + ], + "asks": [ + [ + "4.00000200", + "12.00000000" + ] + ] +} +``` + +``GET /fapi/v3/depth`` + +**Weight:** + +Adjusted based on the limit: + +| Limit | Weight | +| ------------- | ------ | +| 5, 10, 20, 50 | 2 | +| 100 | 5 | +| 500 | 10 | +| 1000 | 20 | + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ------ | ------ | --------- | --------------------------------------------------------- | +| symbol | STRING | YES | | +| limit | INT | NO | Default 500; Valid limits:[5, 10, 20, 50, 100, 500, 1000] | + +## Recent Trades List + +> **Response:** + +```javascript +[ + { + "id": 28457, + "price": "4.00000100", + "qty": "12.00000000", + "quoteQty": "48.00", + "time": 1499865549590, + "isBuyerMaker": true, + } +] +``` + +``GET /fapi/v3/trades`` + +Get recent market trades + +**Weight:** +1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ------ | ------ | --------- | ---------------------- | +| symbol | STRING | YES | | +| limit | INT | NO | Default 500; max 1000. | + +* Market trades means trades filled in the order book. Only market trades will be returned, which means the insurance fund trades and ADL trades won't be returned. + +## Old Trades Lookup (MARKET_DATA) + +> **Response:** + +```javascript +[ + { + "id": 28457, + "price": "4.00000100", + "qty": "12.00000000", + "quoteQty": "8000.00", + "time": 1499865549590, + "isBuyerMaker": true, + } +] +``` + +``GET /fapi/v3/historicalTrades`` + +Get older market historical trades. + +**Weight:** +20 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ------ | ------ | --------- | ------------------------------------------------------- | +| symbol | STRING | YES | | +| limit | INT | NO | Default 500; max 1000. | +| fromId | LONG | NO | TradeId to fetch from. Default gets most recent trades. | + +* Market trades means trades filled in the order book. Only market trades will be returned, which means the insurance fund trades and ADL trades won't be returned. + +## Compressed/Aggregate Trades List + +> **Response:** + +```javascript +[ + { + "a": 26129, // Aggregate tradeId + "p": "0.01633102", // Price + "q": "4.70443515", // Quantity + "f": 27781, // First tradeId + "l": 27781, // Last tradeId + "T": 1498793709153, // Timestamp + "m": true, // Was the buyer the maker? + } +] +``` + +``GET /fapi/v3/aggTrades`` + +Get compressed, aggregate market trades. Market trades that fill at the time, from the same order, with the same price will have the quantity aggregated. + +**Weight:** +20 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| --------- | ------ | --------- | -------------------------------------------------------- | +| symbol | STRING | YES | | +| fromId | LONG | NO | ID to get aggregate trades from INCLUSIVE. | +| startTime | LONG | NO | Timestamp in ms to get aggregate trades from INCLUSIVE. | +| endTime | LONG | NO | Timestamp in ms to get aggregate trades until INCLUSIVE. | +| limit | INT | NO | Default 500; max 1000. | + +* If both startTime and endTime are sent, time between startTime and endTime must be less than 1 hour. +* If fromId, startTime, and endTime are not sent, the most recent aggregate trades will be returned. +* Only market trades will be aggregated and returned, which means the insurance fund trades and ADL trades won't be aggregated. + +## Kline/Candlestick Data + +> **Response:** + +```javascript +[ + [ + 1499040000000, // Open time + "0.01634790", // Open + "0.80000000", // High + "0.01575800", // Low + "0.01577100", // Close + "148976.11427815", // Volume + 1499644799999, // Close time + "2434.19055334", // Quote asset volume + 308, // Number of trades + "1756.87402397", // Taker buy base asset volume + "28.46694368", // Taker buy quote asset volume + "17928899.62484339" // Ignore. + ] +] +``` + +``GET /fapi/v3/klines`` + +Kline/candlestick bars for a symbol. +Klines are uniquely identified by their open time. + +**Weight:** based on parameter `LIMIT` + +| LIMIT | weight | +| ----------- | ------ | +| [1,100) | 1 | +| [100, 500) | 2 | +| [500, 1000] | 5 | + +> 1000 | 10 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| --------- | ------ | --------- | ---------------------- | +| symbol | STRING | YES | | +| interval | ENUM | YES | | +| startTime | LONG | NO | | +| endTime | LONG | NO | | +| limit | INT | NO | Default 500; max 1500. | + +* If startTime and endTime are not sent, the most recent klines are returned. + +## Index Price Kline/Candlestick Data + +> **Response:** + +```javascript +[ + [ + 1591256400000, // Open time + "9653.69440000", // Open + "9653.69640000", // High + "9651.38600000", // Low + "9651.55200000", // Close (or latest price) + "0 ", // Ignore + 1591256459999, // Close time + "0", // Ignore + 60, // Number of Data Points + "0", // Ignore + "0", // Ignore + "0" // Ignore + ] +] +``` + +``GET /fapi/v3/indexPriceKlines`` + +Kline/candlestick bars for the index price of a pair. + +Klines are uniquely identified by their open time. + +**Weight:** based on parameter `LIMIT` + +| LIMIT | weight | +| ----------- | ------ | +| [1,100) | 1 | +| [100, 500) | 2 | +| [500, 1000] | 5 | + +> 1000 | 10 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| --------- | ------ | --------- | ---------------------- | +| pair | STRING | YES | | +| interval | ENUM | YES | | +| startTime | LONG | NO | | +| endTime | LONG | NO | | +| limit | INT | NO | Default 500; max 1500. | + +* If startTime and endTime are not sent, the most recent klines are returned. + +## Mark Price Kline/Candlestick Data + +> **Response:** + +```javascript +[ + [ + 1591256460000, // Open time + "9653.29201333", // Open + "9654.56401333", // High + "9653.07367333", // Low + "9653.07367333", // Close (or latest price) + "0 ", // Ignore + 1591256519999, // Close time + "0", // Ignore + 60, // Number of Data Points + "0", // Ignore + "0", // Ignore + "0" // Ignore + ] +] +``` + +``GET /fapi/v3/markPriceKlines`` + +Kline/candlestick bars for the mark price of a symbol. + +Klines are uniquely identified by their open time. + +**Weight:** based on parameter `LIMIT` + +| LIMIT | weight | +| ----------- | ------ | +| [1,100) | 1 | +| [100, 500) | 2 | +| [500, 1000] | 5 | + +> 1000 | 10 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| --------- | ------ | --------- | ---------------------- | +| symbol | STRING | YES | | +| interval | ENUM | YES | | +| startTime | LONG | NO | | +| endTime | LONG | NO | | +| limit | INT | NO | Default 500; max 1500. | + +* If startTime and endTime are not sent, the most recent klines are returned. + +## Mark Price + +> **Response:** + +```javascript +{ + "symbol": "BTCUSDT", + "markPrice": "11793.63104562", // mark price + "indexPrice": "11781.80495970", // index price + "estimatedSettlePrice": "11781.16138815", // Estimated Settle Price, only useful in the last hour before the settlement starts. + "lastFundingRate": "0.00038246", // This is the lasted funding rate + "nextFundingTime": 1597392000000, + "interestRate": "0.00010000", + "time": 1597370495002 +} +``` + +> **OR (when symbol not sent)** + +```javascript +[ + { + "symbol": "BTCUSDT", + "markPrice": "11793.63104562", // mark price + "indexPrice": "11781.80495970", // index price + "estimatedSettlePrice": "11781.16138815", // Estimated Settle Price, only useful in the last hour before the settlement starts. + "lastFundingRate": "0.00038246", // This is the lasted funding rate + "nextFundingTime": 1597392000000, + "interestRate": "0.00010000", + "time": 1597370495002 + } +] +``` + +``GET /fapi/v3/premiumIndex`` + +Mark Price and Funding Rate + +**Weight:** +1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ------ | ------ | --------- | ----------- | +| symbol | STRING | NO | | + +## Get Funding Rate History + +> **Response:** + +```javascript +[ + { + "symbol": "BTCUSDT", + "fundingRate": "-0.03750000", + "fundingTime": 1570608000000, + }, + { + "symbol": "BTCUSDT", + "fundingRate": "0.00010000", + "fundingTime": 1570636800000, + } +] +``` + +``GET /fapi/v3/fundingRate`` + +**Weight:** +1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| --------- | ------ | --------- | ----------------------------------------------------- | +| symbol | STRING | NO | | +| startTime | LONG | NO | Timestamp in ms to get funding rate from INCLUSIVE. | +| endTime | LONG | NO | Timestamp in ms to get funding rate until INCLUSIVE. | +| limit | INT | NO | Default 100; max 1000 | + +* If `startTime` and `endTime` are not sent, the most recent `limit` datas are returned. +* If the number of data between `startTime` and `endTime` is larger than `limit`, return as `startTime` + `limit`. +* In ascending order. + +## 24hr Ticker Price Change Statistics + +> **Response:** + +```javascript +{ + "symbol": "BTCUSDT", + "priceChange": "-94.99999800", + "priceChangePercent": "-95.960", + "weightedAvgPrice": "0.29628482", + "prevClosePrice": "0.10002000", + "lastPrice": "4.00000200", + "lastQty": "200.00000000", + "openPrice": "99.00000000", + "highPrice": "100.00000000", + "lowPrice": "0.10000000", + "volume": "8913.30000000", + "quoteVolume": "15.30000000", + "openTime": 1499783499040, + "closeTime": 1499869899040, + "firstId": 28385, // First tradeId + "lastId": 28460, // Last tradeId + "count": 76 // Trade count +} +``` + +> OR + +```javascript +[ + { + "symbol": "BTCUSDT", + "priceChange": "-94.99999800", + "priceChangePercent": "-95.960", + "weightedAvgPrice": "0.29628482", + "prevClosePrice": "0.10002000", + "lastPrice": "4.00000200", + "lastQty": "200.00000000", + "openPrice": "99.00000000", + "highPrice": "100.00000000", + "lowPrice": "0.10000000", + "volume": "8913.30000000", + "quoteVolume": "15.30000000", + "openTime": 1499783499040, + "closeTime": 1499869899040, + "firstId": 28385, // First tradeId + "lastId": 28460, // Last tradeId + "count": 76 // Trade count + } +] +``` + +``GET /fapi/v3/ticker/24hr`` + +24 hour rolling window price change statistics. +**Careful** when accessing this with no symbol. + +**Weight:** +1 for a single symbol; +**40** when the symbol parameter is omitted + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ------ | ------ | --------- | ----------- | +| symbol | STRING | NO | | + +* If the symbol is not sent, tickers for all symbols will be returned in an array. + +## Symbol Price Ticker + +> **Response:** + +```javascript +{ + "symbol": "BTCUSDT", + "price": "6000.01", + "time": 1589437530011 // Transaction time +} +``` + +> OR + +```javascript +[ + { + "symbol": "BTCUSDT", + "price": "6000.01", + "time": 1589437530011 + } +] +``` + +``GET /fapi/v3/ticker/price`` + +Latest price for a symbol or symbols. + +**Weight:** +1 for a single symbol; +**2** when the symbol parameter is omitted + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ------ | ------ | --------- | ----------- | +| symbol | STRING | NO | | + +* If the symbol is not sent, prices for all symbols will be returned in an array. + +## Symbol Order Book Ticker + +> **Response:** + +```javascript +{ + "symbol": "BTCUSDT", + "bidPrice": "4.00000000", + "bidQty": "431.00000000", + "askPrice": "4.00000200", + "askQty": "9.00000000", + "time": 1589437530011 // Transaction time +} +``` + +> OR + +```javascript +[ + { + "symbol": "BTCUSDT", + "bidPrice": "4.00000000", + "bidQty": "431.00000000", + "askPrice": "4.00000200", + "askQty": "9.00000000", + "time": 1589437530011 + } +] +``` + +``GET /fapi/v3/ticker/bookTicker`` + +Best price/qty on the order book for a symbol or symbols. + +**Weight:** +1 for a single symbol; +**2** when the symbol parameter is omitted + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ------ | ------ | --------- | ----------- | +| symbol | STRING | NO | | + +* If the symbol is not sent, bookTickers for all symbols will be returned in an array. + +# Websocket Market Streams + +* The baseurl for websocket is **wss://fstream5.asterdex-testnet.com** +* Streams can be access either in a single raw stream or a combined stream +* Raw streams are accessed at **/ws/\** +* Combined streams are accessed at **/stream?streams=\/\/\** +* Combined stream events are wrapped as follows: **{"stream":"\","data":\}** +* All symbols for streams are **lowercase** +* A single connection is only valid for 24 hours; expect to be disconnected at the 24 hour mark +* The websocket server will send a `ping frame` every 5 minutes. If the websocket server does not receive a `pong frame` back from the connection within a 15 minute period, the connection will be disconnected. Unsolicited `pong frames` are allowed. +* WebSocket connections have a limit of 10 incoming messages per second. +* A connection that goes beyond the limit will be disconnected; IPs that are repeatedly disconnected may be banned. +* A single connection can listen to a maximum of **200** streams. +* Considering the possible data latency from RESTful endpoints during an extremely volatile market, it is highly recommended to get the order status, position, etc from the Websocket user data stream. + +## Live Subscribing/Unsubscribing to streams + +* The following data can be sent through the websocket instance in order to subscribe/unsubscribe from streams. Examples can be seen below. +* The `id` used in the JSON payloads is an unsigned INT used as an identifier to uniquely identify the messages going back and forth. + +### Subscribe to a stream + +> **Response** + +```javascript +{ + "result": null, + "id": 1 +} +``` + +* **Request** + + { + "method": "SUBSCRIBE", + "params": + [ + "btcusdt@aggTrade", + "btcusdt@depth" + ], + "id": 1 + } + +### Unsubscribe to a stream + +> **Response** + +```javascript +{ + "result": null, + "id": 312 +} +``` + +* **Request** + + { + "method": "UNSUBSCRIBE", + "params": + [ + "btcusdt@depth" + ], + "id": 312 + } + +### Listing Subscriptions + +> **Response** + +```javascript +{ + "result": [ + "btcusdt@aggTrade" + ], + "id": 3 +} +``` + +* **Request** + + { + "method": "LIST_SUBSCRIPTIONS", + "id": 3 + } + +### Setting Properties + +Currently, the only property can be set is to set whether `combined` stream payloads are enabled are not. +The combined property is set to `false` when connecting using `/ws/` ("raw streams") and `true` when connecting using `/stream/`. + +> **Response** + +```javascript +{ + "result": null, + "id": 5 +} +``` + +* **Request** + + { + "method": "SET_PROPERTY", + "params": + [ + "combined", + true + ], + "id": 5 + } + +### Retrieving Properties + +> **Response** + +```javascript +{ + "result": true, // Indicates that combined is set to true. + "id": 2 +} +``` + +* **Request** + + { + "method": "GET_PROPERTY", + "params": + [ + "combined" + ], + "id": 2 + } + +### Error Messages + +| Error Message | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------- | +| {"code": 0, "msg": "Unknown property"} | Parameter used in the`SET_PROPERTY` or `GET_PROPERTY` was invalid | +| {"code": 1, "msg": "Invalid value type: expected Boolean"} | Value should only be`true` or `false` | +| {"code": 2, "msg": "Invalid request: property name must be a string"} | Property name provided was invalid | +| {"code": 2, "msg": "Invalid request: request ID must be an unsigned integer"} | Parameter`id` had to be provided or the value provided in the `id` parameter is an unsupported type | +| {"code": 2, "msg": "Invalid request: unknown variant %s, expected one of`SUBSCRIBE`, `UNSUBSCRIBE`, `LIST_SUBSCRIPTIONS`, `SET_PROPERTY`, `GET_PROPERTY` at line 1 column 28"} | Possible typo in the provided method or provided method was neither of the expected values | +| {"code": 2, "msg": "Invalid request: too many parameters"} | Unnecessary parameters provided in the data | +| {"code": 2, "msg": "Invalid request: property name must be a string"} | Property name was not provided | +| {"code": 2, "msg": "Invalid request: missing field`method` at line 1 column 73"} | `method` was not provided in the data | +| {"code":3,"msg":"Invalid JSON: expected value at line %s column %s"} | JSON data sent has incorrect syntax. | + +## Aggregate Trade Streams + +> **Payload:** + +```javascript +{ + "e": "aggTrade", // Event type + "E": 123456789, // Event time + "s": "BTCUSDT", // Symbol + "a": 5933014, // Aggregate trade ID + "p": "0.001", // Price + "q": "100", // Quantity + "f": 100, // First trade ID + "l": 105, // Last trade ID + "T": 123456785, // Trade time + "m": true, // Is the buyer the market maker? +} +``` + +The Aggregate Trade Streams push market trade information that is aggregated for a single taker order every 100 milliseconds. + +**Stream Name:** +``@aggTrade`` + +**Update Speed:** 100ms + +* Only market trades will be aggregated, which means the insurance fund trades and ADL trades won't be aggregated. + +## Mark Price Stream + +> **Payload:** + +```javascript +{ + "e": "markPriceUpdate", // Event type + "E": 1562305380000, // Event time + "s": "BTCUSDT", // Symbol + "p": "11794.15000000", // Mark price + "i": "11784.62659091", // Index price + "P": "11784.25641265", // Estimated Settle Price, only useful in the last hour before the settlement starts + "r": "0.00038167", // Funding rate + "T": 1562306400000 // Next funding time + } +``` + +Mark price and funding rate for a single symbol pushed every 3 seconds or every second. + +**Stream Name:** +``@markPrice`` or ``@markPrice@1s`` + +**Update Speed:** 3000ms or 1000ms + +## Mark Price Stream for All market + +> **Payload:** + +```javascript +[ + { + "e": "markPriceUpdate", // Event type + "E": 1562305380000, // Event time + "s": "BTCUSDT", // Symbol + "p": "11185.87786614", // Mark price + "i": "11784.62659091" // Index price + "P": "11784.25641265", // Estimated Settle Price, only useful in the last hour before the settlement starts + "r": "0.00030000", // Funding rate + "T": 1562306400000 // Next funding time + } +] +``` + +Mark price and funding rate for all symbols pushed every 3 seconds or every second. + +**Stream Name:** +``!markPrice@arr`` or ``!markPrice@arr@1s`` + +**Update Speed:** 3000ms or 1000ms + +## Kline/Candlestick Streams + +> **Payload:** + +```javascript +{ + "e": "kline", // Event type + "E": 123456789, // Event time + "s": "BTCUSDT", // Symbol + "k": { + "t": 123400000, // Kline start time + "T": 123460000, // Kline close time + "s": "BTCUSDT", // Symbol + "i": "1m", // Interval + "f": 100, // First trade ID + "L": 200, // Last trade ID + "o": "0.0010", // Open price + "c": "0.0020", // Close price + "h": "0.0025", // High price + "l": "0.0015", // Low price + "v": "1000", // Base asset volume + "n": 100, // Number of trades + "x": false, // Is this kline closed? + "q": "1.0000", // Quote asset volume + "V": "500", // Taker buy base asset volume + "Q": "0.500", // Taker buy quote asset volume + "B": "123456" // Ignore + } +} +``` + +The Kline/Candlestick Stream push updates to the current klines/candlestick every 250 milliseconds (if existing). + +**Kline/Candlestick chart intervals:** + +m -> minutes; h -> hours; d -> days; w -> weeks; M -> months + +* 1m +* 3m +* 5m +* 15m +* 30m +* 1h +* 2h +* 4h +* 6h +* 8h +* 12h +* 1d +* 3d +* 1w +* 1M + +**Stream Name:** +``@kline_`` + +**Update Speed:** 250ms + +## Individual Symbol Mini Ticker Stream + +> **Payload:** + +```javascript +{ + "e": "24hrMiniTicker", // Event type + "E": 123456789, // Event time + "s": "BTCUSDT", // Symbol + "c": "0.0025", // Close price + "o": "0.0010", // Open price + "h": "0.0025", // High price + "l": "0.0010", // Low price + "v": "10000", // Total traded base asset volume + "q": "18" // Total traded quote asset volume + } +``` + +24hr rolling window mini-ticker statistics for a single symbol. These are NOT the statistics of the UTC day, but a 24hr rolling window from requestTime to 24hrs before. + +**Stream Name:** +``@miniTicker`` + +**Update Speed:** 500ms + +## All Market Mini Tickers Stream + +> **Payload:** + +```javascript +[ + { + "e": "24hrMiniTicker", // Event type + "E": 123456789, // Event time + "s": "BTCUSDT", // Symbol + "c": "0.0025", // Close price + "o": "0.0010", // Open price + "h": "0.0025", // High price + "l": "0.0010", // Low price + "v": "10000", // Total traded base asset volume + "q": "18" // Total traded quote asset volume + } +] +``` + +24hr rolling window mini-ticker statistics for all symbols. These are NOT the statistics of the UTC day, but a 24hr rolling window from requestTime to 24hrs before. Note that only tickers that have changed will be present in the array. + +**Stream Name:** +``!miniTicker@arr`` + +**Update Speed:** 1000ms + +## Individual Symbol Ticker Streams + +> **Payload:** + +```javascript +{ + "e": "24hrTicker", // Event type + "E": 123456789, // Event time + "s": "BTCUSDT", // Symbol + "p": "0.0015", // Price change + "P": "250.00", // Price change percent + "w": "0.0018", // Weighted average price + "c": "0.0025", // Last price + "Q": "10", // Last quantity + "o": "0.0010", // Open price + "h": "0.0025", // High price + "l": "0.0010", // Low price + "v": "10000", // Total traded base asset volume + "q": "18", // Total traded quote asset volume + "O": 0, // Statistics open time + "C": 86400000, // Statistics close time + "F": 0, // First trade ID + "L": 18150, // Last trade Id + "n": 18151 // Total number of trades +} +``` + +24hr rollwing window ticker statistics for a single symbol. These are NOT the statistics of the UTC day, but a 24hr rolling window from requestTime to 24hrs before. + +**Stream Name:** +``@ticker`` + +**Update Speed:** 500ms + +## All Market Tickers Streams + +> **Payload:** + +```javascript +[ + { + "e": "24hrTicker", // Event type + "E": 123456789, // Event time + "s": "BTCUSDT", // Symbol + "p": "0.0015", // Price change + "P": "250.00", // Price change percent + "w": "0.0018", // Weighted average price + "c": "0.0025", // Last price + "Q": "10", // Last quantity + "o": "0.0010", // Open price + "h": "0.0025", // High price + "l": "0.0010", // Low price + "v": "10000", // Total traded base asset volume + "q": "18", // Total traded quote asset volume + "O": 0, // Statistics open time + "C": 86400000, // Statistics close time + "F": 0, // First trade ID + "L": 18150, // Last trade Id + "n": 18151 // Total number of trades + } +] +``` + +24hr rollwing window ticker statistics for all symbols. These are NOT the statistics of the UTC day, but a 24hr rolling window from requestTime to 24hrs before. Note that only tickers that have changed will be present in the array. + +**Stream Name:** +``!ticker@arr`` + +**Update Speed:** 1000ms + +## Individual Symbol Book Ticker Streams + +> **Payload:** + +```javascript +{ + "e":"bookTicker", // event type + "u":400900217, // order book updateId + "E": 1568014460893, // event time + "T": 1568014460891, // transaction time + "s":"BNBUSDT", // symbol + "b":"25.35190000", // best bid price + "B":"31.21000000", // best bid qty + "a":"25.36520000", // best ask price + "A":"40.66000000" // best ask qty +} +``` + +Pushes any update to the best bid or ask's price or quantity in real-time for a specified symbol. + +**Stream Name:** `@bookTicker` + +**Update Speed:** Real-time + +## All Book Tickers Stream + +> **Payload:** + +```javascript +{ + // Same as @bookTicker payload +} +``` + +Pushes any update to the best bid or ask's price or quantity in real-time for all symbols. + +**Stream Name:** `!bookTicker` + +**Update Speed:** Real-time + +## Liquidation Order Streams + +> **Payload:** + +```javascript +{ + + "e":"forceOrder", // Event Type + "E":1568014460893, // Event Time + "o":{ + + "s":"BTCUSDT", // Symbol + "S":"SELL", // Side + "o":"LIMIT", // Order Type + "f":"IOC", // Time in Force + "q":"0.014", // Original Quantity + "p":"9910", // Price + "ap":"9910", // Average Price + "X":"FILLED", // Order Status + "l":"0.014", // Order Last Filled Quantity + "z":"0.014", // Order Filled Accumulated Quantity + "T":1568014460893, // Order Trade Time + + } + +} +``` + +The Liquidation Order Snapshot Streams push force liquidation order information for specific symbol. + +For each symbol,only the latest one liquidation order within 1000ms will be pushed as the snapshot. If no liquidation happens in the interval of 1000ms, no stream will be pushed. + +**Stream Name:** ``@forceOrder`` + +**Update Speed:** 1000ms + +## All Market Liquidation Order Streams + +> **Payload:** + +```javascript +{ + + "e":"forceOrder", // Event Type + "E":1568014460893, // Event Time + "o":{ + + "s":"BTCUSDT", // Symbol + "S":"SELL", // Side + "o":"LIMIT", // Order Type + "f":"IOC", // Time in Force + "q":"0.014", // Original Quantity + "p":"9910", // Price + "ap":"9910", // Average Price + "X":"FILLED", // Order Status + "l":"0.014", // Order Last Filled Quantity + "z":"0.014", // Order Filled Accumulated Quantity + "T":1568014460893, // Order Trade Time + + } + +} +``` + +The All Liquidation Order Snapshot Streams push force liquidation order information for all symbols in the market. + +For each symbol,only the latest one liquidation order within 1000ms will be pushed as the snapshot. If no liquidation happens in the interval of 1000ms, no stream will be pushed. + +**Stream Name:** ``!forceOrder@arr`` + +**Update Speed:** 1000ms + +## Partial Book Depth Streams + +> **Payload:** + +```javascript +{ + "e": "depthUpdate", // Event type + "E": 1571889248277, // Event time + "T": 1571889248276, // Transaction time + "s": "BTCUSDT", + "U": 390497796, + "u": 390497878, + "pu": 390497794, + "b": [ // Bids to be updated + [ + "7403.89", // Price Level to be + "0.002" // Quantity + ], + [ + "7403.90", + "3.906" + ], + [ + "7404.00", + "1.428" + ], + [ + "7404.85", + "5.239" + ], + [ + "7405.43", + "2.562" + ] + ], + "a": [ // Asks to be updated + [ + "7405.96", // Price level to be + "3.340" // Quantity + ], + [ + "7406.63", + "4.525" + ], + [ + "7407.08", + "2.475" + ], + [ + "7407.15", + "4.800" + ], + [ + "7407.20", + "0.175" + ] + ] +} +``` + +Top **** bids and asks, Valid **** are 5, 10, or 20. + +**Stream Names:** `@depth` OR `@depth@500ms` OR `@depth@100ms`. + +**Update Speed:** 250ms, 500ms or 100ms + +## Diff. Book Depth Streams + +> **Payload:** + +```javascript +{ + "e": "depthUpdate", // Event type + "E": 123456789, // Event time + "T": 123456788, // Transaction time + "s": "BTCUSDT", // Symbol + "U": 157, // First update ID in event + "u": 160, // Final update ID in event + "pu": 149, // Final update Id in last stream(ie `u` in last stream) + "b": [ // Bids to be updated + [ + "0.0024", // Price level to be updated + "10" // Quantity + ] + ], + "a": [ // Asks to be updated + [ + "0.0026", // Price level to be updated + "100" // Quantity + ] + ] +} +``` + +Bids and asks, pushed every 250 milliseconds, 500 milliseconds, 100 milliseconds (if existing) + +**Stream Name:** +``@depth`` OR ``@depth@500ms`` OR ``@depth@100ms`` + +**Update Speed:** 250ms, 500ms, 100ms + +## How to manage a local order book correctly + +1. Open a stream to **wss://fstream.asterdex-testnet.com/stream?streams=btcusdt@depth**. +2. Buffer the events you receive from the stream. For same price, latest received update covers the previous one. +3. Get a depth snapshot from **https://fapi.asterdex-testnet.com/fapi/v3/depth?symbol=BTCUSDT&limit=1000** . +4. Drop any event where `u` is < `lastUpdateId` in the snapshot. +5. The first processed event should have `U` <= `lastUpdateId` **AND** `u` >= `lastUpdateId` +6. While listening to the stream, each new event's `pu` should be equal to the previous event's `u`, otherwise initialize the process from step 3. +7. The data in each event is the **absolute** quantity for a price level. +8. If the quantity is 0, **remove** the price level. +9. Receiving an event that removes a price level that is not in your local order book can happen and is normal. + +# Account/Trades Endpoints + + + +## Change Position Mode(TRADE) + +> **Response:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +``POST /fapi/v3/positionSide/dual (HMAC SHA256)`` + +Change user's position mode (Hedge Mode or One-way Mode ) on ***EVERY symbol*** + +**Weight:** +1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ---------------- | ------ | --------- | ----------------------------------------- | +| dualSidePosition | STRING | YES | "true": Hedge Mode; "false": One-way Mode | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +## Get Current Position Mode(USER_DATA) + +> **Response:** + +```javascript +{ + "dualSidePosition": true // "true": Hedge Mode; "false": One-way Mode +} +``` + +``GET /fapi/v3/positionSide/dual (HMAC SHA256)`` + +Get user's position mode (Hedge Mode or One-way Mode ) on ***EVERY symbol*** + +**Weight:** +30 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ---------- | ---- | --------- | ----------- | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +## Change Multi-Assets Mode (TRADE) + +> **Response:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +``POST /fapi/v3/multiAssetsMargin (HMAC SHA256)`` + +Change user's Multi-Assets mode (Multi-Assets Mode or Single-Asset Mode) on ***Every symbol*** + +**Weight:** +1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ----------------- | ------ | --------- | ----------------------------------------------------- | +| multiAssetsMargin | STRING | YES | "true": Multi-Assets Mode; "false": Single-Asset Mode | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +## Get Current Multi-Assets Mode (USER_DATA) + +> **Response:** + +```javascript +{ + "multiAssetsMargin": true // "true": Multi-Assets Mode; "false": Single-Asset Mode +} +``` + +``GET /fapi/v3/multiAssetsMargin (HMAC SHA256)`` + +Get user's Multi-Assets mode (Multi-Assets Mode or Single-Asset Mode) on ***Every symbol*** + +**Weight:** +30 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ---------- | ---- | --------- | ----------- | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +## New Order (TRADE) + +> **Response:** + +```javascript +{ + "clientOrderId": "testOrder", + "cumQty": "0", + "cumQuote": "0", + "executedQty": "0", + "orderId": 22542179, + "avgPrice": "0.00000", + "origQty": "10", + "price": "0", + "reduceOnly": false, + "side": "BUY", + "positionSide": "SHORT", + "status": "NEW", + "stopPrice": "9300", // please ignore when order type is TRAILING_STOP_MARKET + "closePosition": false, // if Close-All + "symbol": "BTCUSDT", + "timeInForce": "GTC", + "type": "TRAILING_STOP_MARKET", + "origType": "TRAILING_STOP_MARKET", + "activatePrice": "9020", // activation price, only return with TRAILING_STOP_MARKET order + "priceRate": "0.3", // callback rate, only return with TRAILING_STOP_MARKET order + "updateTime": 1566818724722, + "workingType": "CONTRACT_PRICE", + "priceProtect": false // if conditional order trigger is protected +} +``` + +``POST /fapi/v3/order (HMAC SHA256)`` + +Send in a new order. + +**Weight:** +1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ---------------- | ------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------- | +| symbol | STRING | YES | | +| side | ENUM | YES | | +| positionSide | ENUM | NO | Default`BOTH` for One-way Mode ; `LONG` or `SHORT` for Hedge Mode. It must be sent in Hedge Mode. | +| type | ENUM | YES | | +| timeInForce | ENUM | NO | | +| quantity | DECIMAL | NO | Cannot be sent with`closePosition`=`true`(Close-All) | +| reduceOnly | STRING | NO | "true" or "false". default "false". Cannot be sent in Hedge Mode; cannot be sent with`closePosition`=`true` | +| price | DECIMAL | NO | | +| newClientOrderId | STRING | NO | A unique id among open orders. Automatically generated if not sent. Can only be string following the rule:`^[\.A-Z\:/a-z0-9_-]{1,36}$` | +| stopPrice | DECIMAL | NO | Used with`STOP/STOP_MARKET` or `TAKE_PROFIT/TAKE_PROFIT_MARKET` orders. | +| closePosition | STRING | NO | `true`, `false`;Close-All,used with `STOP_MARKET` or `TAKE_PROFIT_MARKET`. | +| activationPrice | DECIMAL | NO | Used with`TRAILING_STOP_MARKET` orders, default as the latest price(supporting different `workingType`) | +| callbackRate | DECIMAL | NO | Used with`TRAILING_STOP_MARKET` orders, min 0.1, max 5 where 1 for 1% | +| workingType | ENUM | NO | stopPrice triggered by: "MARK_PRICE", "CONTRACT_PRICE". Default "CONTRACT_PRICE" | +| priceProtect | STRING | NO | "TRUE" or "FALSE", default "FALSE". Used with`STOP/STOP_MARKET` or `TAKE_PROFIT/TAKE_PROFIT_MARKET` orders. | +| newOrderRespType | ENUM | NO | "ACK", "RESULT", default "ACK" | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +Additional mandatory parameters based on `type`: + +| Type | Additional mandatory parameters | +| -------------------------------- | ---------------------------------- | +| `LIMIT` | `timeInForce`, `quantity`, `price` | +| `MARKET` | `quantity` | +| `STOP/TAKE_PROFIT` | `quantity`, `price`, `stopPrice` | +| `STOP_MARKET/TAKE_PROFIT_MARKET` | `stopPrice` | +| `TRAILING_STOP_MARKET` | `callbackRate` | + +* Order with type `STOP`, parameter `timeInForce` can be sent ( default `GTC`). +* Order with type `TAKE_PROFIT`, parameter `timeInForce` can be sent ( default `GTC`). +* Condition orders will be triggered when: + + * If parameter`priceProtect`is sent as true: + + * when price reaches the `stopPrice` ,the difference rate between "MARK_PRICE" and "CONTRACT_PRICE" cannot be larger than the "triggerProtect" of the symbol + * "triggerProtect" of a symbol can be got from `GET /fapi/v3/exchangeInfo` + * `STOP`, `STOP_MARKET`: + + * BUY: latest price ("MARK_PRICE" or "CONTRACT_PRICE") >= `stopPrice` + * SELL: latest price ("MARK_PRICE" or "CONTRACT_PRICE") <= `stopPrice` + * `TAKE_PROFIT`, `TAKE_PROFIT_MARKET`: + + * BUY: latest price ("MARK_PRICE" or "CONTRACT_PRICE") <= `stopPrice` + * SELL: latest price ("MARK_PRICE" or "CONTRACT_PRICE") >= `stopPrice` + * `TRAILING_STOP_MARKET`: + + * BUY: the lowest price after order placed <= `activationPrice`, and the latest price >= the lowest price * (1 + `callbackRate`) + * SELL: the highest price after order placed >= `activationPrice`, and the latest price <= the highest price * (1 - `callbackRate`) +* For `TRAILING_STOP_MARKET`, if you got such error code.``{"code": -2021, "msg": "Order would immediately trigger."}``means that the parameters you send do not meet the following requirements: + + * BUY: `activationPrice` should be smaller than latest price. + * SELL: `activationPrice` should be larger than latest price. +* If `newOrderRespType ` is sent as `RESULT` : + + * `MARKET` order: the final FILLED result of the order will be return directly. + * `LIMIT` order with special `timeInForce`: the final status result of the order(FILLED or EXPIRED) will be returned directly. +* `STOP_MARKET`, `TAKE_PROFIT_MARKET` with `closePosition`=`true`: + + * Follow the same rules for condition orders. + * If triggered,**close all** current long position( if `SELL`) or current short position( if `BUY`). + * Cannot be used with `quantity` paremeter + * Cannot be used with `reduceOnly` parameter + * In Hedge Mode,cannot be used with `BUY` orders in `LONG` position side. and cannot be used with `SELL` orders in `SHORT` position side + +## Place Multiple Orders (TRADE) + +> **Response:** + +```javascript +[ + { + "clientOrderId": "testOrder", + "cumQty": "0", + "cumQuote": "0", + "executedQty": "0", + "orderId": 22542179, + "avgPrice": "0.00000", + "origQty": "10", + "price": "0", + "reduceOnly": false, + "side": "BUY", + "positionSide": "SHORT", + "status": "NEW", + "stopPrice": "9300", // please ignore when order type is TRAILING_STOP_MARKET + "symbol": "BTCUSDT", + "timeInForce": "GTC", + "type": "TRAILING_STOP_MARKET", + "origType": "TRAILING_STOP_MARKET", + "activatePrice": "9020", // activation price, only return with TRAILING_STOP_MARKET order + "priceRate": "0.3", // callback rate, only return with TRAILING_STOP_MARKET order + "updateTime": 1566818724722, + "workingType": "CONTRACT_PRICE", + "priceProtect": false // if conditional order trigger is protected + }, + { + "code": -2022, + "msg": "ReduceOnly Order is rejected." + } +] +``` + +``POST /fapi/v3/batchOrders (HMAC SHA256)`` + +**Weight:** +5 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ----------- | ---------- | --------- | ------------------------ | +| batchOrders | LIST | YES | order list. Max 5 orders | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +**Where ``batchOrders`` is the list of order parameters in JSON** + +| Name | Type | Mandatory | Description | +| ---------------- | ------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------- | +| symbol | STRING | YES | | +| side | ENUM | YES | | +| positionSide | ENUM | NO | Default`BOTH` for One-way Mode ; `LONG` or `SHORT` for Hedge Mode. It must be sent with Hedge Mode. | +| type | ENUM | YES | | +| timeInForce | ENUM | NO | | +| quantity | DECIMAL | YES | | +| reduceOnly | STRING | NO | "true" or "false". default "false". | +| price | DECIMAL | NO | | +| newClientOrderId | STRING | NO | A unique id among open orders. Automatically generated if not sent. Can only be string following the rule:`^[\.A-Z\:/a-z0-9_-]{1,36}$` | +| stopPrice | DECIMAL | NO | Used with`STOP/STOP_MARKET` or `TAKE_PROFIT/TAKE_PROFIT_MARKET` orders. | +| activationPrice | DECIMAL | NO | Used with`TRAILING_STOP_MARKET` orders, default as the latest price(supporting different `workingType`) | +| callbackRate | DECIMAL | NO | Used with`TRAILING_STOP_MARKET` orders, min 0.1, max 4 where 1 for 1% | +| workingType | ENUM | NO | stopPrice triggered by: "MARK_PRICE", "CONTRACT_PRICE". Default "CONTRACT_PRICE" | +| priceProtect | STRING | NO | "TRUE" or "FALSE", default "FALSE". Used with`STOP/STOP_MARKET` or `TAKE_PROFIT/TAKE_PROFIT_MARKET` orders. | +| newOrderRespType | ENUM | NO | "ACK", "RESULT", default "ACK" | + +* Paremeter rules are same with `New Order` +* Batch orders are processed concurrently, and the order of matching is not guaranteed. +* The order of returned contents for batch orders is the same as the order of the order list. + + +## Transfer Between Futures And Spot (USER_DATA) + +> **Response:** + +```javascript +{ + "tranId": 21841, //transaction id + "status": "SUCCESS" //status +} +``` + +`` +POST /fapi/v3/asset/wallet/transfer (HMAC SHA256) +`` + +**Weight:** +5 + +**Parameters:** + +Name | Type | Mandatory | Description +---------------- | ------- | -------- | ---- +amount | DECIMAL | YES | amount +asset | STRING | YES | asset +clientTranId | STRING | YES | transaction id +kindType | STRING | YES | kindType +timestamp | LONG | YES | timestamp + +Notes: + +* kindType can take the following values: + FUTURE_SPOT (futures converted to spot) + SPOT_FUTURE (spot converted to futures) + + +## Query Order (USER_DATA) + +> **Response:** + +```javascript +{ + "avgPrice": "0.00000", + "clientOrderId": "abc", + "cumQuote": "0", + "executedQty": "0", + "orderId": 1917641, + "origQty": "0.40", + "origType": "TRAILING_STOP_MARKET", + "price": "0", + "reduceOnly": false, + "side": "BUY", + "positionSide": "SHORT", + "status": "NEW", + "stopPrice": "9300", // please ignore when order type is TRAILING_STOP_MARKET + "closePosition": false, // if Close-All + "symbol": "BTCUSDT", + "time": 1579276756075, // order time + "timeInForce": "GTC", + "type": "TRAILING_STOP_MARKET", + "activatePrice": "9020", // activation price, only return with TRAILING_STOP_MARKET order + "priceRate": "0.3", // callback rate, only return with TRAILING_STOP_MARKET order + "updateTime": 1579276756075, // update time + "workingType": "CONTRACT_PRICE", + "priceProtect": false // if conditional order trigger is protected +} +``` + +``GET /fapi/v3/order (HMAC SHA256)`` + +Check an order's status. + +**Weight:** +1 + +* These orders will not be found: + * order status is `CANCELED` or `EXPIRED`, **AND** + * order has NO filled trade, **AND** + * created time + 7 days < current time + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ----------------- | ------ | --------- | ----------- | +| symbol | STRING | YES | | +| orderId | LONG | NO | | +| origClientOrderId | STRING | NO | | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +Notes: + +* Either `orderId` or `origClientOrderId` must be sent. + +## Cancel Order (TRADE) + +> **Response:** + +```javascript +{ + "clientOrderId": "myOrder1", + "cumQty": "0", + "cumQuote": "0", + "executedQty": "0", + "orderId": 283194212, + "origQty": "11", + "origType": "TRAILING_STOP_MARKET", + "price": "0", + "reduceOnly": false, + "side": "BUY", + "positionSide": "SHORT", + "status": "CANCELED", + "stopPrice": "9300", // please ignore when order type is TRAILING_STOP_MARKET + "closePosition": false, // if Close-All + "symbol": "BTCUSDT", + "timeInForce": "GTC", + "type": "TRAILING_STOP_MARKET", + "activatePrice": "9020", // activation price, only return with TRAILING_STOP_MARKET order + "priceRate": "0.3", // callback rate, only return with TRAILING_STOP_MARKET order + "updateTime": 1571110484038, + "workingType": "CONTRACT_PRICE", + "priceProtect": false // if conditional order trigger is protected +} +``` + +``DELETE /fapi/v3/order (HMAC SHA256)`` + +Cancel an active order. + +**Weight:** +1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ----------------- | ------ | --------- | ----------- | +| symbol | STRING | YES | | +| orderId | LONG | NO | | +| origClientOrderId | STRING | NO | | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +Either `orderId` or `origClientOrderId` must be sent. + +## Cancel All Open Orders (TRADE) + +> **Response:** + +```javascript +{ + "code": "200", + "msg": "The operation of cancel all open order is done." +} +``` + +``DELETE /fapi/v3/allOpenOrders (HMAC SHA256)`` + +**Weight:** +1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ---------- | ------ | --------- | ----------- | +| symbol | STRING | YES | | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +## Cancel Multiple Orders (TRADE) + +> **Response:** + +```javascript +[ + { + "clientOrderId": "myOrder1", + "cumQty": "0", + "cumQuote": "0", + "executedQty": "0", + "orderId": 283194212, + "origQty": "11", + "origType": "TRAILING_STOP_MARKET", + "price": "0", + "reduceOnly": false, + "side": "BUY", + "positionSide": "SHORT", + "status": "CANCELED", + "stopPrice": "9300", // please ignore when order type is TRAILING_STOP_MARKET + "closePosition": false, // if Close-All + "symbol": "BTCUSDT", + "timeInForce": "GTC", + "type": "TRAILING_STOP_MARKET", + "activatePrice": "9020", // activation price, only return with TRAILING_STOP_MARKET order + "priceRate": "0.3", // callback rate, only return with TRAILING_STOP_MARKET order + "updateTime": 1571110484038, + "workingType": "CONTRACT_PRICE", + "priceProtect": false // if conditional order trigger is protected + }, + { + "code": -2011, + "msg": "Unknown order sent." + } +] +``` + +``DELETE /fapi/v3/batchOrders (HMAC SHA256)`` + +**Weight:** +1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| --------------------- | -------------- | --------- | ----------------------------------------------------------------------------------------------- | +| symbol | STRING | YES | | +| orderIdList | LIST\ | NO | max length 10 e.g. [1234567,2345678] | +| origClientOrderIdList | LIST\ | NO | max length 10 e.g. ["my_id_1","my_id_2"], encode the double quotes. No space after comma. | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +Either `orderIdList` or `origClientOrderIdList ` must be sent. + +## Auto-Cancel All Open Orders (TRADE) + +> **Response:** + +```javascript +{ + "symbol": "BTCUSDT", + "countdownTime": "100000" +} +``` + +Cancel all open orders of the specified symbol at the end of the specified countdown. + +``POST /fapi/v3/countdownCancelAll (HMAC SHA256)`` + +**Weight:** +10 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ------------- | ------ | --------- | -------------------------------------------------------- | +| symbol | STRING | YES | | +| countdownTime | LONG | YES | countdown time, 1000 for 1 second. 0 to cancel the timer | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +* The endpoint should be called repeatedly as heartbeats so that the existing countdown time can be canceled and replaced by a new one. +* Example usage: + Call this endpoint at 30s intervals with an countdownTime of 120000 (120s). + If this endpoint is not called within 120 seconds, all your orders of the specified symbol will be automatically canceled. + If this endpoint is called with an countdownTime of 0, the countdown timer will be stopped. +* The system will check all countdowns **approximately every 10 milliseconds**, so please note that sufficient redundancy should be considered when using this function. We do not recommend setting the countdown time to be too precise or too small. + +## Query Current Open Order (USER_DATA) + +> **Response:** + +```javascript +{ + "avgPrice": "0.00000", + "clientOrderId": "abc", + "cumQuote": "0", + "executedQty": "0", + "orderId": 1917641, + "origQty": "0.40", + "origType": "TRAILING_STOP_MARKET", + "price": "0", + "reduceOnly": false, + "side": "BUY", + "positionSide": "SHORT", + "status": "NEW", + "stopPrice": "9300", // please ignore when order type is TRAILING_STOP_MARKET + "closePosition": false, // if Close-All + "symbol": "BTCUSDT", + "time": 1579276756075, // order time + "timeInForce": "GTC", + "type": "TRAILING_STOP_MARKET", + "activatePrice": "9020", // activation price, only return with TRAILING_STOP_MARKET order + "priceRate": "0.3", // callback rate, only return with TRAILING_STOP_MARKET order + "updateTime": 1579276756075, + "workingType": "CONTRACT_PRICE", + "priceProtect": false // if conditional order trigger is protected +} +``` + +``GET /fapi/v3/openOrder (HMAC SHA256)`` + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ----------------- | ------ | --------- | ----------- | +| symbol | STRING | YES | | +| orderId | LONG | NO | | +| origClientOrderId | STRING | NO | | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +* Either`orderId` or `origClientOrderId` must be sent +* If the queried order has been filled or cancelled, the error message "Order does not exist" will be returned. + +## Current All Open Orders (USER_DATA) + +> **Response:** + +```javascript +[ + { + "avgPrice": "0.00000", + "clientOrderId": "abc", + "cumQuote": "0", + "executedQty": "0", + "orderId": 1917641, + "origQty": "0.40", + "origType": "TRAILING_STOP_MARKET", + "price": "0", + "reduceOnly": false, + "side": "BUY", + "positionSide": "SHORT", + "status": "NEW", + "stopPrice": "9300", // please ignore when order type is TRAILING_STOP_MARKET + "closePosition": false, // if Close-All + "symbol": "BTCUSDT", + "time": 1579276756075, // order time + "timeInForce": "GTC", + "type": "TRAILING_STOP_MARKET", + "activatePrice": "9020", // activation price, only return with TRAILING_STOP_MARKET order + "priceRate": "0.3", // callback rate, only return with TRAILING_STOP_MARKET order + "updateTime": 1579276756075, // update time + "workingType": "CONTRACT_PRICE", + "priceProtect": false // if conditional order trigger is protected + } +] +``` + +``GET /fapi/v3/openOrders (HMAC SHA256)`` + +Get all open orders on a symbol. **Careful** when accessing this with no symbol. + +**Weight:** +1 for a single symbol; **40** when the symbol parameter is omitted + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ---------- | ------ | --------- | ----------- | +| symbol | STRING | NO | | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +* If the symbol is not sent, orders for all symbols will be returned in an array. + +## All Orders (USER_DATA) + +> **Response:** + +```javascript +[ + { + "avgPrice": "0.00000", + "clientOrderId": "abc", + "cumQuote": "0", + "executedQty": "0", + "orderId": 1917641, + "origQty": "0.40", + "origType": "TRAILING_STOP_MARKET", + "price": "0", + "reduceOnly": false, + "side": "BUY", + "positionSide": "SHORT", + "status": "NEW", + "stopPrice": "9300", // please ignore when order type is TRAILING_STOP_MARKET + "closePosition": false, // if Close-All + "symbol": "BTCUSDT", + "time": 1579276756075, // order time + "timeInForce": "GTC", + "type": "TRAILING_STOP_MARKET", + "activatePrice": "9020", // activation price, only return with TRAILING_STOP_MARKET order + "priceRate": "0.3", // callback rate, only return with TRAILING_STOP_MARKET order + "updateTime": 1579276756075, // update time + "workingType": "CONTRACT_PRICE", + "priceProtect": false // if conditional order trigger is protected + } +] +``` + +``GET /fapi/v3/allOrders (HMAC SHA256)`` + +Get all account orders; active, canceled, or filled. + +* These orders will not be found: + * order status is `CANCELED` or `EXPIRED`, **AND** + * order has NO filled trade, **AND** + * created time + 7 days < current time + +**Weight:** +5 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ---------- | ------ | --------- | ---------------------- | +| symbol | STRING | YES | | +| orderId | LONG | NO | | +| startTime | LONG | NO | | +| endTime | LONG | NO | | +| limit | INT | NO | Default 500; max 1000. | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +**Notes:** + +* If `orderId` is set, it will get orders >= that `orderId`. Otherwise most recent orders are returned. +* The query time period must be less then 7 days( default as the recent 7 days). + +## Futures Account Balance v3 (USER_DATA) + +> **Response:** + +```javascript +[ + { + "accountAlias": "SgsR", // unique account code + "asset": "USDT", // asset name + "balance": "122607.35137903", // wallet balance + "crossWalletBalance": "23.72469206", // crossed wallet balance + "crossUnPnl": "0.00000000" // unrealized profit of crossed positions + "availableBalance": "23.72469206", // available balance + "maxWithdrawAmount": "23.72469206", // maximum amount for transfer out + "marginAvailable": true, // whether the asset can be used as margin in Multi-Assets mode + "updateTime": 1617939110373 + } +] +``` + +``GET /fapi/v3/balance (HMAC SHA256)`` + +**Weight:** +5 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ---------- | ---- | --------- | ----------- | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +## Account Information v3 (USER_DATA) + +> **Response:** + +```javascript +{ + "feeTier": 0, // account commisssion tier + "canTrade": true, // if can trade + "canDeposit": true, // if can transfer in asset + "canWithdraw": true, // if can transfer out asset + "updateTime": 0, + "totalInitialMargin": "0.00000000", // total initial margin required with current mark price (useless with isolated positions), only for USDT asset + "totalMaintMargin": "0.00000000", // total maintenance margin required, only for USDT asset + "totalWalletBalance": "23.72469206", // total wallet balance, only for USDT asset + "totalUnrealizedProfit": "0.00000000", // total unrealized profit, only for USDT asset + "totalMarginBalance": "23.72469206", // total margin balance, only for USDT asset + "totalPositionInitialMargin": "0.00000000", // initial margin required for positions with current mark price, only for USDT asset + "totalOpenOrderInitialMargin": "0.00000000", // initial margin required for open orders with current mark price, only for USDT asset + "totalCrossWalletBalance": "23.72469206", // crossed wallet balance, only for USDT asset + "totalCrossUnPnl": "0.00000000", // unrealized profit of crossed positions, only for USDT asset + "availableBalance": "23.72469206", // available balance, only for USDT asset + "maxWithdrawAmount": "23.72469206" // maximum amount for transfer out, only for USDT asset + "assets": [ + { + "asset": "USDT", // asset name + "walletBalance": "23.72469206", // wallet balance + "unrealizedProfit": "0.00000000", // unrealized profit + "marginBalance": "23.72469206", // margin balance + "maintMargin": "0.00000000", // maintenance margin required + "initialMargin": "0.00000000", // total initial margin required with current mark price + "positionInitialMargin": "0.00000000", //initial margin required for positions with current mark price + "openOrderInitialMargin": "0.00000000", // initial margin required for open orders with current mark price + "crossWalletBalance": "23.72469206", // crossed wallet balance + "crossUnPnl": "0.00000000" // unrealized profit of crossed positions + "availableBalance": "23.72469206", // available balance + "maxWithdrawAmount": "23.72469206", // maximum amount for transfer out + "marginAvailable": true, // whether the asset can be used as margin in Multi-Assets mode + "updateTime": 1625474304765 // last update time + }, + { + "asset": "BUSD", // asset name + "walletBalance": "103.12345678", // wallet balance + "unrealizedProfit": "0.00000000", // unrealized profit + "marginBalance": "103.12345678", // margin balance + "maintMargin": "0.00000000", // maintenance margin required + "initialMargin": "0.00000000", // total initial margin required with current mark price + "positionInitialMargin": "0.00000000", //initial margin required for positions with current mark price + "openOrderInitialMargin": "0.00000000", // initial margin required for open orders with current mark price + "crossWalletBalance": "103.12345678", // crossed wallet balance + "crossUnPnl": "0.00000000" // unrealized profit of crossed positions + "availableBalance": "103.12345678", // available balance + "maxWithdrawAmount": "103.12345678", // maximum amount for transfer out + "marginAvailable": true, // whether the asset can be used as margin in Multi-Assets mode + "updateTime": 1625474304765 // last update time + } + ], + "positions": [ // positions of all symbols in the market are returned + // only "BOTH" positions will be returned with One-way mode + // only "LONG" and "SHORT" positions will be returned with Hedge mode + { + "symbol": "BTCUSDT", // symbol name + "initialMargin": "0", // initial margin required with current mark price + "maintMargin": "0", // maintenance margin required + "unrealizedProfit": "0.00000000", // unrealized profit + "positionInitialMargin": "0", // initial margin required for positions with current mark price + "openOrderInitialMargin": "0", // initial margin required for open orders with current mark price + "leverage": "100", // current initial leverage + "isolated": true, // if the position is isolated + "entryPrice": "0.00000", // average entry price + "maxNotional": "250000", // maximum available notional with current leverage + "positionSide": "BOTH", // position side + "positionAmt": "0", // position amount + "updateTime": 0 // last update time + } + ] +} +``` + +``GET /fapi/v3/account (HMAC SHA256)`` + +Get current account information. + +**Weight:** +5 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ---------- | ---- | --------- | ----------- | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +## Change Initial Leverage (TRADE) + +> **Response:** + +```javascript +{ + "leverage": 21, + "maxNotionalValue": "1000000", + "symbol": "BTCUSDT" +} +``` + +``POST /fapi/v3/leverage (HMAC SHA256)`` + +Change user's initial leverage of specific symbol market. + +**Weight:** +1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ---------- | ------ | --------- | ------------------------------------------ | +| symbol | STRING | YES | | +| leverage | INT | YES | target initial leverage: int from 1 to 125 | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +## Change Margin Type (TRADE) + +> **Response:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +``POST /fapi/v3/marginType (HMAC SHA256)`` + +**Weight:** +1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ---------- | ------ | --------- | ----------------- | +| symbol | STRING | YES | | +| marginType | ENUM | YES | ISOLATED, CROSSED | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +## Modify Isolated Position Margin (TRADE) + +> **Response:** + +```javascript +{ + "amount": 100.0, + "code": 200, + "msg": "Successfully modify position margin.", + "type": 1 +} +``` + +``POST /fapi/v3/positionMargin (HMAC SHA256)`` + +**Weight:** +1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ------------ | ------- | --------- | --------------------------------------------------------------------------------------------------- | +| symbol | STRING | YES | | +| positionSide | ENUM | NO | Default`BOTH` for One-way Mode ; `LONG` or `SHORT` for Hedge Mode. It must be sent with Hedge Mode. | +| amount | DECIMAL | YES | | +| type | INT | YES | 1: Add position margin,2: Reduce position margin | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +* Only for isolated symbol + +## Get Position Margin Change History (TRADE) + +> **Response:** + +```javascript +[ + { + "amount": "23.36332311", + "asset": "USDT", + "symbol": "BTCUSDT", + "time": 1578047897183, + "type": 1, + "positionSide": "BOTH" + }, + { + "amount": "100", + "asset": "USDT", + "symbol": "BTCUSDT", + "time": 1578047900425, + "type": 1, + "positionSide": "LONG" + } +] +``` + +``GET /fapi/v3/positionMargin/history (HMAC SHA256)`` + +**Weight:** +1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ---------- | ------ | --------- | ------------------------------------------------- | +| symbol | STRING | YES | | +| type | INT | NO | 1: Add position margin,2: Reduce position margin | +| startTime | LONG | NO | | +| endTime | LONG | NO | | +| limit | INT | NO | Default: 500 | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +## Position Information v3 (USER_DATA) + +> **Response:** + +> For One-way position mode: + +```javascript +[ + { + "entryPrice": "0.00000", + "marginType": "isolated", + "isAutoAddMargin": "false", + "isolatedMargin": "0.00000000", + "leverage": "10", + "liquidationPrice": "0", + "markPrice": "6679.50671178", + "maxNotionalValue": "20000000", + "positionAmt": "0.000", + "symbol": "BTCUSDT", + "unRealizedProfit": "0.00000000", + "positionSide": "BOTH", + "updateTime": 0 + } +] +``` + +> For Hedge position mode: + +```javascript +[ + { + "entryPrice": "6563.66500", + "marginType": "isolated", + "isAutoAddMargin": "false", + "isolatedMargin": "15517.54150468", + "leverage": "10", + "liquidationPrice": "5930.78", + "markPrice": "6679.50671178", + "maxNotionalValue": "20000000", + "positionAmt": "20.000", + "symbol": "BTCUSDT", + "unRealizedProfit": "2316.83423560" + "positionSide": "LONG", + "updateTime": 1625474304765 + }, + { + "entryPrice": "0.00000", + "marginType": "isolated", + "isAutoAddMargin": "false", + "isolatedMargin": "5413.95799991", + "leverage": "10", + "liquidationPrice": "7189.95", + "markPrice": "6679.50671178", + "maxNotionalValue": "20000000", + "positionAmt": "-10.000", + "symbol": "BTCUSDT", + "unRealizedProfit": "-1156.46711780" + "positionSide": "SHORT", + "updateTime": 0 + } +] +``` + +``GET /fapi/v3/positionRisk (HMAC SHA256)`` + +Get current position information. + +**Weight:** +5 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ---------- | ------ | --------- | ----------- | +| symbol | STRING | NO | | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +**Note** +Please use with user data stream `ACCOUNT_UPDATE` to meet your timeliness and accuracy needs. + +## Account Trade List (USER_DATA) + +> **Response:** + +```javascript +[ + { + "buyer": false, + "commission": "-0.07819010", + "commissionAsset": "USDT", + "id": 698759, + "maker": false, + "orderId": 25851813, + "price": "7819.01", + "qty": "0.002", + "quoteQty": "15.63802", + "realizedPnl": "-0.91539999", + "side": "SELL", + "positionSide": "SHORT", + "symbol": "BTCUSDT", + "time": 1569514978020 + } +] +``` + +``GET /fapi/v3/userTrades (HMAC SHA256)`` + +Get trades for a specific account and symbol. + +**Weight:** +5 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ---------- | ------ | --------- | -------------------------------------------------------- | +| symbol | STRING | YES | | +| startTime | LONG | NO | | +| endTime | LONG | NO | | +| fromId | LONG | NO | Trade id to fetch from. Default gets most recent trades. | +| limit | INT | NO | Default 500; max 1000. | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +* 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. +* The parameter `fromId` cannot be sent with `startTime` or `endTime`. + +## Get Income History(USER_DATA) + +> **Response:** + +```javascript +[ + { + "symbol": "", // trade symbol, if existing + "incomeType": "TRANSFER", // income type + "income": "-0.37500000", // income amount + "asset": "USDT", // income asset + "info":"TRANSFER", // extra information + "time": 1570608000000, + "tranId":"9689322392", // transaction id + "tradeId":"" // trade id, if existing + }, + { + "symbol": "BTCUSDT", + "incomeType": "COMMISSION", + "income": "-0.01000000", + "asset": "USDT", + "info":"COMMISSION", + "time": 1570636800000, + "tranId":"9689322392", + "tradeId":"2059192" + } +] +``` + +``GET /fapi/v3/income (HMAC SHA256)`` + +**Weight:** +30 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ---------- | ------ | --------- | -------------------------------------------------------------------------------------------------------------------------------- | +| symbol | STRING | NO | | +| incomeType | STRING | NO | "TRANSFER","WELCOME_BONUS", "REALIZED_PNL","FUNDING_FEE", "COMMISSION", "INSURANCE_CLEAR", and "MARKET_MERCHANT_RETURN_REWARD" | +| startTime | LONG | NO | Timestamp in ms to get funding from INCLUSIVE. | +| endTime | LONG | NO | Timestamp in ms to get funding until INCLUSIVE. | +| limit | INT | NO | Default 100; max 1000 | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +* If neither `startTime` nor `endTime` is sent, the recent 7-day data will be returned. +* If `incomeType ` is not sent, all kinds of flow will be returned +* "trandId" is unique in the same incomeType for a user + +## Notional and Leverage Brackets (USER_DATA) + +> **Response:** + +```javascript +[ + { + "symbol": "ETHUSDT", + "brackets": [ + { + "bracket": 1, // Notional bracket + "initialLeverage": 75, // Max initial leverage for this bracket + "notionalCap": 10000, // Cap notional of this bracket + "notionalFloor": 0, // Notional threshold of this bracket + "maintMarginRatio": 0.0065, // Maintenance ratio for this bracket + "cum":0 // Auxiliary number for quick calculation + + }, + ] + } +] +``` + +> **OR** (if symbol sent) + +```javascript +{ + "symbol": "ETHUSDT", + "brackets": [ + { + "bracket": 1, + "initialLeverage": 75, + "notionalCap": 10000, + "notionalFloor": 0, + "maintMarginRatio": 0.0065, + "cum":0 + }, + ] +} +``` + +``GET /fapi/v3/leverageBracket`` + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ---------- | ------ | --------- | ----------- | +| symbol | STRING | NO | | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +## Position ADL Quantile Estimation (USER_DATA) + +> **Response:** + +```javascript +[ + { + "symbol": "ETHUSDT", + "adlQuantile": + { + // if the positions of the symbol are crossed margined in Hedge Mode, "LONG" and "SHORT" will be returned a same quantile value, and "HEDGE" will be returned instead of "BOTH". + "LONG": 3, + "SHORT": 3, + "HEDGE": 0 // only a sign, ignore the value + } + }, + { + "symbol": "BTCUSDT", + "adlQuantile": + { + // for positions of the symbol are in One-way Mode or isolated margined in Hedge Mode + "LONG": 1, // adl quantile for "LONG" position in hedge mode + "SHORT": 2, // adl qauntile for "SHORT" position in hedge mode + "BOTH": 0 // adl qunatile for position in one-way mode + } + } + ] +``` + +``GET /fapi/v3/adlQuantile`` + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ---------- | ------ | --------- | ----------- | +| symbol | STRING | NO | | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +* Values update every 30s. +* Values 0, 1, 2, 3, 4 shows the queue position and possibility of ADL from low to high. +* For positions of the symbol are in One-way Mode or isolated margined in Hedge Mode, "LONG", "SHORT", and "BOTH" will be returned to show the positions' adl quantiles of different position sides. +* If the positions of the symbol are crossed margined in Hedge Mode: + + * "HEDGE" as a sign will be returned instead of "BOTH"; + * A same value caculated on unrealized pnls on long and short sides' positions will be shown for "LONG" and "SHORT" when there are positions in both of long and short sides. + +## User's Force Orders (USER_DATA) + +> **Response:** + +```javascript +[ + { + "orderId": 6071832819, + "symbol": "BTCUSDT", + "status": "FILLED", + "clientOrderId": "autoclose-1596107620040000020", + "price": "10871.09", + "avgPrice": "10913.21000", + "origQty": "0.001", + "executedQty": "0.001", + "cumQuote": "10.91321", + "timeInForce": "IOC", + "type": "LIMIT", + "reduceOnly": false, + "closePosition": false, + "side": "SELL", + "positionSide": "BOTH", + "stopPrice": "0", + "workingType": "CONTRACT_PRICE", + "origType": "LIMIT", + "time": 1596107620044, + "updateTime": 1596107620087 + } + { + "orderId": 6072734303, + "symbol": "BTCUSDT", + "status": "FILLED", + "clientOrderId": "adl_autoclose", + "price": "11023.14", + "avgPrice": "10979.82000", + "origQty": "0.001", + "executedQty": "0.001", + "cumQuote": "10.97982", + "timeInForce": "GTC", + "type": "LIMIT", + "reduceOnly": false, + "closePosition": false, + "side": "BUY", + "positionSide": "SHORT", + "stopPrice": "0", + "workingType": "CONTRACT_PRICE", + "origType": "LIMIT", + "time": 1596110725059, + "updateTime": 1596110725071 + } +] +``` + +``GET /fapi/v3/forceOrders`` + +**Weight:** 20 with symbol, 50 without symbol + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ------------- | ------ | --------- | ----------------------------------------------------------- | +| symbol | STRING | NO | | +| autoCloseType | ENUM | NO | "LIQUIDATION" for liquidation orders, "ADL" for ADL orders. | +| startTime | LONG | NO | | +| endTime | LONG | NO | | +| limit | INT | NO | Default 50; max 100. | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +* If "autoCloseType" is not sent, orders with both of the types will be returned +* If "startTime" is not sent, data within 7 days before "endTime" can be queried + +## User Commission Rate (USER_DATA) + +> **Response:** + +```javascript +{ + "symbol": "BTCUSDT", + "makerCommissionRate": "0.0002", // 0.02% + "takerCommissionRate": "0.0004" // 0.04% +} +``` + +``GET /fapi/v3/commissionRate (HMAC SHA256)`` + +**Weight:** +20 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ---------- | ------ | --------- | ----------- | +| symbol | STRING | YES | | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +# User Data Streams + +* The base API endpoint is: **https://fapi.asterdex-testnet.com** +* A User Data Stream `listenKey` is valid for 60 minutes after creation. +* Doing a `PUT` on a `listenKey` will extend its validity for 60 minutes. +* Doing a `DELETE` on a `listenKey` will close the stream and invalidate the `listenKey`. +* Doing a `POST` on an account with an active `listenKey` will return the currently active `listenKey` and extend its validity for 60 minutes. +* The baseurl for websocket is **wss://fstream.asterdex-testnet.com** +* User Data Streams are accessed at **/ws/\** +* User data stream payloads are **not guaranteed** to be in order during heavy periods; **make sure to order your updates using E** +* A single connection to **fstream.asterdex-testnet.com** is only valid for 24 hours; expect to be disconnected at the 24 hour mark + +## Start User Data Stream (USER_STREAM) + +> **Response:** + +```javascript +{ + "listenKey": "pqia91ma19a5s61cv6a81va65sdf19v8a65a1a5s61cv6a81va65sdf19v8a65a1" +} +``` + +``POST /fapi/v3/listenKey`` + +Start a new user data stream. The stream will close after 60 minutes unless a keepalive is sent. If the account has an active `listenKey`, that `listenKey` will be returned and its validity will be extended for 60 minutes. + +**Weight:** +1 + +**Parameters:** + +None + +## Keepalive User Data Stream (USER_STREAM) + +> **Response:** + +```javascript +{} +``` + +``PUT /fapi/v3/listenKey`` + +Keepalive a user data stream to prevent a time out. User data streams will close after 60 minutes. It's recommended to send a ping about every 60 minutes. + +**Weight:** +1 + +**Parameters:** + +None + +## Close User Data Stream (USER_STREAM) + +> **Response:** + +```javascript +{} +``` + +``DELETE /fapi/v3/listenKey`` + +Close out a user data stream. + +**Weight:** +1 + +**Parameters:** + +None + +## Event: User Data Stream Expired + +> **Payload:** + +```javascript +{ + 'e': 'listenKeyExpired', // event type + 'E': 1576653824250 // event time +} +``` + +When the `listenKey` used for the user data stream turns expired, this event will be pushed. + +**Notice:** + +* This event is not related to the websocket disconnection. +* This event will be received only when a valid `listenKey` in connection got expired. +* No more user data event will be updated after this event received until a new valid `listenKey` used. + +## Event: Margin Call + +> **Payload:** + +```javascript +{ + "e":"MARGIN_CALL", // Event Type + "E":1587727187525, // Event Time + "cw":"3.16812045", // Cross Wallet Balance. Only pushed with crossed position margin call + "p":[ // Position(s) of Margin Call + { + "s":"ETHUSDT", // Symbol + "ps":"LONG", // Position Side + "pa":"1.327", // Position Amount + "mt":"CROSSED", // Margin Type + "iw":"0", // Isolated Wallet (if isolated position) + "mp":"187.17127", // Mark Price + "up":"-1.166074", // Unrealized PnL + "mm":"1.614445" // Maintenance Margin Required + } + ] +} +``` + +* When the user's position risk ratio is too high, this stream will be pushed. +* This message is only used as risk guidance information and is not recommended for investment strategies. +* In the case of a highly volatile market, there may be the possibility that the user's position has been liquidated at the same time when this stream is pushed out. + +## Event: Balance and Position Update + +> **Payload:** + +```javascript +{ + "e": "ACCOUNT_UPDATE", // Event Type + "E": 1564745798939, // Event Time + "T": 1564745798938 , // Transaction + "a": // Update Data + { + "m":"ORDER", // Event reason type + "B":[ // Balances + { + "a":"USDT", // Asset + "wb":"122624.12345678", // Wallet Balance + "cw":"100.12345678", // Cross Wallet Balance + "bc":"50.12345678" // Balance Change except PnL and Commission + }, + { + "a":"BUSD", + "wb":"1.00000000", + "cw":"0.00000000", + "bc":"-49.12345678" + } + ], + "P":[ + { + "s":"BTCUSDT", // Symbol + "pa":"0", // Position Amount + "ep":"0.00000", // Entry Price + "cr":"200", // (Pre-fee) Accumulated Realized + "up":"0", // Unrealized PnL + "mt":"isolated", // Margin Type + "iw":"0.00000000", // Isolated Wallet (if isolated position) + "ps":"BOTH" // Position Side + }, + { + "s":"BTCUSDT", + "pa":"20", + "ep":"6563.66500", + "cr":"0", + "up":"2850.21200", + "mt":"isolated", + "iw":"13200.70726908", + "ps":"LONG" + }, + { + "s":"BTCUSDT", + "pa":"-10", + "ep":"6563.86000", + "cr":"-45.04000000", + "up":"-1423.15600", + "mt":"isolated", + "iw":"6570.42511771", + "ps":"SHORT" + } + ] + } +} +``` + +Event type is `ACCOUNT_UPDATE`. + +* When balance or position get updated, this event will be pushed. + + * `ACCOUNT_UPDATE` will be pushed only when update happens on user's account, including changes on balances, positions, or margin type. + * Unfilled orders or cancelled orders will not make the event `ACCOUNT_UPDATE` pushed, since there's no change on positions. + * Only positions of symbols with non-zero isolatd wallet or non-zero position amount will be pushed in the "position" part of the event `ACCOUNT_UPDATE` when any position changes. +* When "FUNDING FEE" changes to the user's balance, the event will be pushed with the brief message: + + * When "FUNDING FEE" occurs in a **crossed position**, `ACCOUNT_UPDATE` will be pushed with only the balance `B`(including the "FUNDING FEE" asset only), without any position `P` message. + * When "FUNDING FEE" occurs in an **isolated position**, `ACCOUNT_UPDATE` will be pushed with only the balance `B`(including the "FUNDING FEE" asset only) and the relative position message `P`( including the isolated position on which the "FUNDING FEE" occurs only, without any other position message). +* The field "m" represents the reason type for the event and may shows the following possible types: + + * DEPOSIT + * WITHDRAW + * ORDER + * FUNDING_FEE + * WITHDRAW_REJECT + * ADJUSTMENT + * INSURANCE_CLEAR + * ADMIN_DEPOSIT + * ADMIN_WITHDRAW + * MARGIN_TRANSFER + * MARGIN_TYPE_CHANGE + * ASSET_TRANSFER + * OPTIONS_PREMIUM_FEE + * OPTIONS_SETTLE_PROFIT + * AUTO_EXCHANGE +* The field "bc" represents the balance change except for PnL and commission. + +## Event: Order Update + +> **Payload:** + +```javascript +{ + + "e":"ORDER_TRADE_UPDATE", // Event Type + "E":1568879465651, // Event Time + "T":1568879465650, // Transaction Time + "o":{ + "s":"BTCUSDT", // Symbol + "c":"TEST", // Client Order Id + // special client order id: + // starts with "autoclose-": liquidation order + // "adl_autoclose": ADL auto close order + "S":"SELL", // Side + "o":"TRAILING_STOP_MARKET", // Order Type + "f":"GTC", // Time in Force + "q":"0.001", // Original Quantity + "p":"0", // Original Price + "ap":"0", // Average Price + "sp":"7103.04", // Stop Price. Please ignore with TRAILING_STOP_MARKET order + "x":"NEW", // Execution Type + "X":"NEW", // Order Status + "i":8886774, // Order Id + "l":"0", // Order Last Filled Quantity + "z":"0", // Order Filled Accumulated Quantity + "L":"0", // Last Filled Price + "N":"USDT", // Commission Asset, will not push if no commission + "n":"0", // Commission, will not push if no commission + "T":1568879465651, // Order Trade Time + "t":0, // Trade Id + "b":"0", // Bids Notional + "a":"9.91", // Ask Notional + "m":false, // Is this trade the maker side? + "R":false, // Is this reduce only + "wt":"CONTRACT_PRICE", // Stop Price Working Type + "ot":"TRAILING_STOP_MARKET", // Original Order Type + "ps":"LONG", // Position Side + "cp":false, // If Close-All, pushed with conditional order + "AP":"7476.89", // Activation Price, only puhed with TRAILING_STOP_MARKET order + "cr":"5.0", // Callback Rate, only puhed with TRAILING_STOP_MARKET order + "rp":"0" // Realized Profit of the trade + } + +} +``` + +When new order created, order status changed will push such event. +event type is `ORDER_TRADE_UPDATE`. + +**Side** + +* BUY +* SELL + +**Order Type** + +* MARKET +* LIMIT +* STOP +* TAKE_PROFIT +* LIQUIDATION + +**Execution Type** + +* NEW +* CANCELED +* CALCULATED - Liquidation Execution +* EXPIRED +* TRADE + +**Order Status** + +* NEW +* PARTIALLY_FILLED +* FILLED +* CANCELED +* EXPIRED +* NEW_INSURANCE - Liquidation with Insurance Fund +* NEW_ADL - Counterparty Liquidation` + +**Time in force** + +* GTC +* IOC +* FOK +* GTX + +**Working Type** + +* MARK_PRICE +* CONTRACT_PRICE + +## Event: Account Configuration Update previous Leverage Update + +> **Payload:** + +```javascript +{ + "e":"ACCOUNT_CONFIG_UPDATE", // Event Type + "E":1611646737479, // Event Time + "T":1611646737476, // Transaction Time + "ac":{ + "s":"BTCUSDT", // symbol + "l":25 // leverage + + } +} +``` + +> **Or** + +```javascript +{ + "e":"ACCOUNT_CONFIG_UPDATE", // Event Type + "E":1611646737479, // Event Time + "T":1611646737476, // Transaction Time + "ai":{ // User's Account Configuration + "j":true, // Multi-Assets Mode + "f":true, // Specified token fee deduction + "d":true // Position mode: true for dual-side (hedge) mode, false for single-side (one-way) mode + } +} +``` + +When the account configuration is changed, the event type will be pushed as `ACCOUNT_CONFIG_UPDATE` + +When the leverage of a trade pair changes, the payload will contain the object `ac` to represent the account configuration of the trade pair, where `s` represents the specific trade pair and `l` represents the leverage + +When the user Multi-Assets margin mode changes the payload will contain the object `ai` representing the user account configuration, where `j` represents the user Multi-Assets margin mode + +# Error Codes + +> Here is the error JSON payload: + +```javascript +{ + "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 + +* An unknown error occured while processing the request. + +> -1001 DISCONNECTED + +* Internal error; unable to process your request. Please try again. + +> -1002 UNAUTHORIZED + +* You are not authorized to execute this request. + +> -1003 TOO_MANY_REQUESTS + +* Too many requests queued. +* Too many requests; please use the websocket for live updates. +* Too many requests; current limit is %s requests per minute. Please use the websocket for live updates to avoid polling the API. +* Way too many requests; IP banned until %s. Please use the websocket for live updates to avoid bans. + +> -1004 DUPLICATE_IP + +* This IP is already on the white list + +> -1005 NO_SUCH_IP + +* No such IP has been white listed + +> -1006 UNEXPECTED_RESP + +* An unexpected response was received from the message bus. Execution status unknown. + +> -1007 TIMEOUT + +* Timeout waiting for response from backend server. Send status unknown; execution status unknown. + +> -1010 ERROR_MSG_RECEIVED + +* ERROR_MSG_RECEIVED. + +> -1011 NON_WHITE_LIST + +* This IP cannot access this route. + +> -1013 INVALID_MESSAGE + +* INVALID_MESSAGE. + +> -1014 UNKNOWN_ORDER_COMPOSITION + +* Unsupported order combination. + +> -1015 TOO_MANY_ORDERS + +* Too many new orders. +* Too many new orders; current limit is %s orders per %s. + +> -1016 SERVICE_SHUTTING_DOWN + +* This service is no longer available. + +> -1020 UNSUPPORTED_OPERATION + +* This operation is not supported. + +> -1021 INVALID_TIMESTAMP + +* Timestamp for this request is outside of the recvWindow. +* Timestamp for this request was 1000ms ahead of the server's time. + +> -1022 INVALID_SIGNATURE + +* Signature for this request is not valid. + +> -1023 START_TIME_GREATER_THAN_END_TIME + +* Start time is greater than end time. + +## 11xx - Request issues + +> -1100 ILLEGAL_CHARS + +* Illegal characters found in a parameter. +* Illegal characters found in parameter '%s'; legal range is '%s'. + +> -1101 TOO_MANY_PARAMETERS + +* Too many parameters sent for this endpoint. +* Too many parameters; expected '%s' and received '%s'. +* Duplicate values for a parameter detected. + +> -1102 MANDATORY_PARAM_EMPTY_OR_MALFORMED + +* A mandatory parameter was not sent, was empty/null, or malformed. +* Mandatory parameter '%s' was not sent, was empty/null, or malformed. +* Param '%s' or '%s' must be sent, but both were empty/null! + +> -1103 UNKNOWN_PARAM + +* An unknown parameter was sent. + +> -1104 UNREAD_PARAMETERS + +* Not all sent parameters were read. +* Not all sent parameters were read; read '%s' parameter(s) but was sent '%s'. + +> -1105 PARAM_EMPTY + +* A parameter was empty. +* Parameter '%s' was empty. + +> -1106 PARAM_NOT_REQUIRED + +* A parameter was sent when not required. +* Parameter '%s' sent when not required. + +> -1108 BAD_ASSET + +* Invalid asset. + +> -1109 BAD_ACCOUNT + +* Invalid account. + +> -1110 BAD_INSTRUMENT_TYPE + +* Invalid symbolType. + +> -1111 BAD_PRECISION + +* Precision is over the maximum defined for this asset. + +> -1112 NO_DEPTH + +* No orders on book for symbol. + +> -1113 WITHDRAW_NOT_NEGATIVE + +* Withdrawal amount must be negative. + +> -1114 TIF_NOT_REQUIRED + +* TimeInForce parameter sent when not required. + +> -1115 INVALID_TIF + +* Invalid timeInForce. + +> -1116 INVALID_ORDER_TYPE + +* Invalid orderType. + +> -1117 INVALID_SIDE + +* Invalid side. + +> -1118 EMPTY_NEW_CL_ORD_ID + +* New client order ID was empty. + +> -1119 EMPTY_ORG_CL_ORD_ID + +* Original client order ID was empty. + +> -1120 BAD_INTERVAL + +* Invalid interval. + +> -1121 BAD_SYMBOL + +* Invalid symbol. + +> -1125 INVALID_LISTEN_KEY + +* This listenKey does not exist. + +> -1127 MORE_THAN_XX_HOURS + +* Lookup interval is too big. +* More than %s hours between startTime and endTime. + +> -1128 OPTIONAL_PARAMS_BAD_COMBO + +* Combination of optional parameters invalid. + +> -1130 INVALID_PARAMETER + +* Invalid data sent for a parameter. +* Data sent for parameter '%s' is not valid. + +> -1136 INVALID_NEW_ORDER_RESP_TYPE + +* Invalid newOrderRespType. + +## 20xx - Processing Issues + +> -2010 NEW_ORDER_REJECTED + +* NEW_ORDER_REJECTED + +> -2011 CANCEL_REJECTED + +* CANCEL_REJECTED + +> -2013 NO_SUCH_ORDER + +* Order does not exist. + +> -2014 BAD_API_KEY_FMT + +* API-key format invalid. + +> -2015 REJECTED_MBX_KEY + +* Invalid API-key, IP, or permissions for action. + +> -2016 NO_TRADING_WINDOW + +* No trading window could be found for the symbol. Try ticker/24hrs instead. + +> -2018 BALANCE_NOT_SUFFICIENT + +* Balance is insufficient. + +> -2019 MARGIN_NOT_SUFFICIEN + +* Margin is insufficient. + +> -2020 UNABLE_TO_FILL + +* Unable to fill. + +> -2021 ORDER_WOULD_IMMEDIATELY_TRIGGER + +* Order would immediately trigger. + +> -2022 REDUCE_ONLY_REJECT + +* ReduceOnly Order is rejected. + +> -2023 USER_IN_LIQUIDATION + +* User in liquidation mode now. + +> -2024 POSITION_NOT_SUFFICIENT + +* Position is not sufficient. + +> -2025 MAX_OPEN_ORDER_EXCEEDED + +* Reach max open order limit. + +> -2026 REDUCE_ONLY_ORDER_TYPE_NOT_SUPPORTED + +* This OrderType is not supported when reduceOnly. + +> -2027 MAX_LEVERAGE_RATIO + +* Exceeded the maximum allowable position at current leverage. + +> -2028 MIN_LEVERAGE_RATIO + +* Leverage is smaller than permitted: insufficient margin balance. + +## 40xx - Filters and other Issues + +> -4000 INVALID_ORDER_STATUS + +* Invalid order status. + +> -4001 PRICE_LESS_THAN_ZERO + +* Price less than 0. + +> -4002 PRICE_GREATER_THAN_MAX_PRICE + +* Price greater than max price. + +> -4003 QTY_LESS_THAN_ZERO + +* Quantity less than zero. + +> -4004 QTY_LESS_THAN_MIN_QTY + +* Quantity less than min quantity. + +> -4005 QTY_GREATER_THAN_MAX_QTY + +* Quantity greater than max quantity. + +> -4006 STOP_PRICE_LESS_THAN_ZERO + +* Stop price less than zero. + +> -4007 STOP_PRICE_GREATER_THAN_MAX_PRICE + +* Stop price greater than max price. + +> -4008 TICK_SIZE_LESS_THAN_ZERO + +* Tick size less than zero. + +> -4009 MAX_PRICE_LESS_THAN_MIN_PRICE + +* Max price less than min price. + +> -4010 MAX_QTY_LESS_THAN_MIN_QTY + +* Max qty less than min qty. + +> -4011 STEP_SIZE_LESS_THAN_ZERO + +* Step size less than zero. + +> -4012 MAX_NUM_ORDERS_LESS_THAN_ZERO + +* Max mum orders less than zero. + +> -4013 PRICE_LESS_THAN_MIN_PRICE + +* Price less than min price. + +> -4014 PRICE_NOT_INCREASED_BY_TICK_SIZE + +* Price not increased by tick size. + +> -4015 INVALID_CL_ORD_ID_LEN + +* Client order id is not valid. +* Client order id length should not be more than 36 chars + +> -4016 PRICE_HIGHTER_THAN_MULTIPLIER_UP + +* Price is higher than mark price multiplier cap. + +> -4017 MULTIPLIER_UP_LESS_THAN_ZERO + +* Multiplier up less than zero. + +> -4018 MULTIPLIER_DOWN_LESS_THAN_ZERO + +* Multiplier down less than zero. + +> -4019 COMPOSITE_SCALE_OVERFLOW + +* Composite scale too large. + +> -4020 TARGET_STRATEGY_INVALID + +* Target strategy invalid for orderType '%s',reduceOnly '%b'. + +> -4021 INVALID_DEPTH_LIMIT + +* Invalid depth limit. +* '%s' is not valid depth limit. + +> -4022 WRONG_MARKET_STATUS + +* market status sent is not valid. + +> -4023 QTY_NOT_INCREASED_BY_STEP_SIZE + +* Qty not increased by step size. + +> -4024 PRICE_LOWER_THAN_MULTIPLIER_DOWN + +* Price is lower than mark price multiplier floor. + +> -4025 MULTIPLIER_DECIMAL_LESS_THAN_ZERO + +* Multiplier decimal less than zero. + +> -4026 COMMISSION_INVALID + +* Commission invalid. +* `%s` less than zero. +* `%s` absolute value greater than `%s` + +> -4027 INVALID_ACCOUNT_TYPE + +* Invalid account type. + +> -4028 INVALID_LEVERAGE + +* Invalid leverage +* Leverage `%s` is not valid +* Leverage `%s` already exist with `%s` + +> -4029 INVALID_TICK_SIZE_PRECISION + +* Tick size precision is invalid. + +> -4030 INVALID_STEP_SIZE_PRECISION + +* Step size precision is invalid. + +> -4031 INVALID_WORKING_TYPE + +* Invalid parameter working type +* Invalid parameter working type: `%s` + +> -4032 EXCEED_MAX_CANCEL_ORDER_SIZE + +* Exceed maximum cancel order size. +* Invalid parameter working type: `%s` + +> -4033 INSURANCE_ACCOUNT_NOT_FOUND + +* Insurance account not found. + +> -4044 INVALID_BALANCE_TYPE + +* Balance Type is invalid. + +> -4045 MAX_STOP_ORDER_EXCEEDED + +* Reach max stop order limit. + +> -4046 NO_NEED_TO_CHANGE_MARGIN_TYPE + +* No need to change margin type. + +> -4047 THERE_EXISTS_OPEN_ORDERS + +* Margin type cannot be changed if there exists open orders. + +> -4048 THERE_EXISTS_QUANTITY + +* Margin type cannot be changed if there exists position. + +> -4049 ADD_ISOLATED_MARGIN_REJECT + +* Add margin only support for isolated position. + +> -4050 CROSS_BALANCE_INSUFFICIENT + +* Cross balance insufficient. + +> -4051 ISOLATED_BALANCE_INSUFFICIENT + +* Isolated balance insufficient. + +> -4052 NO_NEED_TO_CHANGE_AUTO_ADD_MARGIN + +* No need to change auto add margin. + +> -4053 AUTO_ADD_CROSSED_MARGIN_REJECT + +* Auto add margin only support for isolated position. + +> -4054 ADD_ISOLATED_MARGIN_NO_POSITION_REJECT + +* Cannot add position margin: position is 0. + +> -4055 AMOUNT_MUST_BE_POSITIVE + +* Amount must be positive. + +> -4056 INVALID_API_KEY_TYPE + +* Invalid api key type. + +> -4057 INVALID_RSA_PUBLIC_KEY + +* Invalid api public key + +> -4058 MAX_PRICE_TOO_LARGE + +* maxPrice and priceDecimal too large,please check. + +> -4059 NO_NEED_TO_CHANGE_POSITION_SIDE + +* No need to change position side. + +> -4060 INVALID_POSITION_SIDE + +* Invalid position side. + +> -4061 POSITION_SIDE_NOT_MATCH + +* Order's position side does not match user's setting. + +> -4062 REDUCE_ONLY_CONFLICT + +* Invalid or improper reduceOnly value. + +> -4063 INVALID_OPTIONS_REQUEST_TYPE + +* Invalid options request type + +> -4064 INVALID_OPTIONS_TIME_FRAME + +* Invalid options time frame + +> -4065 INVALID_OPTIONS_AMOUNT + +* Invalid options amount + +> -4066 INVALID_OPTIONS_EVENT_TYPE + +* Invalid options event type + +> -4067 POSITION_SIDE_CHANGE_EXISTS_OPEN_ORDERS + +* Position side cannot be changed if there exists open orders. + +> -4068 POSITION_SIDE_CHANGE_EXISTS_QUANTITY + +* Position side cannot be changed if there exists position. + +> -4069 INVALID_OPTIONS_PREMIUM_FEE + +* Invalid options premium fee + +> -4070 INVALID_CL_OPTIONS_ID_LEN + +* Client options id is not valid. +* Client options id length should be less than 32 chars + +> -4071 INVALID_OPTIONS_DIRECTION + +* Invalid options direction + +> -4072 OPTIONS_PREMIUM_NOT_UPDATE + +* premium fee is not updated, reject order + +> -4073 OPTIONS_PREMIUM_INPUT_LESS_THAN_ZERO + +* input premium fee is less than 0, reject order + +> -4074 OPTIONS_AMOUNT_BIGGER_THAN_UPPER + +* Order amount is bigger than upper boundary or less than 0, reject order + +> -4075 OPTIONS_PREMIUM_OUTPUT_ZERO + +* output premium fee is less than 0, reject order + +> -4076 OPTIONS_PREMIUM_TOO_DIFF + +* original fee is too much higher than last fee + +> -4077 OPTIONS_PREMIUM_REACH_LIMIT + +* place order amount has reached to limit, reject order + +> -4078 OPTIONS_COMMON_ERROR + +* options internal error + +> -4079 INVALID_OPTIONS_ID + +* invalid options id +* invalid options id: %s +* duplicate options id %d for user %d + +> -4080 OPTIONS_USER_NOT_FOUND + +* user not found +* user not found with id: %s + +> -4081 OPTIONS_NOT_FOUND + +* options not found +* options not found with id: %s + +> -4082 INVALID_BATCH_PLACE_ORDER_SIZE + +* Invalid number of batch place orders. +* Invalid number of batch place orders: %s + +> -4083 PLACE_BATCH_ORDERS_FAIL + +* Fail to place batch orders. + +> -4084 UPCOMING_METHOD + +* Method is not allowed currently. Upcoming soon. + +> -4085 INVALID_NOTIONAL_LIMIT_COEF + +* Invalid notional limit coefficient + +> -4086 INVALID_PRICE_SPREAD_THRESHOLD + +* Invalid price spread threshold + +> -4087 REDUCE_ONLY_ORDER_PERMISSION + +* User can only place reduce only order + +> -4088 NO_PLACE_ORDER_PERMISSION + +* User can not place order currently + +> -4104 INVALID_CONTRACT_TYPE + +* Invalid contract type + +> -4114 INVALID_CLIENT_TRAN_ID_LEN + +* clientTranId is not valid +* Client tran id length should be less than 64 chars + +> -4115 DUPLICATED_CLIENT_TRAN_ID + +* clientTranId is duplicated +* Client tran id should be unique within 7 days + +> -4118 REDUCE_ONLY_MARGIN_CHECK_FAILED + +* ReduceOnly Order Failed. Please check your existing position and open orders + +> -4131 MARKET_ORDER_REJECT + +* The counterparty's best price does not meet the PERCENT_PRICE filter limit + +> -4135 INVALID_ACTIVATION_PRICE + +* Invalid activation price + +> -4137 QUANTITY_EXISTS_WITH_CLOSE_POSITION + +* Quantity must be zero with closePosition equals true + +> -4138 REDUCE_ONLY_MUST_BE_TRUE + +* Reduce only must be true with closePosition equals true + +> -4139 ORDER_TYPE_CANNOT_BE_MKT + +* Order type can not be market if it's unable to cancel + +> -4140 INVALID_OPENING_POSITION_STATUS + +* Invalid symbol status for opening position + +> -4141 SYMBOL_ALREADY_CLOSED + +* Symbol is closed + +> -4142 STRATEGY_INVALID_TRIGGER_PRICE + +* REJECT: take profit or stop order will be triggered immediately + +> -4144 INVALID_PAIR + +* Invalid pair + +> -4161 ISOLATED_LEVERAGE_REJECT_WITH_POSITION + +* Leverage reduction is not supported in Isolated Margin Mode with open positions + +> -4164 MIN_NOTIONAL + +* Order's notional must be no smaller than 5.0 (unless you choose reduce only) +* Order's notional must be no smaller than %s (unless you choose reduce only) + +> -4165 INVALID_TIME_INTERVAL + +* Invalid time interval +* Maximum time interval is %s days + +> -4183 PRICE_HIGHTER_THAN_STOP_MULTIPLIER_UP + +* Price is higher than stop price multiplier cap. +* Limit price can't be higher than %s. + +> -4184 PRICE_LOWER_THAN_STOP_MULTIPLIER_DOWN + +* Price is lower than stop price multiplier floor. +* Limit price can't be lower than %s. + diff --git a/aster-finance-spot-api-testnet.md b/aster-finance-spot-api-testnet.md new file mode 100644 index 0000000..a10986b --- /dev/null +++ b/aster-finance-spot-api-testnet.md @@ -0,0 +1,2624 @@ +# Spot API Overview + +* This document lists the base URL for the API endpoints: [**https://sapi.asterdex-testnet.com**](https://sapi.asterdex-testnet.com) +* All API responses are in JSON format. + +### Attention +* TESTUSDT or any other symbols starting with TEST are symbols used for Aster’s INTERNAL TESTING ONLY. Please DO NOT trade on these symbols starting with TEST. Aster does not hold any accountability for loss of funds due to trading on these symbols. However, if you run into issues, you may contact support about this any time, we will try to help you recover your funds. + +### HTTP return codes + +* HTTP `4XX` status codes are used to indicate errors in the request content, behavior, or format. The problem lies with the requester. +* HTTP `403` status code indicates a violation of WAF restrictions (Web Application Firewall). +* HTTP `429` error code indicates a warning that the access frequency limit has been exceeded and the IP is about to be blocked. +* HTTP `418` indicates that after receiving a 429 you continued to access, so the IP has been blocked. +* HTTP `5XX` error codes are used to indicate issues on the Aster service side. + +### API error codes + +* When using the endpoint `/api/v3`, any endpoint may throw exceptions; + +The API error codes are returned in the following format: + +```javascript +{ + "code": -1121, + "msg": "Invalid symbol." +} +``` + +### Basic information about the endpoint + +* Endpoints with the `GET` method must send parameters in the `query string`. +* For `POST`, `PUT`, and `DELETE` endpoints, parameters can be sent in the `query string` with content type `application/x-www-form-urlencoded` , or in the `request body`. +* The order of parameters is not required. + +--- + +## Access restrictions + +### Basic information on access restrictions + +* The `rateLimits` array in `/api/v3/exchangeInfo` contains objects related to REQUEST\_WEIGHT and ORDERS rate limits for trading. These are further defined in the `enum definitions` section under `rateLimitType`. +* A 429 will be returned when any of the rate limits are violated. + +### IP access limits + +* Each request will include a header named `X-MBX-USED-WEIGHT-(intervalNum)(intervalLetter)` that contains the used weight of all requests from the current IP. +* Each endpoint has a corresponding weight, and some endpoints may have different weights depending on their parameters. The more resources an endpoint consumes, the higher its weight will be. +* Upon receiving a 429, you are responsible for stopping requests and must not abuse the API. +* **If you continue to violate access limits after receiving a 429, your IP will be banned and you will receive a 418 error code.** +* Repeated violations of the limits will result in progressively longer bans, **from a minimum of 2 minutes up to a maximum of 3 days**. +* The `Retry-After` header will be sent with responses bearing 418 or 429, and will give the wait time **in seconds** (if 429\) to avoid the ban, or, if 418, until the ban ends. +* **Access restrictions are based on IP, not API Key** + +You are advised to use WebSocket messages to obtain the corresponding data as much as possible to reduce the load and rate-limit pressure from requests. + +### Order rate limits + +* Each successful order response will include a `X-MBX-ORDER-COUNT-(intervalNum)(intervalLetter)` header containing the number of order limit units currently used by the account. +* When the number of orders exceeds the limit, you will receive a response with status 429 but without the `Retry-After` header. Please check the order rate limits in `GET api/v3/exchangeInfo` (rateLimitType \= ORDERS) and wait until the ban period ends. +* Rejected or unsuccessful orders are not guaranteed to include the above header in the response. +* **Order placement rate limits are counted per account.** + +### WebSocket connection limits + +* The WebSocket server accepts a maximum of 5 messages per second. Messages include: + * PING frame + * PONG frame + * Messages in JSON format, such as subscribe and unsubscribe. +* If a user sends messages that exceed the limit, the connection will be terminated. IPs that are repeatedly disconnected may be blocked by the server. +* A single connection can subscribe to up to **1024** Streams. + +--- + +## API authentication types + +* Each API has its own authentication type, which determines what kind of authentication is required when accessing it. +* If authentication is required, a signer should be included in the request body. + +| Security Type | Description | +| ------------- | ----------------------------------------- | +| NONE | API that does not require authentication | +| TRADE | A valid signer and signature are required | +| USER_DATA | A valid signer and signature are required | +| USER_STREAM | A valid signer and signature are required | +| MARKET_DATA | A valid signer and signature are required | + +--- + +## SIGNED (TRADE AND USER\_DATA) Endpoint security + + +## Authentication signature payload + +| Parameter | Description | +| --------- | ---------------------------------- | +| user | Main account wallet address | +| signer | API wallet address | +| nonce | Current timestamp, in microseconds | +| signature | Signature | + +## Endpoints requiring signature +* Security Type: TRADE, USER_DATA, USER_STREAM, MARKET_DATA +* After converting the API parameters to strings, sort them by their key values in ASCII order to generate the final string. Note: All parameter values must be treated as strings during the signing process. +* After generating the string, combine it with the authentication signature parameters user, signer, and nonce, then use Web3’s ABI parameter encoding to generate the bytecode. +* After generating the bytecode, use the Keccak algorithm to generate the hash. +* Use the private key of **API wallet address** to sign the hash using web3’s ECDSA signature algorithm, generating the final signature. + +## Example of POST /api/v3/order + +#### All parameters are passed through the request body (Python 3.9.6) + +#### The following parameters are API registration details. The values for user, signer, and privateKey are for demonstration purposes only (the privateKey corresponds to the signer). + +| Key | Value | Desc +| ---------- | ------------------------------------------------------------------ | ---------- | +| user | 0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e |Login wallet address | +| signer | 0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0 |[Click Here](https://www.asterdex-testnet.com/en/api-wallet) | +| privateKey | 0x4fd0a42218f3eae43a6ce26d22544e986139a01e5b34a62db53757ffca81bae1 |[Click Here](https://www.asterdex-testnet.com/en/api-wallet) | + +#### The nonce parameter is the current system time in microseconds. If it exceeds the system time or lags behind it by more than 5 seconds, the request is considered invalid. + +```python +#python +nonce = math.trunc(time.time()*1000000) +print(nonce) +#1748310859508867 +``` + +```java +//java +Instant now = Instant.now(); +long microsecond = now.getEpochSecond() * 1000000 + now.getNano() / 1000; +``` +#### Example: The following parameters are business request parameters. + +```python + +typed_data = { + "types": { + "EIP712Domain": [ + {"name": "name", "type": "string"}, + {"name": "version", "type": "string"}, + {"name": "chainId", "type": "uint256"}, + {"name": "verifyingContract", "type": "address"} + ], + "Message": [ + { "name": "msg", "type": "string" } + ] + }, + "primaryType": "Message", + "domain": { + "name": "AsterSignTransaction", + "version": "1", + "chainId": 714, + "verifyingContract": "0x0000000000000000000000000000000000000000" + }, + "message": { + "msg": "$msg" + } +} +``` + +#### Example: As a query string (using Python as an example). + +> **Step 1: As a query string** + +```python +import random +import time + +import requests +from eth_account.messages import encode_typed_data +from eth_account import Account + +from eip712 import typed_data + + +def get_url(my_dict) -> str: + return '&'.join(f'{key}={str(value)}'for key, value in my_dict.items()) + +def send_by_body() : + my_dict = {"symbol": "ASTERUSDT", "type": "LIMIT", "side": "BUY", + "timeInForce": "GTC", "quantity": "10", "price": "0.6"} + + test_net_end_point = 'https://sapi.asterdex-testnet.com/api/v3/order' + + nonce = int(time.time()) * 1_000_000 + random.randint(0, 999999) + my_dict['nonce'] = str(nonce) + my_dict['user'] = '0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e' + my_dict['signer'] = '0xF1A3E9330a348Df202D29E5a065089f6EbA01b26' + + content = get_url(my_dict) + + typed_data['message']['msg'] = content + + message = encode_typed_data(full_message=typed_data) + + private_key = "*" + signed = Account.sign_message(message, private_key=private_key) + print(signed.signature.hex()) + + my_dict['signature'] = signed.signature.hex() + + headers = { + 'Content-Type': 'application/x-www-form-urlencoded', + 'User-Agent': 'PythonApp/1.0' + } + print(my_dict) + res = requests.post(test_net_end_point, data=my_dict, headers=headers) + + print(res.text) + +if __name__ == '__main__': + send_by_body() + + +``` + +> **Step 1: As a body** + +```python +import random +import time + +import requests +from eth_account.messages import encode_typed_data +from eth_account import Account + +from eip712 import typed_data + + +def get_url(my_dict) -> str: + return '&'.join(f'{key}={str(value)}'for key, value in my_dict.items()) + +def send_by_url() : + import random + import time + + import requests + from eth_account.messages import encode_typed_data + from eth_account import Account + + test_net_end_point = 'https://sapi.asterdex-testnet.com/api/v3/order' + param = 'symbol=ASTERUSDT&side=BUY&type=LIMIT&quantity=10&price=0.6&timeInForce=GTC' + + nonce = int(time.time()) * 1_000_000 + random.randint(0, 999999) + param += '&nonce=' + str(nonce) + param += '&user=' + '0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e' + param += '&signer=' + '0xF1A3E9330a348Df202D29E5a065089f6EbA01b26' + + typed_data['message']['msg'] = param + + message = encode_typed_data(full_message=typed_data) + + private_key = "*" + signed = Account.sign_message(message, private_key=private_key) + print(signed.signature.hex()) + + url = test_net_end_point + '?' + param + '&signature=' + signed.signature.hex() + + headers = { + 'Content-Type': 'application/x-www-form-urlencoded', + 'User-Agent': 'PythonApp/1.0' + } + print(url) + res = requests.post(url, headers=headers) + + print(res.text) + +if __name__ == '__main__': + send_by_url() +``` + + +## Public Endpoints Info + +### Terminology + +* `base asset` refers to the asset that is the `quantity` of a symbol. +* `quote asset` refers + +## Public API parameters + +### Terminology + +The terminology in this section applies throughout the document. New users are encouraged to read it carefully for better understanding. + +* `base asset` refers to the asset being traded in a trading pair, i.e., the asset name written first; for example, in `BTCUSDT`, `BTC` is the `base asset`. +* `quote asset` refers to the pricing asset of a trading pair, i.e., the asset name written at the latter part; for example, in `BTCUSDT`, `USDT` is the `quote asset`. + +### Enumeration definition + +**Trading pair status (status):** + +* TRADING \- after trade + +**Trading pair type:** + +* SPOT \- spot + +**Order status (status):** + +| Status | Description | +| :---- | :---- | +| NEW | Order accepted by the matching engine | +| PARTIALLY\_FILLED | Part of the order was filled | +| FILLED | The order was fully filled | +| CANCELED | The user canceled the order | +| REJECTED | The order was not accepted by the matching engine and was not processed | +| EXPIRED | Order canceled by the trading engine, for example: Limit FOK order not filled, Market order not fully filled, orders canceled during exchange maintenance | + +**Order types (orderTypes, type):** + +* LIMIT \- Limit Order +* MARKET \- Market Order +* STOP \- Limit Stop Order +* TAKE\_PROFIT \- Limit Take-Profit Order +* STOP\_MARKET \- Market Stop Order +* TAKE\_PROFIT\_MARKET \- Market Take-Profit Order + +**Order response type (newOrderRespType):** + +* ACK +* RESULT +* FULL + +**Order direction (direction side):** + +* BUY \- Buy +* SELL \- Sell + +**Valid types (timeInForce):** + +This defines how long an order can remain valid before expiring. + +| Status | Description | +| :---- | :---- | +| GTC (Good ‘Til Canceled) | The order remains active until it is fully executed or manually canceled. | +| IOC (Immediate or Cancel) | The order will execute immediately for any amount available. Any unfilled portion is automatically canceled. | +| FOK (Fill or Kill) | The order must be fully executed immediately. If it cannot be filled in full, it is canceled right away. | +| GTX (Good till crossing, Post only) | The post-only limit order will only be placed if it can be added as a maker order and not as a taker order. | + +**K-line interval:** + +m (minutes), h (hours), d (days), w (weeks), M (months) + +* 1m +* 3m +* 5m +* 15m +* 30m +* 1h +* 2h +* 4h +* 6h +* 8h +* 12h +* 1d +* 3d +* 1w +* 1M + +**Rate limit type (rateLimitType)** + +REQUEST\_WEIGHT + +```json + { + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200 + } +``` + +ORDERS + +```json + { + "rateLimitType": "ORDERS", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 100 + } +``` + +* REQUEST\_WEIGHT \- The maximum sum of request weights allowed within a unit time + +* ORDERS \- Order placement frequency limit per time unit + +**Interval restriction (interval)** + +* MINUTE \- Minute + +--- + +## Filters + +Filters, i.e. Filter, define a set of trading rules. There are two types: filters for trading pairs `symbol filters`, and filters for the entire exchange `exchange filters` (not supported yet) + +### Trading pair filters + +#### PRICE\_FILTER Price filter + +**Format in the /exchangeInfo response:** + +```javascript + { + "minPrice": "556.72", + "maxPrice": "4529764", + "filterType": "PRICE_FILTER", + "tickSize": "0.01"   + } +``` + +The `Price Filter` checks the validity of the `price` parameter in an order. It consists of the following three parts: + +* `minPrice` defines the minimum allowed value for `price`/`stopPrice`. +* `maxPrice` defines the maximum allowed value for `price`/`stopPrice`. +* `tickSize` defines the step interval for `price`/`stopPrice`, meaning the price must equal minPrice plus an integer multiple of tickSize. + +Each of the above items can be 0; when 0 it means that item is not constrained. + +The logical pseudocode is as follows: + +* `price` \>= `minPrice` +* `price` \<= `maxPrice` +* (`price`\-`minPrice`) % `tickSize` \== 0 + +#### PERCENT\_PRICE price amplitude filter + +**Format in the /exchangeInfo response:** + +```javascript + { + "multiplierDown": "0.9500", + "multiplierUp": "1.0500", + "multiplierDecimal": "4", + "filterType": "PERCENT_PRICE" +  } +``` + +The `PERCENT_PRICE` filter defines the valid range of prices based on the index price. + +For the "price percentage" to apply, the "price" must meet the following conditions: + +* `price` \<=`indexPrice` \*`multiplierUp` +* `price`\> \=`indexPrice` \*`multiplierDown` + +#### LOT\_SIZE order size + +**Format in the /exchangeInfo response:** + +```javascript + { + "stepSize": "0.00100000", +   "filterType": "LOT_SIZE", + "maxQty": "100000.00000000", +   "minQty": "0.00100000" + } +``` + +Lots is an auction term. The `LOT_SIZE` filter validates the `quantity` (i.e., the amount) parameter in orders. It consists of three parts: + +* `minQty` indicates the minimum allowed value for `quantity`. +* `maxQty` denotes the maximum allowed value for `quantity`. +* `stepSize` denotes the allowed step increment for `quantity`. + +The logical pseudocode is as follows: + +* `quantity` \>= `minQty` +* `quantity` \<= `maxQty` +* (`quantity`\-`minQty`) % `stepSize` \== 0 + +#### MARKET\_LOT\_SIZE \- Market order size + +\***/exchangeInfo response format:** + +```javascript + { + "stepSize": "0.00100000", +   "filterType": "MARKET_LOT_SIZE" + "maxQty": "100000.00000000", + "minQty": "0.00100000" + } +``` + +The `MARKET_LOT_SIZE` filter defines the `quantity` (i.e., the "lots" in an auction) rules for `MARKET` orders on a trading pair. There are three parts: + +* `minQty` defines the minimum allowed `quantity`. +* `maxQty` defines the maximum allowed quantity. +* `stepSize` defines the increments by which the quantity can be increased or decreased. + +In order to comply with the `market lot size`, the `quantity` must satisfy the following conditions: + +* `quantity` \>= `minQty` +* `quantity` \<= `maxQty` +* (`quantity`\-`minQty`) % `stepSize` \== 0 + +# Market data API + +## Test server connectivity + +**Response** + +```javascript +{} +``` + +`GET /api/v3/ping` + +Test whether the REST API can be reached. + +**Weight:** 1 + +**Parameters:** NONE + +## Get server time + +**Response** + +```javascript +{ + "serverTime": 1499827319559 +} +``` + +`GET /api/v3/time` + +Test if the REST API can be reached and retrieve the server time. + +**Weight:** 1 + +**Parameters:** NONE + +## Trading specification information + +**Response** + +```javascript +{ + "timezone": "UTC", + "serverTime": 1756197279679, + "rateLimits": [{ + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 6000 + }, + { + "rateLimitType": "ORDERS", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 6000 + }, + { + "rateLimitType": "ORDERS", + "interval": "SECOND", + "intervalNum": 10, + "limit": 300 + } + ], + "exchangeFilters": [], + "assets": [{ + "asset": "USD" + }, { + "asset": "USDT" + }, + { + "asset": "BNB" + } + ], + "symbols": [{ + "status": "TRADING", + "baseAsset": "BNB", + "quoteAsset": "USDT", + "pricePrecision": 8, + "quantityPrecision": 8, + "baseAssetPrecision": 8, + "quotePrecision": 8, + "filters": [{ + "minPrice": "0.01000000", + "maxPrice": "100000", + "filterType": "PRICE_FILTER", + "tickSize": "0.01000000" + }, + { + "stepSize": "0.00100000", + "filterType": "LOT_SIZE", + "maxQty": "1000", + "minQty": "1" + }, + { + "stepSize": "0.00100000", + "filterType": "MARKET_LOT_SIZE", + "maxQty": "900000", + "minQty": "0.00100000" + }, + { + "limit": 200, + "filterType": "MAX_NUM_ORDERS" + }, + { + "minNotional": "5", + "filterType": "MIN_NOTIONAL" + }, + { + "maxNotional": "100", + "filterType": "MAX_NOTIONAL" + }, + { + "maxNotional": "100", + "minNotional": "5", + "avgPriceMins": 5, + "applyMinToMarket": true, + "filterType": "NOTIONAL", + "applyMaxToMarket": true + }, + { + "multiplierDown": "0", + "multiplierUp": "5", + "multiplierDecimal": "0", + "filterType": "PERCENT_PRICE" + }, + { + "bidMultiplierUp": "5", + "askMultiplierUp": "5", + "bidMultiplierDown": "0", + "avgPriceMins": 5, + "multiplierDecimal": "0", + "filterType": "PERCENT_PRICE_BY_SIDE", + "askMultiplierDown": "0" + } + ], + "orderTypes": [ + "LIMIT", + "MARKET", + "STOP", + "STOP_MARKET", + "TAKE_PROFIT", + "TAKE_PROFIT_MARKET" + ], + "timeInForce": [ + "GTC", + "IOC", + "FOK", + "GTX" + ], + "symbol": "BNBUSDT", + "ocoAllowed": false + }] +} +``` + +`GET /api/v3/exchangeInfo` + +Retrieve trading rules and trading pair information. + +**Weight:** 1 + +**Parameters:** None + +## Depth information + +**Response** + +```javascript +{ + "lastUpdateId": 1027024, + "E":1589436922972, // Message output time + "T":1589436922959, // Transaction time + "bids": [ + [ + "4.00000000", // PRICE + "431.00000000" // QTY + ] + ], + "asks": [ + [ + "4.00000200", + "12.00000000" + ] + ] +} +``` + +`GET /api/v3/depth` + +**Weight:** + +Based on limit adjustments: + +| Limitations | Weight | +| :---- | :---- | +| 5, 10, 20, 50 | 2 | +| 100 | 5 | +| 500 | 10 | +| 1000 | 20 | + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| limit | INT | NO | Default 100\. Optional values: \[5, 10, 20, 50, 100, 500, 1000\] | + +## Recent trades list + +**Response** + +```javascript +[ + { + "id": 657, + "price": "1.01000000", + "qty": "5.00000000", + "baseQty": "4.95049505", + "time": 1755156533943, + "isBuyerMaker": false + } +] +``` + +`GET /api/v3/trades` + +Get recent trades + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| limit | INT | NO | Default 500; maximum 1000 | + +## Query historical trades (MARKET\_DATA) + +**Response** + +```javascript +[ + { + "id": 1140, + "price": "1.10000000", + "qty": "7.27200000", + "baseQty": "6.61090909", + "time": 1756094288700, + "isBuyerMaker": false + } +] +``` + +`GET /api/v3/historicalTrades` + +Retrieve historical trades + +**Weight:** 20 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| limit | INT | NO | Default 500; maximum 1000\. | +| fromId | LONG | NO | Return starting from which trade id. Defaults to returning the most recent trade records. | + +## Recent trades (aggregated) + +**Response** + +```javascript +[ + { + "a": 26129, // Aggregate tradeId + "p": "0.01633102", // Price + "q": "4.70443515", // Quantity + "f": 27781, // First tradeId + "l": 27781, // Last tradeId + "T": 1498793709153, // Timestamp + "m": true, // Was the buyer the maker? + } +] +``` + +`GET /api/v3/aggTrades` + +The difference between aggregated trades and individual trades is that trades with the same price, same side, and same time are combined into a single entry. + +**Weight:** 20 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| fromId | LONG | NO | Return results starting from the trade ID that includes fromId | +| startTime | LONG | NO | Return results starting from trades after that time | +| endTime | LONG | NO | Return the trade records up to that moment | +| limit | INT | NO | Default 500; maximum 1000\. | + +* If you send startTime and endTime, the interval must be less than one hour. +* If no filter parameters (fromId, startTime, endTime) are sent, the most recent trade records are returned by default + +## K-line data + +**Response** + +```javascript +[ + [ + 1499040000000, // Open time + "0.01634790", // Open + "0.80000000", // High + "0.01575800", // Low + "0.01577100", // Close + "148976.11427815", // Volume + 1499644799999, // Close time + "2434.19055334", // Quote asset volume + 308, // Number of trades + "1756.87402397", // Taker buy base asset volume + "28.46694368", // Taker buy quote asset volume + ] +] +``` + +`GET /api/v3/klines` + +Each K-line represents a trading pair. The open time of each K-line can be regarded as a unique ID. + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| interval | ENUM | YES | See the enumeration definition: K-line interval | +| startTime | LONG | NO | | +| endTime | LONG | NO | | +| limit | INT | NO | Default 500; maximum 1500\. | + +* If startTime and endTime are not sent, the most recent trades are returned by default + +## 24h price change + +**Response** + +```javascript +{ + "symbol": "BTCUSDT", //symbol + "priceChange": "-94.99999800", //price change + "priceChangePercent": "-95.960", //price change percent + "weightedAvgPrice": "0.29628482", //weighted avgPrice + "prevClosePrice": "3.89000000", //prev close price + "lastPrice": "4.00000200", //last price + "lastQty": "200.00000000", //last qty + "bidPrice": "866.66000000", //first bid price + "bidQty": "72.05100000", //first bid qty + "askPrice": "866.73000000", //first ask price + "askQty": "1.21700000", //first ask qty + "openPrice": "99.00000000", //open price + "highPrice": "100.00000000", //high price + "lowPrice": "0.10000000", //low price + "volume": "8913.30000000", //volume + "quoteVolume": "15.30000000", //quote volume + "openTime": 1499783499040, //open time + "closeTime": 1499869899040, //close time + "firstId": 28385, // first id + "lastId": 28460, // last id + "count": 76, // count + "baseAsset": "BTC", //base asset + "quoteAsset": "USDT" //quote asset +} +``` + +`GET /api/v3/ticker/24hr` + +24-hour rolling window price change data. Please note that omitting the symbol parameter will return data for all trading pairs; in that case the returned data is an example array for the respective pairs, which is not only large in volume but also has a very high weight. + +**Weight:** 1 \= single trading pair; **40** \= When the trading pair parameter is missing (returns all trading pairs) + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | NO | | + +* Please note that omitting the symbol parameter will return data for all trading pairs + +## Latest price + +**Response** + +```javascript +{ + "symbol": "ADAUSDT", + "price": "1.30000000", + "time": 1649666690902 +} +``` + +OR + +```javascript +[ + { + "symbol": "ADAUSDT", + "price": "1.30000000", + "time": 1649666690902 + } +] +``` + +`GET /api/v3/ticker/price` + +Get the latest price for a trading pair + +**Weight:** 1 \= Single trading pair; **2** \= No symbol parameter (returns all pairs) + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | NO | | + +* If no trading pair parameter is sent, information for all trading pairs will be returned + +## Current best order + +**Response** + +```javascript +{ + "symbol": "LTCBTC", + "bidPrice": "4.00000000", + "bidQty": "431.00000000", + "askPrice": "4.00000200", + "askQty": "9.00000000" + "time": 1589437530011 // Timestamp +} +``` + +OR + +```javascript +[ + { + "symbol": "LTCBTC", + "bidPrice": "4.00000000", + "bidQty": "431.00000000", + "askPrice": "4.00000200", + "askQty": "9.00000000", + "time": 1589437530011 // Timestamp + } +] +``` + +`GET /api/v3/ticker/bookTicker` + +Return the current best orders (highest bid, lowest ask) + +**Weight:** 1 \= Single trading pair; **2** \= No symbol parameter (returns all pairs) + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | NO | | + +* If no trading pair parameter is sent, information for all trading pairs will be returned + +## Get symbol fees + +**Response** + +```javascript +{ + "symbol": "APXUSDT", + "makerCommissionRate": "0.000200",     + "takerCommissionRate": "0.000700" +} +``` + +`GET /api/v3/commissionRate` + +Get symbol fees + +**Weight:** 20 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| recvWindow | LONG | NO | The assigned value cannot be greater than 60000 | +| timestamp | LONG | YES | | + +# Spot account and trading API + +## Place order (TRADE) + +**Response ACK:** + +```javascript +{ + "symbol": "BTCUSDT", + "orderId": 28, + "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP", + "updateTime": 1507725176595, + "price": "0.00000000", + "avgPrice": "0.0000000000000000", + "origQty": "10.00000000", + "cumQty": "0", + "executedQty": "10.00000000", + "cumQuote": "10.00000000", + "status": "FILLED", + "timeInForce": "GTC", + "stopPrice": "0", + "origType": "LIMIT", + "type": "LIMIT", + "side": "SELL", +} +``` + +`POST /api/v3/order (HMAC SHA256)` + +Send order + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| side | ENUM | YES | See enum definition: Order direction | +| type | ENUM | YES | See enumeration definition: Order type | +| timeInForce | ENUM | NO | See enum definition: Time in force | +| quantity | DECIMAL | NO | | +| quoteOrderQty | DECIMAL | NO | | +| price | DECIMAL | NO | | +| newClientOrderId | STRING | NO | Client-customized unique order ID. If not provided, one will be generated automatically. | +| stopPrice | DECIMAL | NO | Only STOP, STOP\_MARKET, TAKE\_PROFIT, TAKE\_PROFIT\_MARKET require this parameter | +| recvWindow | LONG | NO | The value cannot be greater than 60000 | +| timestamp | LONG | YES | | + +Depending on the order `type`, certain parameters are mandatory: + +| Type | Mandatory parameters | +| :---- | :---- | +| LIMIT | timeInForce, quantity, price | +| MARKET | quantity or quoteOrderQty | +| STOP and TAKE\_PROFIT | quantity, price, stopPrice | +| STOP\_MARKET and TAKE\_PROFIT\_MARKET | quantity, stopPrice | + +Other information: + +* Place a `MARKET` `SELL` market order; the user controls the amount of base assets to sell with the market order via `QUANTITY`. + * For example, when placing a `MARKET` `SELL` market order on the `BTCUSDT` pair, use `QUANTITY` to let the user specify how much BTC they want to sell. +* For a `MARKET` `BUY` market order, the user controls how much of the quote asset they want to spend with `quoteOrderQty`; `QUANTITY` will be calculated by the system based on market liquidity. For example, when placing a `MARKET` `BUY` market order on the `BTCUSDT` pair, use `quoteOrderQty` to let the user choose how much USDT to use to buy BTC. +* A `MARKET` order using `quoteOrderQty` will not violate the `LOT_SIZE` limit rules; the order will be executed as closely as possible to the given `quoteOrderQty`. +* Unless a previous order has already been filled, orders set with the same `newClientOrderId` will be rejected. + +## Cancel order (TRADE) + +**Response** + +```javascript +{ + "symbol": "BTCUSDT", + "orderId": 28, + "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP", + "updateTime": 1507725176595, + "price": "0.00000000", + "avgPrice": "0.0000000000000000", + "origQty": "10.00000000", + "cumQty": "0", + "executedQty": "10.00000000", + "cumQuote": "10.00000000", + "status": "CANCELED", + "timeInForce": "GTC", + "stopPrice": "0", + "origType": "LIMIT", + "type": "LIMIT", + "side": "SELL", +} +``` + +`DELETE /api/v3/order (HMAC SHA256)` + +Cancel active orders + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| orderId | LONG | NO | | +| origClientOrderId | STRING | NO | | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +At least one of `orderId` or `origClientOrderId` must be sent. + +## Query order (USER\_DATA) + +**Response** + +```javascript +{ + "orderId": 38, + "symbol": "ADA25SLP25", + "status": "FILLED", + "clientOrderId": "afMd4GBQyHkHpGWdiy34Li", + "price": "20", + "avgPrice": "12.0000000000000000", + "origQty": "10", + "executedQty": "10", + "cumQuote": "120", + "timeInForce": "GTC", + "type": "LIMIT", + "side": "BUY", + "stopPrice": "0", + "origType": "LIMIT", + "time": 1649913186270, + "updateTime": 1649913186297 +} +``` + +`GET /api/v3/order (HMAC SHA256)` + +Query order status + +* Please note that orders meeting the following conditions will not be returned: + * The final status of the order is `CANCELED` or `EXPIRED`, **and** + * The order has no trade records, **and** + * Order creation time \+ 7 days \< current time + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| orderId | LONG | NO | | +| origClientOrderId | STRING | NO | | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +Note: + +* You must send at least one of `orderId` or `origClientOrderId`. + +## Current open orders (USER\_DATA) + +**Response** + +```javascript +[ + { + "orderId": 349661, + "symbol": "BNBUSDT", + "status": "NEW", + "clientOrderId": "LzypgiMwkf3TQ8wwvLo8RA", + "price": "1.10000000", + "avgPrice": "0.0000000000000000", + "origQty": "5",   + "executedQty": "0", + "cumQuote": "0", + "timeInForce": "GTC", + "type": "LIMIT", + "side": "BUY", + "stopPrice": "0", + "origType": "LIMIT", + "time": 1756252940207, + "updateTime": 1756252940207, + } +] +``` + +`GET /api/v3/openOrders (HMAC SHA256)` + +Retrieve all current open orders for trading pairs. Use calls without a trading pair parameter with caution. + +**Weight:** + +* With symbol ***1*** +* Without ***40***   + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | NO | | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +* If the symbol parameter is not provided, it will return the order books for all trading pairs. + +## Cancel All Open Orders (TRADE) + +> **Response** + +```javascript +{ + "code": 200, + "msg": "The operation of cancel all open order is done." +} +``` + +`` +DEL /api/v3/allOpenOrders (HMAC SHA256) +`` + +**Weight:** +- ***1*** + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +orderIdList | STRING | NO | orderid array string +origClientOrderIdList | STRING | NO | clientOrderId array string +recvWindow | LONG | NO | +timestamp | LONG | YES | + + +## Query all orders (USER\_DATA) + +**Response** + +```javascript +[ + { + "orderId": 349661, + "symbol": "BNBUSDT", + "status": "NEW", + "clientOrderId": "LzypgiMwkf3TQ8wwvLo8RA", + "price": "1.10000000", + "avgPrice": "0.0000000000000000", + "origQty": "5",   + "executedQty": "0", + "cumQuote": "0", + "timeInForce": "GTC", + "type": "LIMIT", + "side": "BUY", + "stopPrice": "0", + "origType": "LIMIT", + "time": 1756252940207, + "updateTime": 1756252940207, + } +] +``` + +`GET /api/v3/allOrders (HMAC SHA256)` + +Retrieve all account orders; active, canceled, or completed. + +* Please note that orders meeting the following conditions will not be returned: + * Order creation time \+ 7 days \< current time + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| orderId | LONG | NO | | +| startTime | LONG | NO | | +| endTime | LONG | NO | | +| limit | INT | NO | Default 500; maximum 1000 | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +* The maximum query time range must not exceed 7 days. +* By default, query data is from the last 7 days. + + +## Perp-spot transfer (TRADE) + +**Response:** + +```javascript +{ + "tranId": 21841, //Tran Id + "status": "SUCCESS" //Status +} +``` + +`POST /api/v3/asset/wallet/transfer (HMAC SHA256)` + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| amount | DECIMAL | YES | Quantity | +| asset | STRING | YES | Asset | +| clientTranId | STRING | YES | Transaction ID | +| kindType | STRING | YES | Transaction type | +| timestamp | LONG | YES | Timestamp | + +* kindType FUTURE_SPOT(future to spot)/SPOT_FUTURE(spot to future) + +## Get withdraw fee (NONE) +> **Response:** +```javascript +{ + "tokenPrice": 1.00019000, + "gasCost": 0.5000, + "gasUsdValue": 0.5 +} +``` + +`` +GET /api/v3/aster/withdraw/estimateFee +`` + +**Weight:** +1 + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +chainId | STRING | YES | +asset | STRING | YES | + +**Notes:** +* chainId: 1(ETH),56(BSC),42161(Arbi) +* gasCost: The minimum fee required for a withdrawal + +## Withdraw (USER_DATA) +> **Response:** +```javascript +{ + "withdrawId": "1014729574755487744", + "hash":"0xa6d1e617a3f69211df276fdd8097ac8f12b6ad9c7a49ba75bbb24f002df0ebb" +} +``` + +`` +POST /api/v3/aster/user-withdraw (HMAC SHA256) +`` + +**Weight:** +1 + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +chainId | STRING | YES | 1(ETH),56(BSC),42161(Arbi) +asset | STRING | YES | +amount | STRING | YES | +fee | STRING | YES | +receiver | STRING | YES | The address of the current account +nonce | STRING | YES | The current time in microseconds +userSignature | STRING | YES | +recvWindow | LONG | NO | +timestamp | LONG | YES | + + +**Note:** +* chainId: 1(ETH),56(BSC),42161(Arbi) +* receiver: The address of the current account +* If the futures account balance is insufficient, funds will be transferred from the spot account to the perp account for withdrawal. +* userSignature demo + +```shell +const domain = { + name: 'Aster', + version: '1', + chainId: 56, + verifyingContract: ethers.ZeroAddress, + } + +const currentTime = Date.now() * 1000 + +const types = { + Action: [ + {name: "type", type: "string"}, + {name: "destination", type: "address"}, + {name: "destination Chain", type: "string"}, + {name: "token", type: "string"}, + {name: "amount", type: "string"}, + {name: "fee", type: "string"}, + {name: "nonce", type: "uint256"}, + {name: "aster chain", type: "string"}, + ], + } + const value = { + 'type': 'Withdraw', + 'destination': '0xD9cA6952F1b1349d27f91E4fa6FB8ef67b89F02d', + 'destination Chain': 'BSC', + 'token': 'USDT', + 'amount': '10.123400', + 'fee': '1.234567891', + 'nonce': currentTime, + 'aster chain': 'Mainnet', + } + + +const signature = await signer.signTypedData(domain, types, value) +``` + +## Get User Create Apikey nonce (NONE) + +> **Response:** +```javascript + +111111 + +``` + +`` +POST /api/v3/getNonce +`` + +**Weight:** +1 + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +address | STRING | YES | +userOperationType | STRING | YES | CREATE_API_KEY +network | STRING | NO | + +**Notes:** +* userOperationType: CREATE_API_KEY +* network: For the Solana network, SOL must be provided; otherwise, this field can be ignored. + +## Create Apikey (NONE) + +> **Response:** +```javascript +{ + "apiKey": "bb3b24d0a3dec88cb06be58a257e4575cb0b1bb256ad6fd90ae8fd0ee1d102ae", + "apiSecret": "9fe8f5642ae1961674ea0cb7f957fa99dc8e0421b607c985a963ad2ced90ae1c" +} +``` + +`` +POST /api/v3/createApiKey +`` + +**Weight:** +1 + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +address | STRING | YES | +userOperationType | STRING | YES | CREATE_API_KEY +network | STRING | NO | +userSignature | STRING | YES | +apikeyIP | STRING | NO | +desc | STRING | YES | +recvWindow | LONG | NO | +timestamp | LONG | YES | + +**Note:** +* userOperationType: CREATE_API_KEY +* network: For the Solana network, SOL must be provided; otherwise, this field can be ignored. +* desc: The same account cannot be duplicated, and the length must not exceed 20 characters. +* apikeyIP: An array of IP addresses, separated by commas. +* Rate limit: 60 requests per minute per IP. +* userSignature: EVM demo + +```shell +const nonce = 111111 +const message = 'You are signing into Astherus ${nonce}'; +const signature = await signer.signMessage(message); +``` + +## Account information (USER\_DATA) + +**Response** + +```javascript +{ + "feeTier": 0, + "canTrade": true, + "canDeposit": true, + "canWithdraw": true, + "canBurnAsset": true, + "updateTime": 0, +   "balances": [ + { + "asset": "BTC", + "free": "4723846.89208129", + "locked": "0.00000000" + }, + { + "asset": "LTC", + "free": "4763368.68006011", + "locked": "0.00000000" + } + ] +} +``` + +`GET /api/v3/account (HMAC SHA256)` + +Retrieve current account information + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +## Account trade history (USER\_DATA) + +**Response** + +```javascript +[ + { + "symbol": "BNBUSDT", + "id": 1002, + "orderId": 266358, + "side": "BUY", + "price": "1", + "qty": "2", + "quoteQty": "2", + "commission": "0.00105000", + "commissionAsset": "BNB", + "time": 1755656788798, + "counterpartyId": 19, + "createUpdateId": null, + "maker": false, + "buyer": true + } +] +``` + +`GET /api/v3/userTrades (HMAC SHA256)` + +Retrieve the trade history for a specified trading pair of an account + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | NO | | +| orderId | LONG | NO | Must be used together with the parameter symbol | +| startTime | LONG | NO | | +| endTime | LONG | NO | | +| fromId | LONG | NO | Starting trade ID. Defaults to fetching the most recent trade. | +| limit | INT | NO | Default 500; maximum 1000 | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +* If both `startTime` and `endTime` are not sent, only data from the last 7 days will be returned. +* The maximum interval between startTime and endTime is 7 days. +* `fromId` cannot be sent together with `startTime` or `endTime`.       + +--- + +# WebSocket market data feed + +* The base URL for all wss endpoints listed in this document is: **wss://sstream.asterdex-testnet.com** +* Streams have either a single raw stream or a combined stream +* Single raw streams format is \*\*/ws/\*\* +* The URL format for combined streams is \*\*/stream?streams=//\*\* +* When subscribing to combined streams, the event payload is wrapped in this format: \*\*{"stream":"","data":}\*\* +* All trading pairs in stream names are **lowercase** +* Each link to **sstream.asterdex-testnet.com** is valid for no more than 24 hours; please handle reconnections appropriately +* Every 3 minutes the server sends a ping frame; the client must reply with a pong frame within 10 minutes, otherwise the server will close the connection. The client is allowed to send unpaired pong frames (i.e., the client may send pong frames at a frequency higher than once every 10 minutes to keep the connection alive). + +## Real-time subscribe/unsubscribe data streams + +* The following messages can be sent via WebSocket to subscribe or unsubscribe to data streams. Examples are shown below. +* The `id` in the response content is an unsigned integer that serves as the unique identifier for exchanges of information. +* If the `result` in the response content is `null`, it indicates the request was sent successfully. + +### Subscribe to a stream + +**Response** + +```javascript +{ + "result": null, + "id": 1 +} +``` + +* **Request** { "method": "SUBSCRIBE", "params": \[ "btcusdt@aggTrade", "btcusdt@depth" \], "id": 1 } + +### Unsubscribe from a stream + +**Response** + +```javascript +{ + "result": null, + "id": 312 +} +``` + +* **Request** { "method": "UNSUBSCRIBE", "params": \[ "btcusdt@depth" \], "id": 312 } + +### Subscribed to the feed + +**Response** + +```javascript +{ + "result": [ + "btcusdt@aggTrade" + ], + "id": 3 +} +``` + +* **Request** + + { "method": "LIST\_SUBSCRIPTIONS", "id": 3 } + +### Set properties + +Currently, the only configurable property is whether to enable the `combined` ("combined") stream. When connecting using `/ws/` ("raw stream"), the combined property is set to `false`, while connecting using `/stream/` sets the property to `true`. + +**Response** + +```javascript +{ +"result": null, +"id": 5 +} +``` + +* **Request** { "method": "SET\_PROPERTY" "params": \[ "combined", true \], "id": 5 } + +### Retrieve properties + +**Response** + +```javascript +{ + "result": true, // Indicates that combined is set to true. + "id": 2 +} +``` + +* **Request** + + { "method": "GET\_PROPERTY", "params": \[ "combined" \], "id": 2 } + +\#\#\# Error message + +| Error message | Description | +| :---- | :---- | +| {"code": 0, "msg": "Unknown property"} | Parameters applied in SET\_PROPERTY or GET\_PROPERTY are invalid | +| {"code": 1, "msg": "Invalid value type: expected Boolean", "id": '%s'} | Only true or false are accepted | +| {"code": 2, "msg": "Invalid request: property name must be a string"} | The provided attribute name is invalid | +| {"code": 2, "msg": "Invalid request: request ID must be an unsigned integer"} | Parameter ID not provided or ID has an invalid type | +| {"code": 2, "msg": "Invalid request: unknown variant %s, expected one of SUBSCRIBE, UNSUBSCRIBE, LIST\_SUBSCRIPTIONS, SET\_PROPERTY, GET\_PROPERTY at line 1 column 28"} | Typo warning, or the provided value is not of the expected type | +| {"code": 2, "msg": "Invalid request: too many parameters"} | Unnecessary parameters were provided in the data | +| {"code": 2, "msg": "Invalid request: property name must be a string"} | Property name not provided | +| {"code": 2, "msg": "Invalid request: missing field method at line 1 column 73"} | Data did not provide method | +| {"code":3,"msg":"Invalid JSON: expected value at line %s column %s"} | JSON syntax error | + +## Collection transaction flow + +**Payload:** + +```javascript +{ + "e": "aggTrade", // Event type + "E": 123456789, // Event time + "s": "BNBBTC", // Symbol + "a": 12345, // Aggregate trade ID + "p": "0.001", // Price + "q": "100", // Quantity + "f": 100, // First trade ID + "l": 105, // Last trade ID + "T": 123456785, // Trade time + "m": true, // Is the buyer the market maker? + "M": true // Ignore +} +``` + +The collection transaction stream pushes transaction information and is an aggregation of a single order. + +**Stream name:** `@aggTrade` + +**Update speed:** real-time + +## Tick-by-tick trades + +**Payload:** + +```javascript +{ + "e": "trade", // Event type + "E": 123456789, // Event time + "s": "BNBBTC", // Symbol + "t": 12345, // Trade ID + "p": "0.001", // Price + "q": "100", // Quantity + "T": 123456785, // Trade time + "m": true, // Is the buyer the market maker? +} +``` + +**Stream name:** `@trade` + +Each trade stream pushes the details of every individual trade. A **trade**, also called a transaction, is defined as a match between exactly one taker and one maker. + +## K-line streams + +**Payload:** + +```javascript +{ + "e": "kline", // Event type + "E": 123456789, // Event time + "s": "BNBBTC", // Symbol + "k": { + "t": 123400000, // Kline start time + "T": 123460000, // Kline close time + "s": "BNBBTC", // Symbol + "i": "1m", // Interval + "f": 100, // First trade ID + "L": 200, // Last trade ID + "o": "0.0010", // Open price + "c": "0.0020", // Close price + "h": "0.0025", // High price + "l": "0.0015", // Low price + "v": "1000", // Base asset volume + "n": 100, // Number of trades + "x": false, // Is this kline closed? + "q": "1.0000", // Quote asset volume + "V": "500", // Taker buy base asset volume + "Q": "0.500", // Taker buy quote asset volume + "B": "123456" // Ignore + } +} +``` + +The K-line stream pushes per-second updates for the requested type of K-line (the latest candle). + +**Stream name:** `@kline_` + +**Update speed:** 2000ms + +**K-line interval parameter:** + +m (minutes), h (hours), d (days), w (weeks), M (months) + +* 1m +* 3m +* 5m +* 15m +* 30m +* 1h +* 2h +* 4h +* 6h +* 8h +* 12h +* 1d +* 3d +* 1w +* 1M + +## Simplified ticker by symbol + +**Payload:** + +```javascript + { + "e": "24hrMiniTicker", // Event type + "E": 123456789, // Event time + "s": "BNBBTC", // Symbol + "c": "0.0025", // Close price + "o": "0.0010", // Open price + "h": "0.0025", // High price + "l": "0.0010", // Low price + "v": "10000", // Total traded base asset volume + "q": "18" // Total traded quote asset volume + } +``` + +Refreshed simplified 24-hour ticker information by symbol + +**Stream name:** `@miniTicker` + +**Update speed:** 1000ms + +## Compact tickers for all symbols in the entire market + +**Payload:** + +```javascript +[ + { + // Same as @miniTicker payload + } +] +``` + +Same as above, but pushes all trading pairs. Note that only updated tickers will be pushed. + +**Stream name:** \!miniTicker@arr + +**Update speed:** 1000ms + +## Full ticker per symbol + +**Payload:** + +```javascript +{ + "e": "24hrTicker", // Event type + "E": 123456789, // Event time + "s": "BNBBTC", // Symbol + "p": "0.0015", // Price change + "P": "250.00", // Price change percent + "w": "0.0018", // Weighted average price + "c": "0.0025", // Last price + "Q": "10", // Last quantity + "o": "0.0010", // Open price + "h": "0.0025", // High price + "l": "0.0010", // Low price + "v": "10000", // Total traded base asset volume + "q": "18", // Total traded quote asset volume + "O": 0, // Statistics open time + "C": 86400000, // Statistics close time + "F": 0, // First trade ID + "L": 18150, // Last trade Id + "n": 18151 // Total number of trades +} +``` + +Pushes per-second tag statistics for a single trading pair over a rolling 24-hour window. + +**Stream name:** `@ticker` + +**Update speed:** 1000ms + +## Complete ticker for all trading pairs on the entire market + +**Payload:** + +```javascript +[ + { + // Same as @ticker payload + } +] +``` + +Pushes the full 24-hour refreshed ticker information for all trading pairs across the entire market. Note that tickers without updates will not be pushed. + +**Stream name:** `!ticker@arr` + +**Update speed:** 1000ms + +## Best order book information by symbol + +**Payload:** + +```javascript +{ + "u":400900217, // order book updateId + "s":"BNBUSDT", // symbol + "b":"25.35190000", // best bid price + "B":"31.21000000", // best bid qty + "a":"25.36520000", // best ask price + "A":"40.66000000" // best ask qty +} +``` + +Real-time push of best order book information for the specified trading pair + +**Stream name:** `@bookTicker` + +**Update speed:** Real-time + +## Best order book information across the entire market + +**Payload:** + +```javascript +{ + // 同 @bookTicker payload +} +``` + +Real-time push of the best order information for all trading pairs + +**Stream name:** `!bookTicker` + +**Update speed:** Real-time + +## Limited depth information + +**Payload:** + +```javascript +{ + "e": "depthUpdate", // Event type + "E": 123456789, // Event time + "T": 123456788, // Transaction time + "s": "BTCUSDT", // Symbol + "U": 100, // First update ID in event + "u": 120, // Final update ID in event + "pu": 99, // Final update Id in last stream(ie `u` in last stream) +  "bids": [ // Bids to be updated + [ + "0.0024", // Price level to be updated + "10" // Quantity + ] + ], + "asks": [ // Asks to be updated + [ + "0.0026", // Price level to be updated + "100" // Quantity + ] + ] +} +``` + +Limited depth information pushed every second or every 100 milliseconds. Levels indicate how many levels of bid/ask information, optional 5/10/20 levels. + +**Stream names:** `@depth` or `@depth@100ms`. + +**Update speed:** 1000ms or 100ms + +## Incremental depth information + +**Payload:** + +```javascript +{ + "e": "depthUpdate", // Event type + "E": 123456789, // Event time + "T": 123456788, // Transaction time + "s": "BTCUSDT", // Symbol + "U": 100, // First update ID in event + "u": 120, // Final update ID in event + "pu": 99, // Final update Id in last stream(ie `u` in last stream) + "b": [ // Bids to be updated + [ + "5.4", // Price level to be updated + "10" // Quantity + ] + ], + "a": [ // Asks to be updated + [ + "5.6", // Price level to be updated + "100" // Quantity + ] + ] +} +``` + +Pushes the changed parts of the orderbook (if any) every second or every 100 milliseconds + +**Stream name:** `@depth` or `@depth@100ms` + +**Update speed:** 1000ms or 100ms + +## How to correctly maintain a local copy of an order book + +1. Subscribe to **wss://sstream.asterdex-testnet.com/ws/asterusdt@depth** +2. Start caching the received updates. For the same price level, later updates overwrite earlier ones. +3. Fetch the REST endpoint [**https://sapi.asterdex-testnet.com/api/v3/depth?symbol=ASTERUSDT\&limit=1000**](https://sapi.asterdex-testnet.com/api/v3/depth?symbol=ASTERUSDT&limit=1000) to obtain a 1000-level depth snapshot +4. Discard from the currently cached messages those with `u` \<= the `lastUpdateId` obtained in step 3 (drop older, expired information) +5. Apply the depth snapshot to your local order book copy, and resume updating the local copy from the first WebSocket event whose `U` \<= `lastUpdateId`\+1 **and** `u` \>= `lastUpdateId`\+1 +6. Each new event’s `U` should equal exactly the previous event’s `u`\+1; otherwise packets may have been lost \- restart initialization from step 3 +7. The order quantity in each event represents the current order quantity at that price as an **absolute value**, not a relative change +8. If the order quantity at a given price is 0, it means the orders at that price have been canceled or filled, and that price level should be removed + +# WebSocket account information push + +* The base URL for the API endpoints listed in this document is: [**https://sapi.asterdex-testnet.com**](https://sapi.asterdex-testnet.com) +* The `listenKey` used to subscribe to account data is valid for 60 minutes from the time of creation +* You can extend the 60-minute validity of a `listenKey` by sending a `PUT` request +* You can immediately close the current data stream and invalidate the `listenKey` by sending a `DELETE` for a `listenKey` +* Sending a `POST` on an account with a valid `listenKey` will return the currently valid `listenKey` and extend its validity by 60 minutes +* The WebSocket interface baseurl: **wss://sstream.asterdex-testnet.com** +* The stream name for subscribing to the user account data stream is \*\*/ws/\*\* +* Each connection is valid for no more than 24 hours; please handle disconnections and reconnections appropriately + +## Listen Key (spot account) + +### Generate Listen Key (USER\_STREAM) + +**Response** + +```javascript +{ + "listenKey": "pqia91ma19a5s61cv6a81va65sdf19v8a65a1a5s61cv6a81va65sdf19v8a65a1" +} +``` + +`POST /api/v3/listenKey` + +Start a new data stream. The data stream will be closed after 60 minutes unless a keepalive is sent. If the account already has a valid `listenKey`, that `listenKey` will be returned and its validity extended by 60 minutes. + +**Weight:** 1 + +**Parameters:** NONE + +### Extend Listen Key validity period (USER\_STREAM) + +**Response** + +```javascript +{} +``` + +`PUT /api/v3/listenKey` + +Validity extended to 60 minutes after this call. It is recommended to send a ping every 30 minutes. + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| listenKey | STRING | YES | | + +### Close Listen Key (USER\_STREAM) + +**Response** + +```javascript +{} +``` + +`DELETE /api/v3/listenKey` + +Close user data stream + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| listenKey | STRING | YES | | + +## Payload: ACCOUNT\_UPDATE + +An `outboundAccountPosition` event is sent whenever an account balance changes; it contains the assets that may have changed due to the event that generated the balance update. + +**Payload** + +```javascript +{ + "B":[ //Balance + { + "a":"SLP25",   //Asset + "f":"10282.42029415",   //Free + "l":"653.00000001"   //Locked + }, + { + "a":"ADA25", + "f":"9916.96229880", + "l":"34.00510000" + } + ], + "e":"outboundAccountPosition",   //Event type + "T":1649926447190,   //Time of last account update + "E":1649926447205   //Event Time + "m":"WITHDRAW" // Event reason type +} +``` + +## Payload: Order Update + +Orders are updated via the `executionReport` event + +**Payload** + +```javascript +{ + "s":"ADA25SLP25",   // symbol + "c":"Xzh0gnxT41PStbwqOtXnjD",  // client order id + "S":"SELL",   // order direction + "o":"LIMIT",   // order type + "f":"GTC",   // Time in force + "q":"10.001000",   // Order quantity + "p":"19.1000000000",   // Order price + "ap":"19.0999999955550656", //average price + "P":"0", //stop price + "x":"TRADE",   // Current execution type + "X":"PARTIALLY_FILLED",   // Current order status + "i":27,   // Order ID + "l":"1",   // Last executed quantity + "z":"8.999000",   // Cumulative filled quantity + "L":"19.1000000000",   // Last executed price + "n":"0.00382000",  // Commission amount + "N":"SLP25",   // Commission asset + "T":1649926447190,   //Trasanction Time + "t":18,   // transaction id + "m":true,   // is this trade the maker side? + "ot":"LIMIT", //original order type + "O":0,   // Order creation time + "Z":"171.88089996", // Cumulative quote asset transacted quantity + "Y":"19.1000000000000000",   // Last quote asset transacted quantity (i.e. lastPrice * lastQty) + "Q":"0",   // Quote Order Qty + "e":"executionReport",   // event + "E":1649926447209  // event time +} +``` + +**Execution type:** + +* NEW \- New Order +* CANCELED \- Order canceled +* REJECTED \- New order was rejected +* TRADE \- Order had a new fill +* EXPIRED \- Order expired (based on the order's Time In Force parameter) + +\#错误代码 + +error JSON payload: + +```javascript +{ + "code":-1121, + "msg":"Invalid symbol." +} +``` + +Errors consist of two parts: an error code and a message. The code is standardized, but the message may vary. + +## 10xx \- General server or network issues + +### \-1000 UNKNOWN + +* An unknown error occurred while processing the request. + +### \-1001 DISCONNECTED + +* Internal error; unable to process your request. Please try again. + +### \-1002 UNAUTHORIZED + +* You are not authorized to execute this request. + +### \-1003 TOO\_MANY\_REQUESTS + +* Too many requests queued. +* Too many requests; please use the WebSocket for live updates. +* Too many requests; current limit is %s requests per minute. Please use the WebSocket for live updates to avoid polling the API. +* Too many request weights; IP banned until %s. Please use the WebSocket for live updates to avoid bans. + +### \-1004 DUPLICATE\_IP + +* This IP is already on the white list. + +### \-1005 NO\_SUCH\_IP + +* No such IP has been whitelisted. + +### \-1006 UNEXPECTED\_RESP + +* An unexpected response was received from the message bus. Execution status unknown. + +### \-1007 TIMEOUT + +* Timeout waiting for response from backend server. Send status unknown; execution status unknown. + +### \-1014 UNKNOWN\_ORDER\_COMPOSITION + +* The current order parameter combination is not supported. + +### \-1015 TOO\_MANY\_ORDERS + +* Too many new orders. +* Too many new orders; the current limit is %s orders per %s. + +### \-1016 SERVICE\_SHUTTING\_DOWN + +* This service is no longer available. + +### \-1020 UNSUPPORTED\_OPERATION + +* This operation is not supported. + +### \-1021 INVALID\_TIMESTAMP + +* Timestamp for this request is outside of the recvWindow. +* The timestamp for this request was 1000ms ahead of the server's time. + +### \-1022 INVALID\_SIGNATURE + +* The signature for this request is invalid. + +### \-1023 START\_TIME\_GREATER\_THAN\_END\_TIME + +* The start time in the parameters is after the end time. + +## 11xx \- Request issues + +### \-1100 ILLEGAL\_CHARS + +* Illegal characters found in a parameter. +* Illegal characters found in parameter %s; legal range is %s. + +### \-1101 TOO\_MANY\_PARAMETERS + +* Too many parameters sent for this endpoint. +* Too many parameters; expected %s and received %s. +* Duplicate values for a parameter detected. + +### \-1102 MANDATORY\_PARAM\_EMPTY\_OR\_MALFORMED + +* A mandatory parameter was not sent, was empty/null, or malformed. +* Mandatory parameter %s was not sent, was empty/null, or malformed. +* Param %s or %s must be sent, but both were empty/null. + +### \-1103 UNKNOWN\_PARAM + +* An unknown parameter was sent. + +### \-1104 UNREAD\_PARAMETERS + +* Not all sent parameters were read. +* Not all sent parameters were read; read %s parameter(s) but %s parameter(s) were sent. + +### \-1105 PARAM\_EMPTY + +* A parameter was empty. +* Parameter %s was empty. + +### \-1106 PARAM\_NOT\_REQUIRED + +* A parameter was sent when not required.  + +### \-1111 BAD\_PRECISION  + +* The precision exceeds the maximum defined for this asset. + +### \-1112 NO\_DEPTH + +* No open orders for the trading pair. + +### \-1114 TIF\_NOT\_REQUIRED + +* TimeInForce parameter sent when not required. + +### \-1115 INVALID\_TIF + +* Invalid timeInForce. + +### \-1116 INVALID\_ORDER\_TYPE + +* Invalid orderType. + +### \-1117 INVALID\_SIDE + +* Invalid order side. + +### \-1118 EMPTY\_NEW\_CL\_ORD\_ID + +* New client order ID was empty. + +### \-1119 EMPTY\_ORG\_CL\_ORD\_ID + +* The client’s custom order ID is empty. + +### \-1120 BAD\_INTERVAL + +* Invalid time interval. + +### \-1121 BAD\_SYMBOL + +* Invalid trading pair. + +### \-1125 INVALID\_LISTEN\_KEY + +* This listenKey does not exist. + +### \-1127 MORE\_THAN\_XX\_HOURS + +* The query interval is too large. +* More than %s hours between startTime and endTime. + +### \-1128 OPTIONAL\_PARAMS\_BAD\_COMBO  + +* Combination of optional parameters invalid.  + +### \-1130 INVALID\_PARAMETER  + +* The parameter sent contains invalid data. +* Data sent for parameter %s is not valid.  + +### \-1136 INVALID\_NEW\_ORDER\_RESP\_TYPE  + +* Invalid newOrderRespType.  + +## 20xx \- Processing Issues  + +### \-2010 NEW\_ORDER\_REJECTED  + +* New order rejected. + +### \-2011 CANCEL\_REJECTED + +* Order cancellation rejected. + +### \-2013 NO\_SUCH\_ORDER + +* Order does not exist. + +### \-2014 BAD\_API\_KEY\_FMT + +* API-key format invalid. + +### \-2015 REJECTED\_MBX\_KEY + +* Invalid API key, IP, or permissions for action. + +### \-2016 NO\_TRADING\_WINDOW + +* No trading window could be found for the symbol. Try ticker/24hrs instead. + +### \-2018 BALANCE\_NOT\_SUFFICIENT + +* Balance is insufficient. + +### \-2020 UNABLE\_TO\_FILL + +* Unable to fill. + +### \-2021 ORDER\_WOULD\_IMMEDIATELY\_TRIGGER + +* Order would immediately trigger. + +### \-2022 REDUCE\_ONLY\_REJECT + +* ReduceOnly Order is rejected. + +### \-2024 POSITION\_NOT\_SUFFICIENT + +* Position is not sufficient. + +### \-2025 MAX\_OPEN\_ORDER\_EXCEEDED + +* Reached max open order limit. + +### \-2026 REDUCE\_ONLY\_ORDER\_TYPE\_NOT\_SUPPORTED + +* This OrderType is not supported when reduceOnly. + +## 40xx \- Filters and other Issues + +### \-4000 INVALID\_ORDER\_STATUS + +* Invalid order status. + +### \-4001 PRICE\_LESS\_THAN\_ZERO + +* Price less than 0\. + +### \-4002 PRICE\_GREATER\_THAN\_MAX\_PRICE + +* Price greater than max price. + +### \-4003 QTY\_LESS\_THAN\_ZERO + +* Quantity less than zero. + +### \-4004 QTY\_LESS\_THAN\_MIN\_QTY + +* Quantity less than minimum quantity. + +### \-4005 QTY\_GREATER\_THAN\_MAX\_QTY + +* Quantity greater than maximum quantity. + +### \-4006 STOP\_PRICE\_LESS\_THAN\_ZERO + +* Stop price less than zero. + +### \-4007 STOP\_PRICE\_GREATER\_THAN\_MAX\_PRICE + +* Stop price greater than max price. + +### \-4008 TICK\_SIZE\_LESS\_THAN\_ZERO + +* Tick size less than zero. + +### \-4009 MAX\_PRICE\_LESS\_THAN\_MIN\_PRICE + +* Max price less than min price. + +### \-4010 MAX\_QTY\_LESS\_THAN\_MIN\_QTY + +* Maximum quantity less than minimum quantity. + +### \-4011 STEP\_SIZE\_LESS\_THAN\_ZERO + +* Step size less than zero. + +### \-4012 MAX\_NUM\_ORDERS\_LESS\_THAN\_ZERO + +* Maximum order quantity less than 0\. + +### \-4013 PRICE\_LESS\_THAN\_MIN\_PRICE + +* Price less than minimum price. + +### \-4014 PRICE\_NOT\_INCREASED\_BY\_TICK\_SIZE + +* Price not increased by tick size. + +### \-4015 INVALID\_CL\_ORD\_ID\_LEN + +* Client order ID is not valid. +* Client order ID length should not be more than 36 characters. + +### \-4016 PRICE\_HIGHTER\_THAN\_MULTIPLIER\_UP + +* Price is higher than mark price multiplier cap. + +### \-4017 MULTIPLIER\_UP\_LESS\_THAN\_ZERO + +* Multiplier up less than zero. + +### \-4018 MULTIPLIER\_DOWN\_LESS\_THAN\_ZERO + +* Multiplier down less than zero. + +### \-4019 COMPOSITE\_SCALE\_OVERFLOW + +* Composite scale too large. + +### \-4020 TARGET\_STRATEGY\_INVALID + +* Target strategy invalid for orderType %s, reduceOnly %b' + +### \-4021 INVALID\_DEPTH\_LIMIT + +* Invalid depth limit. +* %s is not a valid depth limit. + +### \-4022 WRONG\_MARKET\_STATUS + +* Market status sent is not valid. + +### \-4023 QTY\_NOT\_INCREASED\_BY\_STEP\_SIZE + +* The increment of the quantity is not a multiple of the step size. + +### \-4024 PRICE\_LOWER\_THAN\_MULTIPLIER\_DOWN + +* Price is lower than mark price multiplier floor. + +### \-4025 MULTIPLIER\_DECIMAL\_LESS\_THAN\_ZERO + +* Multiplier decimal less than zero. + +### \-4026 COMMISSION\_INVALID + +* Commission invalid. +* Incorrect profit value. +* `%s` less than zero. +* `%s` absolute value greater than `%s`. + +### \-4027 INVALID\_ACCOUNT\_TYPE + +* Invalid account type. + +### \-4029 INVALID\_TICK\_SIZE\_PRECISION + +* Tick size precision is invalid. +* Price decimal precision is incorrect. + +### \-4030 INVALID\_STEP\_SIZE\_PRECISION + +* The number of decimal places for the step size is incorrect. + +### \-4031 INVALID\_WORKING\_TYPE + +* Invalid parameter working type: `%s` + +### \-4032 EXCEED\_MAX\_CANCEL\_ORDER\_SIZE + +* Exceeds the maximum order quantity that can be canceled. +* Invalid parameter working type: `%s` + +### \-4044 INVALID\_BALANCE\_TYPE + +* The balance type is incorrect. + +### \-4045 MAX\_STOP\_ORDER\_EXCEEDED + +* Reached the stop-loss order limit. + +### \-4055 AMOUNT\_MUST\_BE\_POSITIVE + +* The quantity must be a positive integer. + +### \-4056 INVALID\_API\_KEY\_TYPE + +* The API key type is invalid. + +### \-4057 INVALID\_RSA\_PUBLIC\_KEY + +* The API key is invalid. + +### \-4058 MAX\_PRICE\_TOO\_LARGE + +* maxPrice and priceDecimal too large, please check. + +### \-4060 INVALID\_POSITION\_SIDE + +* Invalid position side. + +### \-4061 POSITION\_SIDE\_NOT\_MATCH + +* The order's position direction does not match the user’s settings. + +### \-4062 REDUCE\_ONLY\_CONFLICT + +* Invalid or improper reduceOnly value. + +### \-4084 UPCOMING\_METHOD + +* Method is not allowed currently. Coming soon. + +### \-4086 INVALID\_PRICE\_SPREAD\_THRESHOLD + +* Invalid price spread threshold. + +### \-4087 REDUCE\_ONLY\_ORDER\_PERMISSION + +* Users can only place reduce-only orders. + +### \-4088 NO\_PLACE\_ORDER\_PERMISSION + +* User cannot place orders currently. + +### \-4114 INVALID\_CLIENT\_TRAN\_ID\_LEN + +* clientTranId is not valid. +* The customer's tranId length should be less than 64 characters. + +### \-4115 DUPLICATED\_CLIENT\_TRAN\_ID + +* clientTranId is duplicated. +* The client's tranId should be unique within 7 days. + +### \-4118 REDUCE\_ONLY\_MARGIN\_CHECK\_FAILED + +* ReduceOnly Order failed. Please check your existing position and open orders + +### \-4131 MARKET\_ORDER\_REJECT + +* The counterparty's best price does not meet the PERCENT\_PRICE filter limit. + +### \-4135 INVALID\_ACTIVATION\_PRICE + +* Invalid activation price. + +### \-4137 QUANTITY\_EXISTS\_WITH\_CLOSE\_POSITION + +* Quantity must be zero when closePosition is true. + +### \-4138 REDUCE\_ONLY\_MUST\_BE\_TRUE + +* Reduce only must be true when closePosition is true. + +### \-4139 ORDER\_TYPE\_CANNOT\_BE\_MKT + +* Order type cannot be a market order if it cannot be canceled. + +### \-4140 INVALID\_OPENING\_POSITION\_STATUS + +* Invalid symbol status for opening position. + +### \-4141 SYMBOL\_ALREADY\_CLOSED + +* Trading pair has been delisted. + +### \-4142 STRATEGY\_INVALID\_TRIGGER\_PRICE + +* Rejected: Take Profit or Stop order would be triggered immediately. + +### \-4164 MIN\_NOTIONAL + +* Order notional must be at least 5.0 (unless you select Reduce Only) +* Order notional must be no smaller than %s (unless you choose Reduce Only) + +### \-4165 INVALID\_TIME\_INTERVAL + +* Invalid time interval +* Maximum time interval is %s days + +### \-4183 PRICE\_HIGHTER\_THAN\_STOP\_MULTIPLIER\_UP + +* Limit price cannot be higher than the cap of %s. +* Take-Profit/Stop-Loss price cannot be higher than the cap of %s. + +### \-4184 PRICE\_LOWER\_THAN\_STOP\_MULTIPLIER\_DOWN + +* Price is below the stop price limit. +* Take-Profit/Stop-Loss price must be above the trigger price × multiplier floor. +* Order price (limit or TP/SL) can’t be below %s. + From f47086e179f66010d5ebd81e54f815bc4601d1a6 Mon Sep 17 00:00:00 2001 From: mark Date: Wed, 21 Jan 2026 19:24:35 +0800 Subject: [PATCH 040/131] Remaining Openable Notional Value --- aster-finance-futures-api.md | 29 +++++++++++++++++++++++++++++ aster-finance-futures-api_CN.md | 27 +++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/aster-finance-futures-api.md b/aster-finance-futures-api.md index a70b8dc..21c4833 100644 --- a/aster-finance-futures-api.md +++ b/aster-finance-futures-api.md @@ -94,6 +94,7 @@ - [Position ADL Quantile Estimation (USER_DATA)](#position-adl-quantile-estimation-user_data) - [User's Force Orders (USER_DATA)](#users-force-orders-user_data) - [User Commission Rate (USER_DATA)](#user-commission-rate-user_data) + - [Remaining Openable Notional Value (USER_DATA)](#remaining-openable-notional-value-user_data) - [User Data Streams](#user-data-streams) - [Start User Data Stream (USER_STREAM)](#start-user-data-stream-user_stream) - [Keepalive User Data Stream (USER_STREAM)](#keepalive-user-data-stream-user_stream) @@ -3624,6 +3625,34 @@ recvWindow | LONG | NO timestamp | LONG | YES +## Remaining Openable Notional Value (USER_DATA) + +> **Response:** + +```javascript +{ + "remainingOpenableNotionalValue": 200 // User's current ramaining openable notional value,USDT +} +``` + +`` +GET /fapi/v1/remainingOpenableNotionalValue (HMAC SHA256) +`` + +**Weight:** +20 + + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES +leverage | INT | YES +recvWindow | LONG | NO +timestamp | LONG | YES + + diff --git a/aster-finance-futures-api_CN.md b/aster-finance-futures-api_CN.md index a0de164..231c9d5 100644 --- a/aster-finance-futures-api_CN.md +++ b/aster-finance-futures-api_CN.md @@ -94,6 +94,7 @@ - [持仓ADL队列估算 (USER_DATA)](#持仓adl队列估算-user_data) - [用户强平单历史 (USER_DATA)](#用户强平单历史-user_data) - [用户手续费率 (USER_DATA)](#用户手续费率-user_data) + - [剩余可开仓名义价值 (USER_DATA)](#剩余可开仓名义价值-user_data) - [Websocket 账户信息推送](#websocket-账户信息推送) - [生成listenKey (USER_STREAM)](#生成listenkey-user_stream) - [延长listenKey有效期 (USER_STREAM)](#延长listenkey有效期-user_stream) @@ -3508,6 +3509,32 @@ recvWindow | LONG | NO timestamp | LONG | YES +## 剩余可开仓名义价值 (USER_DATA) + +> **响应:** + +```javascript +{ + "remainingOpenableNotionalValue": 200 //用户当前可开仓名义价值,单位USDT +} +``` + +`` +GET /fapi/v1/remainingOpenableNotionalValue (HMAC SHA256) +`` + +**权重:** +20 + + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES +leverage | INT | YES +recvWindow | LONG | NO +timestamp | LONG | YES From d7c9b1fd08d526a9ed8e7f2a93519cb7356018fa Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Thu, 22 Jan 2026 20:17:02 +0800 Subject: [PATCH 041/131] eip172 --- aster-finance-futures-api-v3.md | 365 +++++++---------------------- aster-finance-futures-api-v3_CN.md | 353 +++++++--------------------- 2 files changed, 161 insertions(+), 557 deletions(-) diff --git a/aster-finance-futures-api-v3.md b/aster-finance-futures-api-v3.md index 5842451..aebe160 100644 --- a/aster-finance-futures-api-v3.md +++ b/aster-finance-futures-api-v3.md @@ -12,8 +12,6 @@ - [Timing Security](#timing-security) - [Endpoints requiring signature](#endpoints-requiring-signature) - [POST /fapi/v3/order example](#example-of-post-fapiv3order) - - [GET /fapi/v3/order example](#Eexample-of-get-fapiv3order) - - [python script](#python-script) - [Public Endpoints Info](#public-endpoints-info) - [Terminology](#terminology) - [ENUM definitions](#enum-definitions) @@ -254,326 +252,125 @@ if (timestamp < (serverTime + 1000) && (serverTime - timestamp) <= recvWindow){ | privateKey | 0x4fd0a42218f3eae43a6ce26d22544e986139a01e5b34a62db53757ffca81bae1 |[Click Here](https://www.asterdex.com/en/api-wallet) | #### The nonce parameter is the current system time in microseconds. If it exceeds the system time or lags behind it by more than 5 seconds, the request is considered invalid. - ```python #python nonce = math.trunc(time.time()*1000000) print(nonce) #1748310859508867 ``` - ```java +#python //java Instant now = Instant.now(); long microsecond = now.getEpochSecond() * 1000000 + now.getNano() / 1000; ``` -#### Example: The following parameters are business request parameters. - -```python -my_dict = {'symbol': 'SANDUSDT', 'positionSide': 'BOTH', 'type': 'LIMIT', 'side': 'BUY', - 'timeInForce': 'GTC', 'quantity': "190", 'price': 0.28694} -``` -#### Example: All parameters are sent via form body (using Python as an example). +#### Example: Post an order (using Python as an example). -> **Step 1: Convert all business parameters to strings, then sort them in ASCII order to generate a string.** ```python - #Define all element values as strings. - def _trim_dict(my_dict) : - for key in my_dict: - value = my_dict[key] - if isinstance(value, list): - new_value = [] - for item in value: - if isinstance(item, dict): - new_value.append(json.dumps(_trim_dict(item))) - else: - new_value.append(str(item)) - my_dict[key] = json.dumps(new_value) - continue - if isinstance(value, dict): - my_dict[key] = json.dumps(_trim_dict(value)) - continue - my_dict[key] = str(value) - - return my_dict - - #Remove elements with null (empty) values. - my_dict = {key: value for key, value in my_dict.items() if value is not None} - my_dict['recvWindow'] = 50000 - my_dict['timestamp'] = int(round(time.time()*1000)) - # my_dict['timestamp'] = 1749545309665 - #Convert elements to strings. - _trim_dict(my_dict) - #Generate a string sorted by ASCII values and remove special characters. - json_str = json.dumps(my_dict, sort_keys=True).replace(' ', '').replace('\'','\"') - print(json_str) - #{"positionSide":"BOTH","price":"0.28694","quantity":"190","recvWindow":"50000","side":"BUY","symbol":"SANDUSDT","timeInForce":"GTC","timestamp":"1749545309665","type":"LIMIT"} -``` +import time +import requests +from eth_account.messages import encode_structured_data +from eth_account import Account -> **Step 2: Take the string generated in Step 1 and encode it together with the account information and nonce using ABI encoding to generate a hash string.** +typed_data = { + "types": { + "EIP712Domain": [ + {"name": "name", "type": "string"}, + {"name": "version", "type": "string"}, + {"name": "chainId", "type": "uint256"}, + {"name": "verifyingContract", "type": "address"} + ], + "Message": [ + { "name": "msg", "type": "string" } + ] + }, + "primaryType": "Message", + "domain": { + "name": "AsterSignTransaction", + "version": "1", + "chainId": 1666, + "verifyingContract": "0x0000000000000000000000000000000000000000" + }, + "message": { + "msg": "$msg" + } +} -```python - from eth_abi import encode - from web3 import Web3 - #Use Web3 ABI to encode the generated string along with user, signer, and nonce. - encoded = encode(['string', 'address', 'address', 'uint256'], [json_str, user, signer, nonce]) - print(encoded.hex()) - #000000000000000000000000000000000000000000000000000000000000008000000000000000000000000063dd5acc6b1aa0f563956c0e534dd30b6dcf7c4e00000000000000000000000021cf8ae13bb72632562c6fff438652ba1a151bb00000000000000000000000000000000000000000000000000006361457bcec8300000000000000000000000000000000000000000000000000000000000000af7b22706f736974696f6e53696465223a22424f5448222c227072696365223a22302e3238363934222c227175616e74697479223a22313930222c227265637657696e646f77223a223530303030222c2273696465223a22425559222c2273796d626f6c223a2253414e4455534454222c2274696d65496e466f726365223a22475443222c2274696d657374616d70223a2231373439353435333039363635222c2274797065223a224c494d4954227d0000000000000000000000000000000000 - #keccak hex - keccak_hex =Web3.keccak(encoded).hex() - print(keccak_hex) - #9e0273fc91323f5cdbcb00c358be3dee2854afb2d3e4c68497364a2f27a377fc -``` +headers = { + 'Content-Type': 'application/x-www-form-urlencoded', + 'User-Agent': 'PythonApp/1.0' +} +order_url = 'https://fapi.asterdex-testnet.com/fapi/v3/order' -> **Step 3: Sign the hash generated in Step 2 using the privateKey.** +# config your user and agent info here +user = '*' +signer = '*' +private_key = "*" -```python - from eth_account import Account - from eth_abi import encode - from web3 import Web3, EthereumTesterProvider - from eth_account.messages import encode_defunct - - signable_msg = encode_defunct(hexstr=keccak_hex) - signed_message = Account.sign_message(signable_message=signable_msg, private_key=priKey) - signature = '0x'+signed_message.signature.hex() - print(signature) - #0x0337dd720a21543b80ff861cd3c26646b75b3a6a4b5d45805d4c1d6ad6fc33e65f0722778dd97525466560c69fbddbe6874eb4ed6f5fa7e576e486d9b5da67f31b -``` +def get_url(my_dict) -> str: + return '&'.join(f'{key}={str(value)}'for key, value in my_dict.items()) -> **Step 4: Combine all parameters along with the signature generated in Step 3 into the request body.** +_last_ms = 0 +_i = 0 -```python - my_dict['nonce'] = nonce - my_dict['user'] = user - my_dict['signer'] = signer - my_dict['signature'] = '0x'+signed_message.signature.hex() - url ='https://fapi.asterdex.com/fapi/v3/order' - headers = { - 'Content-Type': 'application/x-www-form-urlencoded', - 'User-Agent': 'PythonApp/1.0' - } - res = requests.post(url,data=my_dict,headers=headers) - print(url) - #curl -X POST 'https://fapi.asterdex.com/fapi/v3/order' -d 'symbol=SANDUSDT&positionSide=BOTH&type=LIMIT&side=BUY&timeInForce=GTC&quantity=190&price=0.28694&recvWindow=50000×tamp=1749545309665&nonce=1748310859508867&user=0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e&signer=0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0&signature=0x0337dd720a21543b80ff861cd3c26646b75b3a6a4b5d45805d4c1d6ad6fc33e65f0722778dd97525466560c69fbddbe6874eb4ed6f5fa7e576e486d9b5da67f31b' -``` +def get_nonce(): + global _last_ms, _i + now_ms = int(time.time()) -## Example of POST /fapi/v3/order + if now_ms == _last_ms: + _i += 1 + else: + _last_ms = now_ms + _i = 0 -#### Example: All parameters are sent through the query string (Python 3.9.6). + return now_ms * 1_000_000 + _i -#### Example: The following parameters are API registration information. user, signer, and privateKey are for demonstration purposes only (where privateKey is the private key of the agent). +def send_by_url() : + param = 'symbol=ASTERUSDT&side=BUY&type=LIMIT&quantity=10&price=0.6&timeInForce=GTC' -| Key | Value | -| ---------- | ------------------------------------------------------------------ | -| user | 0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e | -| signer | 0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0 | -| privateKey | 0x4fd0a42218f3eae43a6ce26d22544e986139a01e5b34a62db53757ffca81bae1 | + param += '&nonce=' + str(get_nonce()) + param += '&user=' + user + param += '&signer=' + signer -#### Example: The nonce parameter should be the current system timestamp in microseconds. If it exceeds the current time or lags behind the system time by more than 5 seconds, it will be considered an invalid request. + typed_data['message']['msg'] = param + message = encode_structured_data(typed_data) + signed = Account.sign_message(message, private_key=private_key) + print(signed.signature.hex()) -```python -#python -nonce = math.trunc(time.time()*1000000) -print(nonce) -#1748310859508867 -``` + url = order_url + '?' + param + '&signature=' + signed.signature.hex() -```java -//java -Instant now = Instant.now(); -long microsecond = now.getEpochSecond() * 1000000 + now.getNano() / 1000; -``` - -#### Example: The following parameters are business request parameters. - -```python -my_dict = {'symbol':'SANDUSDT','side':"SELL","type":'LIMIT','orderId':2194215} -``` - -> **Step 1: Convert all business parameters to strings and generate a sorted string based on ASCII order.** - -```python - #Define all element values as strings. - def _trim_dict(my_dict) : - # 假设待删除的字典为d - for key in my_dict: - value = my_dict[key] - if isinstance(value, list): - new_value = [] - for item in value: - if isinstance(item, dict): - new_value.append(json.dumps(_trim_dict(item))) - else: - new_value.append(str(item)) - my_dict[key] = json.dumps(new_value) - continue - if isinstance(value, dict): - my_dict[key] = json.dumps(_trim_dict(value)) - continue - my_dict[key] = str(value) - - return my_dict - - - #Remove elements with empty values. - my_dict = {key: value for key, value in my_dict.items() if value is not None} - my_dict['recvWindow'] = 50000 - my_dict['timestamp'] = int(round(time.time()*1000)) - # my_dict['timestamp'] = 1749545309665 - #Convert all elements to strings. - _trim_dict(my_dict) - #Generate a string sorted by ASCII values and remove special characters. - json_str = json.dumps(my_dict, sort_keys=True).replace(' ', '').replace('\'','\"') - print(json_str) - #{"orderId":"2194215","recvWindow":"50000","side":"BUY","symbol":"SANDUSDT","timestamp":"1749545309665","type":"LIMIT"} -``` - -> **Step 2: Use ABI encoding to combine the string from step 1 with the account information (user, signer) and nonce, then generate a hash string from the encoded result.** - -```python - from eth_abi import encode - from web3 import Web3 - - #Use WEB3 ABI to encode the generated string together with user, signer, and nonce. - encoded = encode(['string', 'address', 'address', 'uint256'], [json_str, user, signer, nonce]) - print(encoded.hex()) - #000000000000000000000000000000000000000000000000000000000000008000000000000000000000000063dd5acc6b1aa0f563956c0e534dd30b6dcf7c4e00000000000000000000000021cf8ae13bb72632562c6fff438652ba1a151bb00000000000000000000000000000000000000000000000000006361457bcec8300000000000000000000000000000000000000000000000000000000000000767b226f726465724964223a2232313934323135222c227265637657696e646f77223a223530303030222c2273696465223a22425559222c2273796d626f6c223a2253414e4455534454222c2274696d657374616d70223a2231373439353435333039363635222c2274797065223a224c494d4954227d00000000000000000000 - keccak_hex =Web3.keccak(encoded).hex() - print(keccak_hex) - #6ad9569ea1355bf62de1b09b33b267a9404239af6d9227fa59e3633edae19e2a -``` + print(url) + res = requests.post(url, headers=headers) -> **Step 3: Sign the hash generated in Step 2 using the privateKey.** + print(res.text) -```python -from eth_account import Account - from eth_abi import encode - from web3 import Web3, EthereumTesterProvider - from eth_account.messages import encode_defunct - - signable_msg = encode_defunct(hexstr=keccak_hex) - signed_message = Account.sign_message(signable_message=signable_msg, private_key=priKey) - signature = '0x'+signed_message.signature.hex() - print(signature) - #0x4f5e36e91f0d4cf5b29b6559ebc2c808d3c808ebb13b2bcaaa478b98fb4195642c7473f0d1aa101359aaf278126af1a53bcb482fb05003bfb6bdc03de03c63151b -``` +def send_by_body() : + my_dict = {"symbol": "ASTERUSDT", "type": "LIMIT", "side": "BUY", + "timeInForce": "GTC", "quantity": "10", "price": "0.6"} -> **Step 4: Combine all parameters and the signature from Step 3 into the request body.** + my_dict['nonce'] = str(get_nonce()) + my_dict['user'] = user + my_dict['signer'] = signer -```python - my_dict['nonce'] = nonce - my_dict['user'] = user - my_dict['signer'] = signer - my_dict['signature'] = '0x'+signed_message.signature.hex() + content = get_url(my_dict) + typed_data['message']['msg'] = content + message = encode_structured_data(typed_data) - url ='https://fapi.asterdex.com/fapi/v3/order' + signed = Account.sign_message(message, private_key=private_key) + print(signed.signature.hex()) - res = requests.get(url, params=my_dict) - print(url) - #curl -X GET 'https://fapi.asterdex.com/fapi/v3/order?symbol=SANDUSDT&side=BUY&type=LIMIT&orderId=2194215&recvWindow=50000×tamp=1749545309665&nonce=1748310859508867&user=0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e&signer=0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0&signature=0x4f5e36e91f0d4cf5b29b6559ebc2c808d3c808ebb13b2bcaaa478b98fb4195642c7473f0d1aa101359aaf278126af1a53bcb482fb05003bfb6bdc03de03c63151b' -``` + my_dict['signature'] = signed.signature.hex() -## python script + print(my_dict) + res = requests.post(order_url, data=my_dict, headers=headers) -```python -#Python 3.9.6 -#Python 3.9.6 -#eth-account~=0.13.7 -#eth-abi~=5.2.0 -#web3~=7.11.0 -#requests~=2.32.3 - -import json -import math -import time -import requests - -from eth_abi import encode -from eth_account import Account -from eth_account.messages import encode_defunct -from web3 import Web3 - -user = '0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e' -signer='0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0' -priKey = "0x4fd0a42218f3eae43a6ce26d22544e986139a01e5b34a62db53757ffca81bae1" -host = 'https://fapi.asterdex.com' -placeOrder = {'url': '/fapi/v3/order', 'method': 'POST', - 'params':{'symbol': 'SANDUSDT', 'positionSide': 'BOTH', 'type': 'LIMIT', 'side': 'BUY', - 'timeInForce': 'GTC', 'quantity': "30", 'price': 0.325,'reduceOnly': True}} -getOrder = {'url':'/fapi/v3/order','method':'GET','params':{'symbol':'SANDUSDT','side':"BUY","type":'LIMIT','orderId':2194215}} - -def call(api): - nonce = math.trunc(time.time() * 1000000) - my_dict = api['params'] - send(api['url'],api['method'],sign(my_dict,nonce)) - -def sign(my_dict,nonce): - my_dict = {key: value for key, value in my_dict.items() if value is not None} - my_dict['recvWindow'] = 50000 - my_dict['timestamp'] = int(round(time.time()*1000)) - msg = trim_param(my_dict,nonce) - signable_msg = encode_defunct(hexstr=msg) - signed_message = Account.sign_message(signable_message=signable_msg, private_key=priKey) - my_dict['nonce'] = nonce - my_dict['user'] = user - my_dict['signer'] = signer - my_dict['signature'] = '0x'+signed_message.signature.hex() - - print(my_dict['signature']) - return my_dict - -def trim_param(my_dict,nonce) -> str: - _trim_dict(my_dict) - json_str = json.dumps(my_dict, sort_keys=True).replace(' ', '').replace('\'','\"') - print(json_str) - encoded = encode(['string', 'address', 'address', 'uint256'], [json_str, user, signer, nonce]) - print(encoded.hex()) - keccak_hex =Web3.keccak(encoded).hex() - print(keccak_hex) - return keccak_hex - -def _trim_dict(my_dict) : - for key in my_dict: - value = my_dict[key] - if isinstance(value, list): - new_value = [] - for item in value: - if isinstance(item, dict): - new_value.append(json.dumps(_trim_dict(item))) - else: - new_value.append(str(item)) - my_dict[key] = json.dumps(new_value) - continue - if isinstance(value, dict): - my_dict[key] = json.dumps(_trim_dict(value)) - continue - my_dict[key] = str(value) - - return my_dict - -def send(url, method, my_dict): - url = host + url - print(url) - print(my_dict) - if method == 'POST': - headers = { - 'Content-Type': 'application/x-www-form-urlencoded', - 'User-Agent': 'PythonApp/1.0' - } - res = requests.post(url, data=my_dict, headers=headers) - print(res.text) - if method == 'GET': - res = requests.get(url, params=my_dict) - print(res.text) - if method == 'DELETE': - res = requests.delete(url, data=my_dict) - print(res.text) + print(res.text) if __name__ == '__main__': - call(placeOrder) - # call(getOrder) + send_by_url() + # send_by_body() ``` ## Public Endpoints Info diff --git a/aster-finance-futures-api-v3_CN.md b/aster-finance-futures-api-v3_CN.md index 649a3fe..f45078a 100644 --- a/aster-finance-futures-api-v3_CN.md +++ b/aster-finance-futures-api-v3_CN.md @@ -11,8 +11,6 @@ - [需要签名的接口](#需要签名的接口) - [时间同步安全](#时间同步安全) - [POST /fapi/v3/order 的示例](#post-fapiv3order-的示例) - - [GET /fapi/v3/order 的示例](#get-fapiv3order-的示例) - - [完整python脚本示例](#完整python脚本示例) - [公开API参数](#公开api参数) - [术语解释](#术语解释) - [枚举定义](#枚举定义) @@ -250,302 +248,111 @@ Instant now = Instant.now(); long microsecond = now.getEpochSecond() * 1000000 + now.getNano() / 1000; ``` -#### 示例 : 以下参数为业务请求参数 +#### 示例 : 下单 (方法以python为例) ```python - my_dict = {'symbol': 'SANDUSDT', 'positionSide': 'BOTH', 'type': 'LIMIT', 'side': 'BUY', - 'timeInForce': 'GTC', 'quantity': "190", 'price': 0.28694} -``` +import time +import requests +from eth_account.messages import encode_structured_data +from eth_account import Account -#### 示例 : 所有参数通过 form body 发送(方法以python为例) +typed_data = { + "types": { + "EIP712Domain": [ + {"name": "name", "type": "string"}, + {"name": "version", "type": "string"}, + {"name": "chainId", "type": "uint256"}, + {"name": "verifyingContract", "type": "address"} + ], + "Message": [ + { "name": "msg", "type": "string" } + ] + }, + "primaryType": "Message", + "domain": { + "name": "AsterSignTransaction", + "version": "1", + "chainId": 1666, + "verifyingContract": "0x0000000000000000000000000000000000000000" + }, + "message": { + "msg": "$msg" + } +} -> **第一步将所有业务参数转字符串后按照ascII排序生成字符串:** +headers = { + 'Content-Type': 'application/x-www-form-urlencoded', + 'User-Agent': 'PythonApp/1.0' +} +order_url = 'https://fapi.asterdex-testnet.com/fapi/v3/order' -```python - #定义所有元素取值转换为字符串 - def _trim_dict(my_dict) : - # 假设待删除的字典为d - for key in my_dict: - value = my_dict[key] - if isinstance(value, list): - new_value = [] - for item in value: - if isinstance(item, dict): - new_value.append(json.dumps(_trim_dict(item))) - else: - new_value.append(str(item)) - my_dict[key] = json.dumps(new_value) - continue - if isinstance(value, dict): - my_dict[key] = json.dumps(_trim_dict(value)) - continue - my_dict[key] = str(value) - - return my_dict - - #移除空值元素 - my_dict = {key: value for key, value in my_dict.items() if value is not None} - my_dict['recvWindow'] = 50000 - my_dict['timestamp'] = int(round(time.time()*1000)) - # my_dict['timestamp'] = 1749545309665 - #将元素转换为字符串 - _trim_dict(my_dict) - #根据ASCII排序生成字符串并移除特殊字符 - json_str = json.dumps(my_dict, sort_keys=True).replace(' ', '').replace('\'','\"') - print(json_str) - {"positionSide":"BOTH","price":"0.28694","quantity":"190","recvWindow":"50000","side":"BUY","symbol":"SANDUSDT","timeInForce":"GTC","timestamp":"1749545309665","type":"LIMIT"} -``` +# config your user and agent info here +user = '*' +signer = '*' +private_key = "*" -> **第二步将第一步生成的字符串与账户信息以及nonce进行abi编码生成hash字符串:** +def get_url(my_dict) -> str: + return '&'.join(f'{key}={str(value)}'for key, value in my_dict.items()) -```python - from eth_abi import encode - from web3 import Web3 - #使用WEB3 ABI对生成的字符串和user, signer, nonce进行编码 - encoded = encode(['string', 'address', 'address', 'uint256'], [json_str, user, signer, nonce]) - print(encoded.hex()) - #000000000000000000000000000000000000000000000000000000000000008000000000000000000000000063dd5acc6b1aa0f563956c0e534dd30b6dcf7c4e00000000000000000000000021cf8ae13bb72632562c6fff438652ba1a151bb00000000000000000000000000000000000000000000000000006361457bcec8300000000000000000000000000000000000000000000000000000000000000af7b22706f736974696f6e53696465223a22424f5448222c227072696365223a22302e3238363934222c227175616e74697479223a22313930222c227265637657696e646f77223a223530303030222c2273696465223a22425559222c2273796d626f6c223a2253414e4455534454222c2274696d65496e466f726365223a22475443222c2274696d657374616d70223a2231373439353435333039363635222c2274797065223a224c494d4954227d0000000000000000000000000000000000 - #keccak hex - keccak_hex =Web3.keccak(encoded).hex() - print(keccak_hex) - #9e0273fc91323f5cdbcb00c358be3dee2854afb2d3e4c68497364a2f27a377fc -``` -> **第三步将第二步生成的hash用privateKey进行签名:** -```python - from eth_account import Account - from eth_abi import encode - from web3 import Web3, EthereumTesterProvider - from eth_account.messages import encode_defunct - - signable_msg = encode_defunct(hexstr=keccak_hex) - signed_message = Account.sign_message(signable_message=signable_msg, private_key=priKey) - signature = '0x'+signed_message.signature.hex() - print(signature) - #0x0337dd720a21543b80ff861cd3c26646b75b3a6a4b5d45805d4c1d6ad6fc33e65f0722778dd97525466560c69fbddbe6874eb4ed6f5fa7e576e486d9b5da67f31b -``` -> **第四步将所有参数以及第三步生成的signature组装成请求体:** +_last_ms = 0 +_i = 0 -```python - my_dict['nonce'] = nonce - my_dict['user'] = user - my_dict['signer'] = signer - my_dict['signature'] = '0x'+signed_message.signature.hex() - url ='https://fapi.asterdex.com/fapi/v3/order' - headers = { - 'Content-Type': 'application/x-www-form-urlencoded', - 'User-Agent': 'PythonApp/1.0' - } - res = requests.post(url,data=my_dict,headers=headers) - print(url) - #curl -X POST 'https://fapi.asterdex.com/fapi/v3/order' -d 'symbol=SANDUSDT&positionSide=BOTH&type=LIMIT&side=BUY&timeInForce=GTC&quantity=190&price=0.28694&recvWindow=50000×tamp=1749545309665&nonce=1748310859508867&user=0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e&signer=0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0&signature=0x0337dd720a21543b80ff861cd3c26646b75b3a6a4b5d45805d4c1d6ad6fc33e65f0722778dd97525466560c69fbddbe6874eb4ed6f5fa7e576e486d9b5da67f31b' +def get_nonce(): + global _last_ms, _i + now_ms = int(time.time()) -``` + if now_ms == _last_ms: + _i += 1 + else: + _last_ms = now_ms + _i = 0 -## GET /fapi/v3/order 的示例 -#### 示例 : 所有参数通过 query string 发送(Python 3.9.6) + return now_ms * 1_000_000 + _i -#### 示例 : 以下参数为api注册信息,user,signer,privateKey仅供示范(privateKey为agent的私钥) +def send_by_url() : + param = 'symbol=ASTERUSDT&side=BUY&type=LIMIT&quantity=10&price=0.6&timeInForce=GTC' -Key | Value ------------- | ------------ -user | 0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e -signer | 0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0 -privateKey | 0x4fd0a42218f3eae43a6ce26d22544e986139a01e5b34a62db53757ffca81bae1 + param += '&nonce=' + str(get_nonce()) + param += '&user=' + user + param += '&signer=' + signer -#### 示例 : nonce参数为当前系统微秒值,超过系统时间50s,或者落后系统时间超过5s为非法请求 -```python -#python -nonce = math.trunc(time.time()*1000000) -print(nonce) -#1748310859508867 -``` -```java -//java -Instant now = Instant.now(); -long microsecond = now.getEpochSecond() * 1000000 + now.getNano() / 1000; -``` + typed_data['message']['msg'] = param + message = encode_structured_data(typed_data) + signed = Account.sign_message(message, private_key=private_key) + print(signed.signature.hex()) -#### 示例 : 以下参数为业务请求参数 -```python -my_dict = {'symbol':'SANDUSDT','side':"SELL","type":'LIMIT','orderId':2194215} -``` + url = order_url + '?' + param + '&signature=' + signed.signature.hex() -> **第一步将所有业务参数转字符串后按照ascII排序生成字符串:** + print(url) + res = requests.post(url, headers=headers) -```python - #定义所有元素取值转换为字符串 - def _trim_dict(my_dict) : - for key in my_dict: - value = my_dict[key] - if isinstance(value, list): - new_value = [] - for item in value: - if isinstance(item, dict): - new_value.append(json.dumps(_trim_dict(item))) - else: - new_value.append(str(item)) - my_dict[key] = json.dumps(new_value) - continue - if isinstance(value, dict): - my_dict[key] = json.dumps(_trim_dict(value)) - continue - my_dict[key] = str(value) - - return my_dict - - #移除空值元素 - my_dict = {key: value for key, value in my_dict.items() if value is not None} - my_dict['recvWindow'] = 50000 - my_dict['timestamp'] = int(round(time.time()*1000)) - # my_dict['timestamp'] = 1749545309665 - #将元素转换为字符串 - _trim_dict(my_dict) - #根据ASCII排序生成字符串并移除特殊字符 - json_str = json.dumps(my_dict, sort_keys=True).replace(' ', '').replace('\'','\"') - print(json_str) - #{"orderId":"2194215","recvWindow":"50000","side":"BUY","symbol":"SANDUSDT","timestamp":"1749545309665","type":"LIMIT"} -``` + print(res.text) -> **第二步将第一步生成的字符串与账户信息以及nonce进行abi编码生成hash字符串:** +def send_by_body() : + my_dict = {"symbol": "ASTERUSDT", "type": "LIMIT", "side": "BUY", + "timeInForce": "GTC", "quantity": "10", "price": "0.6"} -```python - from eth_abi import encode - from web3 import Web3 - - #使用WEB3 ABI对生成的字符串和user, signer, nonce进行编码 - encoded = encode(['string', 'address', 'address', 'uint256'], [json_str, user, signer, nonce]) - print(encoded.hex()) - #000000000000000000000000000000000000000000000000000000000000008000000000000000000000000063dd5acc6b1aa0f563956c0e534dd30b6dcf7c4e00000000000000000000000021cf8ae13bb72632562c6fff438652ba1a151bb00000000000000000000000000000000000000000000000000006361457bcec8300000000000000000000000000000000000000000000000000000000000000767b226f726465724964223a2232313934323135222c227265637657696e646f77223a223530303030222c2273696465223a22425559222c2273796d626f6c223a2253414e4455534454222c2274696d657374616d70223a2231373439353435333039363635222c2274797065223a224c494d4954227d00000000000000000000 - keccak_hex =Web3.keccak(encoded).hex() - print(keccak_hex) - #6ad9569ea1355bf62de1b09b33b267a9404239af6d9227fa59e3633edae19e2a -``` -> **第三步将第二步生成的hash用privateKey进行签名:** -```python - from eth_account import Account - from eth_abi import encode - from web3 import Web3, EthereumTesterProvider - from eth_account.messages import encode_defunct - - signable_msg = encode_defunct(hexstr=keccak_hex) - signed_message = Account.sign_message(signable_message=signable_msg, private_key=priKey) - signature = '0x'+signed_message.signature.hex() - print(signature) - #0x4f5e36e91f0d4cf5b29b6559ebc2c808d3c808ebb13b2bcaaa478b98fb4195642c7473f0d1aa101359aaf278126af1a53bcb482fb05003bfb6bdc03de03c63151b -``` -> **第四步将所有参数以及第三步生成的signature组装成请求体:** + my_dict['nonce'] = str(get_nonce()) + my_dict['user'] = user + my_dict['signer'] = signer -```python - my_dict['nonce'] = nonce - my_dict['user'] = user - my_dict['signer'] = signer - my_dict['signature'] = '0x'+signed_message.signature.hex() + content = get_url(my_dict) + typed_data['message']['msg'] = content + message = encode_structured_data(typed_data) - url ='https://fapi.asterdex.com/fapi/v3/order' + signed = Account.sign_message(message, private_key=private_key) + print(signed.signature.hex()) - res = requests.get(url, params=my_dict) - print(url) - #curl -X GET 'https://fapi.asterdex.com/fapi/v3/order?symbol=SANDUSDT&side=BUY&type=LIMIT&orderId=2194215&recvWindow=50000×tamp=1749545309665&nonce=1748310859508867&user=0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e&signer=0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0&signature=0x4f5e36e91f0d4cf5b29b6559ebc2c808d3c808ebb13b2bcaaa478b98fb4195642c7473f0d1aa101359aaf278126af1a53bcb482fb05003bfb6bdc03de03c63151b' + my_dict['signature'] = signed.signature.hex() -``` -## 完整python脚本示例 -```python -#Python 3.9.6 -#eth-account~=0.13.7 -#eth-abi~=5.2.0 -#web3~=7.11.0 -#requests~=2.32.3 - -import json -import math -import time -import requests + print(my_dict) + res = requests.post(order_url, data=my_dict, headers=headers) -from eth_abi import encode -from eth_account import Account -from eth_account.messages import encode_defunct -from web3 import Web3 - -user = '0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e' -signer='0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0' -priKey = "0x4fd0a42218f3eae43a6ce26d22544e986139a01e5b34a62db53757ffca81bae1" -host = 'https://fapi.asterdex.com' -placeOrder = {'url': '/fapi/v3/order', 'method': 'POST', - 'params':{'symbol': 'SANDUSDT', 'positionSide': 'BOTH', 'type': 'LIMIT', 'side': 'BUY', - 'timeInForce': 'GTC', 'quantity': "30", 'price': 0.325,'reduceOnly': True}} -getOrder = {'url':'/fapi/v3/order','method':'GET','params':{'symbol':'SANDUSDT','side':"BUY","type":'LIMIT','orderId':2194215}} - -def call(api): - nonce = math.trunc(time.time() * 1000000) - my_dict = api['params'] - send(api['url'],api['method'],sign(my_dict,nonce)) - -def sign(my_dict,nonce): - my_dict = {key: value for key, value in my_dict.items() if value is not None} - my_dict['recvWindow'] = 50000 - my_dict['timestamp'] = int(round(time.time()*1000)) - msg = trim_param(my_dict,nonce) - signable_msg = encode_defunct(hexstr=msg) - signed_message = Account.sign_message(signable_message=signable_msg, private_key=priKey) - my_dict['nonce'] = nonce - my_dict['user'] = user - my_dict['signer'] = signer - my_dict['signature'] = '0x'+signed_message.signature.hex() - - print(my_dict['signature']) - return my_dict - -def trim_param(my_dict,nonce) -> str: - _trim_dict(my_dict) - json_str = json.dumps(my_dict, sort_keys=True).replace(' ', '').replace('\'','\"') - print(json_str) - encoded = encode(['string', 'address', 'address', 'uint256'], [json_str, user, signer, nonce]) - print(encoded.hex()) - keccak_hex =Web3.keccak(encoded).hex() - print(keccak_hex) - return keccak_hex - -def _trim_dict(my_dict) : - for key in my_dict: - value = my_dict[key] - if isinstance(value, list): - new_value = [] - for item in value: - if isinstance(item, dict): - new_value.append(json.dumps(_trim_dict(item))) - else: - new_value.append(str(item)) - my_dict[key] = json.dumps(new_value) - continue - if isinstance(value, dict): - my_dict[key] = json.dumps(_trim_dict(value)) - continue - my_dict[key] = str(value) - - return my_dict - -def send(url, method, my_dict): - url = host + url - print(url) - print(my_dict) - if method == 'POST': - headers = { - 'Content-Type': 'application/x-www-form-urlencoded', - 'User-Agent': 'PythonApp/1.0' - } - res = requests.post(url, data=my_dict, headers=headers) - print(res.text) - if method == 'GET': - res = requests.get(url, params=my_dict) - print(res.text) - if method == 'DELETE': - res = requests.delete(url, data=my_dict) - print(res.text) + print(res.text) if __name__ == '__main__': - call(placeOrder) - # call(getOrder) - + send_by_url() + # send_by_body() ``` ## 公开API参数 From 7682d43ee3dcd4bfac2c74c5de0914b0f6eccec8 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Thu, 22 Jan 2026 20:26:55 +0800 Subject: [PATCH 042/131] noop operation --- aster-finance-futures-api-testnet.md | 21 +++++++++++++++++++++ aster-finance-spot-api-testnet.md | 21 +++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/aster-finance-futures-api-testnet.md b/aster-finance-futures-api-testnet.md index 89f24cf..7291754 100644 --- a/aster-finance-futures-api-testnet.md +++ b/aster-finance-futures-api-testnet.md @@ -27,6 +27,7 @@ - [PERCENT_PRICE](#percent_price) - [MIN_NOTIONAL](#min_notional) - [Market Data Endpoints](#market-data-endpoints) + - [Noop](#noop) - [Test Connectivity](#test-connectivity) - [Check Server Time](#check-server-time) - [Exchange Information](#exchange-information) @@ -662,6 +663,26 @@ Since `MARKET` orders have no price, the mark price is used. # Market Data Endpoints +## Noop + +> **Response:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +``POST /fapi/v3/noop`` + +By using this request, it is possible to efficiently cancel previously sent transactions that are still in the queue and have not completed the on chain operation (Nonce should be equal to this request) + +**Weight:** +1 + +**Parameters:** + ## Test Connectivity > **Response:** diff --git a/aster-finance-spot-api-testnet.md b/aster-finance-spot-api-testnet.md index a10986b..7bf498d 100644 --- a/aster-finance-spot-api-testnet.md +++ b/aster-finance-spot-api-testnet.md @@ -500,6 +500,27 @@ In order to comply with the `market lot size`, the `quantity` must satisfy the f # Market data API + +## Noop(TRADE) + +> **Response:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +``POST /api/v3/noop`` + +By using this request, it is possible to efficiently cancel previously sent transactions that are still in the queue and have not completed the on chain operation (Nonce should be equal to this request) + +**Weight:** +1 + +**Parameters:** + ## Test server connectivity **Response** From 40a38d01656ccc6435e45f1a1b685bfa0b0d31e8 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Tue, 27 Jan 2026 15:40:19 +0800 Subject: [PATCH 043/131] funding config --- aster-finance-futures-api-v3.md | 41 ++++++++++++++++++++++++++++++ aster-finance-futures-api-v3_CN.md | 39 ++++++++++++++++++++++++++++ 2 files changed, 80 insertions(+) diff --git a/aster-finance-futures-api-v3.md b/aster-finance-futures-api-v3.md index aebe160..8f9ed16 100644 --- a/aster-finance-futures-api-v3.md +++ b/aster-finance-futures-api-v3.md @@ -1201,6 +1201,47 @@ Mark Price and Funding Rate * If the number of data between `startTime` and `endTime` is larger than `limit`, return as `startTime` + `limit`. * In ascending order. + +## Get Funding Rate Config + +> **Response:** + +```javascript +[ + { + "symbol": "INJUSDT", + "interestRate": "0.00010000", + "time": 1756197479000, + "fundingIntervalHours": 8, + "fundingFeeCap": 0.03, + "fundingFeeFloor": -0.03 + }, + { + "symbol": "ZORAUSDT", + "interestRate": "0.00005000", + "time": 1756197479000, + "fundingIntervalHours": 4, + "fundingFeeCap": 0.02, + "fundingFeeFloor": -0.02 + } +] +``` + +`` +GET /fapi/v3/fundingInfo +`` + + +**Weight:** +1 + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +symbol | STRING | NO | + + ## 24hr Ticker Price Change Statistics > **Response:** diff --git a/aster-finance-futures-api-v3_CN.md b/aster-finance-futures-api-v3_CN.md index f45078a..df1b771 100644 --- a/aster-finance-futures-api-v3_CN.md +++ b/aster-finance-futures-api-v3_CN.md @@ -1205,6 +1205,45 @@ limit | INT | NO | 默认值:100 最大值:1000 * 如果 `startTime` 和 `endTime` 之间的数据量大于 `limit`, 返回 `startTime` + `limit`情况下的数据。 +## 查询资金费率配置 + +> **响应:** + +```javascript +[ + { + "symbol": "INJUSDT", // 交易对 + "interestRate": "0.00010000", // 利率 + "time": 1756197479000, // 更新时间 + "fundingIntervalHours": 8, // 资金费间隔小时数 + "fundingFeeCap": 0.03, // 资金费上限 + "fundingFeeFloor": -0.03 // 资金费下限 + }, + { + "symbol": "ZORAUSDT", + "interestRate": "0.00005000", + "time": 1756197479000, + "fundingIntervalHours": 4, + "fundingFeeCap": 0.02, + "fundingFeeFloor": -0.02 + } +] +``` + +`` +GET /fapi/v3/fundingInfo +`` + +**权重:** +1 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +--------- | ------ | -------- | ----------------------------------------------------- +symbol | STRING | NO | 交易对 + + ## 24hr价格变动情况 > **响应:** From 5dbbd79d716990e26bdd9fd2d2aea58d2d8ca505 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Tue, 27 Jan 2026 19:07:11 +0800 Subject: [PATCH 044/131] change host --- aster-finance-futures-api-v3.md | 2 +- aster-finance-futures-api-v3_CN.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/aster-finance-futures-api-v3.md b/aster-finance-futures-api-v3.md index 8f9ed16..a5beebc 100644 --- a/aster-finance-futures-api-v3.md +++ b/aster-finance-futures-api-v3.md @@ -302,7 +302,7 @@ headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'PythonApp/1.0' } -order_url = 'https://fapi.asterdex-testnet.com/fapi/v3/order' +order_url = 'https://fapi.asterdex.com/fapi/v3/order' # config your user and agent info here user = '*' diff --git a/aster-finance-futures-api-v3_CN.md b/aster-finance-futures-api-v3_CN.md index df1b771..97c7447 100644 --- a/aster-finance-futures-api-v3_CN.md +++ b/aster-finance-futures-api-v3_CN.md @@ -284,7 +284,7 @@ headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'PythonApp/1.0' } -order_url = 'https://fapi.asterdex-testnet.com/fapi/v3/order' +order_url = 'https://fapi.asterdex.com/fapi/v3/order' # config your user and agent info here user = '*' From 9a1a99b34156a541ea4b54a2df74d7af6d135c32 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Tue, 27 Jan 2026 19:14:59 +0800 Subject: [PATCH 045/131] add aster code demo --- demo/aster-code.py | 242 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 242 insertions(+) create mode 100644 demo/aster-code.py diff --git a/demo/aster-code.py b/demo/aster-code.py new file mode 100644 index 0000000..bbfdc21 --- /dev/null +++ b/demo/aster-code.py @@ -0,0 +1,242 @@ +import time + +import requests +from eth_account import Account +from eth_account.messages import encode_structured_data +from copy import deepcopy +import json + +host = 'https://fapi.asterdex.com' +aster_chain = 'Mainnet' +chain_id = 1666 + +# aster_chain = 'Testnet' +# chain_id = 714 + +user = '0x014c85ffb0fF2F2972237AA950B452f92C69Ae1D' +main_private_key = '*' + + +signer = '0xC98Fd64eBc39E28b92849d9cCef9495663439014' +priKey = '*' + +builder = '0x014c85ffb0fF2F2972237AA950B452f92C69Ae1D' +approveAgent = {'url': '/fapi/v3/approveAgent', 'method': 'POST', + 'params':{'agentName': 'ivanbuilder','agentAddress':signer, + 'ipWhitelist':'', 'expired':1967945395040,'canSpotTrade':True, + 'canPerpTrade':False, 'canWithdraw':False} + ,'main':True,"primary_type":"ApproveAgent"} + +updateAgent = {'url': '/fapi/v3/updateAgent', 'method': 'POST', + 'params':{'agentAddress':signer,'ipWhitelist':'101.198.86.182,192.168.1.100,192.168.1.101', + 'canSpotTrade':False, 'canPerpTrade':True, 'canWithdraw':False},'main':True,"primary_type":"UpdateAgent"} + +delAgent = {'url': '/fapi/v3/agent', 'method': 'DELETE', + 'params':{'agentAddress':signer},'main':True,"primary_type":"DelAgent"} + +getAgents = {'url': '/fapi/v3/agent', 'method': 'GET', + 'params':{}} + +approveBuilder = {'url': '/fapi/v3/approveBuilder', 'method': 'POST', + 'params': {'builder': builder, + 'maxFeeRate': '0.00001','builderName':'ivan3' }, 'main': True,"primary_type":"ApproveBuilder"} + +updateBuilder = {'url': '/fapi/v3/updateBuilder', 'method': 'POST', + 'params':{'builder': builder,'maxFeeRate': '0.00002'},'main':True,"primary_type":"UpdateBuilder"} + +delBuilder = {'url': '/fapi/v3/builder', 'method': 'DELETE', + 'params':{'builder':builder},'main':True,"primary_type":"DelBuilder"} +getBuilders = {'url': '/fapi/v3/builder', 'method': 'GET', 'params':{}} + +placeOrder = {'url': '/fapi/v3/order', 'method': 'POST', + 'params':{'symbol': 'BTCUSDT', 'type': 'MARKET','builder':builder,'feeRate':0.00001, 'side': 'BUY','quantity': "0.03"}} + + + +# 模板只包含 EIP712Domain +eip712_template = { + "types": { + "EIP712Domain": [ + {"name": "name", "type": "string"}, + {"name": "version", "type": "string"}, + {"name": "chainId", "type": "uint256"}, + {"name": "verifyingContract", "type": "address"} + ] + }, + "primaryType": "", + "domain": { + "name": "AsterSignTransaction", + "version": "1", + "chainId": 56, + "verifyingContract": "0x0000000000000000000000000000000000000000" + }, + "message": {} +} + +def infer_eip712_type(value): + """根据 Python 值推断 EIP-712 类型""" + if isinstance(value, bool): + return "bool" + elif isinstance(value, int): + # 这里假设所有整数都是 uint256 + return "uint256" + else: + return "string" + +def build_dynamic_eip712_with_infer(template: dict, primary_type: str, values: dict) -> dict: + eip712_data = deepcopy(template) + eip712_data["primaryType"] = primary_type + + # 自动生成主类型 fields + type_fields = [] + for name, val in values.items(): + type_fields.append({"name": name, "type": infer_eip712_type(val)}) + + eip712_data["types"][primary_type] = type_fields + + # 填充 message + eip712_data["message"] = values + return eip712_data + +def sign_v3_eip712(private_key, message, primary_type) -> str: + new_dict = {k[:1].upper() + k[1:]: v for k, v in message.items()} + + sign_data = build_dynamic_eip712_with_infer( + template=eip712_template, + primary_type=primary_type, + values=new_dict + ) + # sign_data['message'] = new_dict + + data = json.dumps(sign_data, indent=2) + print(data) + + print(sign_data) + msg = encode_structured_data(sign_data) + signed = Account.sign_message(msg, private_key=private_key) + return signed.signature.hex() + +def get_url(my_dict) -> str: + if my_dict is None: + return '' + if len(my_dict) == 0: + return '' + return '&'.join(f'{key}={str(value)}'for key, value in my_dict.items()) + +def sign_v3(private_key, message) -> str: + typed_data_sign = { + "types": { + "EIP712Domain": [ + {"name": "name", "type": "string"}, + {"name": "version", "type": "string"}, + {"name": "chainId", "type": "uint256"}, + {"name": "verifyingContract", "type": "address"} + ], + "Message": [ + {"name": "msg", "type": "string"} + ] + }, + "primaryType": "Message", + "domain": { + "name": "AsterSignTransaction", + "version": "1", + "chainId": chain_id, + "verifyingContract": "0x0000000000000000000000000000000000000000" + }, + "message": { + "msg": message + } + } + # print(typed_data_sign) + # print(message) + + msg = encode_structured_data(typed_data_sign) + signed = Account.sign_message(msg, private_key=private_key) + print(signed.signature.hex()) + + return signed.signature.hex() + +_last_ms = 0 +_i = 0 + +def get_nonce(): + global _last_ms, _i + now_ms = int(time.time()) + + if now_ms == _last_ms: + _i += 1 + else: + _last_ms = now_ms + _i = 0 + + return now_ms * 1_000_000 + _i + +def send_by_url(method_config): + param = method_config['params'] + config_url = method_config['url'] + method = method_config['method'] + primary_type = method_config.get('primary_type') + sign_private_key = main_private_key + main = method_config.get('main') is not None + + param['asterChain'] = aster_chain + param['user'] = user + if not main: + sign_private_key = priKey + param['signer'] = signer + + nonce = get_nonce() + param['nonce'] = nonce + + url = '' + signature ='' + if main: + signature = sign_v3_eip712(sign_private_key, param, primary_type) + param['signature'] = signature + param['signatureChainId'] = 56 + + # url = host + config_url + '?' + get_url(param) + url = host + config_url + + else: + url_param = get_url(param) + url = host + config_url + '?' + url_param + signature = sign_v3(sign_private_key, url_param) + url = url + '&signature=' + signature + + + print(signature) + print(url) + + headers = { + 'Content-Type': 'application/x-www-form-urlencoded', + 'User-Agent': 'PythonApp/1.0' + } + + if method == 'POST': + res = requests.post(url, headers=headers,data=param) + print(res.text) + if method == 'GET': + res = requests.get(url, headers=headers) + print(res.text) + if method == 'DELETE': + # res = requests.delete(url, headers=headers) + res = requests.delete(url, headers=headers,data=param) + + print(res.text) + + +if __name__ == '__main__': + send_by_url(approveAgent) + # send_by_url(updateAgent) + # send_by_url(getAgents) + # send_by_url(delAgent) + + # send_by_url(approveBuilder) + # send_by_url(getBuilders) + # send_by_url(updateBuilder) + # send_by_url(delBuilder) + # send_by_url(placeOrder) + + + From 22c2fff033454f7d0eb79ae190f67d51b7bf6236 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Tue, 27 Jan 2026 20:18:29 +0800 Subject: [PATCH 046/131] transfer --- aster-finance-futures-api-v3.md | 4 ++-- aster-finance-futures-api-v3_CN.md | 31 ++++++++++++++++++++++++++++++ aster-finance-futures-api.md | 2 +- aster-finance-futures-api_CN.md | 2 +- 4 files changed, 35 insertions(+), 4 deletions(-) diff --git a/aster-finance-futures-api-v3.md b/aster-finance-futures-api-v3.md index a5beebc..dfc07c4 100644 --- a/aster-finance-futures-api-v3.md +++ b/aster-finance-futures-api-v3.md @@ -2316,7 +2316,7 @@ Additional mandatory parameters based on `type`: * The order of returned contents for batch orders is the same as the order of the order list. -## Transfer Between Futures And Spot (USER_DATA) +## Transfer Between Futures And Spot (TRANSFER) > **Response:** @@ -2328,7 +2328,7 @@ Additional mandatory parameters based on `type`: ``` `` -POST /fapi/v3/asset/wallet/transfer (HMAC SHA256) +POST /fapi/v3/asset/wallet/transfer (TRANSFER) `` **Weight:** diff --git a/aster-finance-futures-api-v3_CN.md b/aster-finance-futures-api-v3_CN.md index 97c7447..ef4da52 100644 --- a/aster-finance-futures-api-v3_CN.md +++ b/aster-finance-futures-api-v3_CN.md @@ -2395,6 +2395,37 @@ newOrderRespType | ENUM | NO | "ACK", "RESULT", 默认 "ACK" +## 期货现货互转 (TRANSFER) + +> **响应:** + +```javascript +{ + "tranId": 21841, //交易id + "status": "SUCCESS" //状态 +} +``` + +`` +POST /fapi/v3/asset/wallet/transfer (TRANSFER) +`` + +**权重:** +5 + +**参数:** + + +名称 | 类型 | 是否必需 | 描述 +---------------- | ------- | -------- | ---- +amount | DECIMAL | YES | 数量 +asset | STRING | YES | 资产 +clientTranId | STRING | YES | 交易id +kindType | STRING | YES | 交易类型 +timestamp | LONG | YES | 时间戳 + +* kindType 取值为FUTURE_SPOT(期货转现货),SPOT_FUTURE(现货转期货) + ## 查询订单 (USER_DATA) diff --git a/aster-finance-futures-api.md b/aster-finance-futures-api.md index 21c4833..1d11082 100644 --- a/aster-finance-futures-api.md +++ b/aster-finance-futures-api.md @@ -2464,7 +2464,7 @@ newOrderRespType | ENUM | NO | "ACK", "RESULT", default "ACK" * Batch orders are processed concurrently, and the order of matching is not guaranteed. * The order of returned contents for batch orders is the same as the order of the order list. -## Transfer Between Futures And Spot (USER_DATA) +## Transfer Between Futures And Spot (TRANSFER) > **Response:** diff --git a/aster-finance-futures-api_CN.md b/aster-finance-futures-api_CN.md index 231c9d5..ecc383b 100644 --- a/aster-finance-futures-api_CN.md +++ b/aster-finance-futures-api_CN.md @@ -2372,7 +2372,7 @@ newOrderRespType | ENUM | NO | "ACK", "RESULT", 默认 "ACK" * 批量下单采取并发处理,不保证订单撮合顺序 * 批量下单的返回内容顺序,与订单列表顺序一致 -## 期货现货互转 (TRADE) +## 期货现货互转 (TRANSFER) > **响应:** From 9ee97c471dab012d8b03aadf744aaec2e5ef4586 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Mon, 9 Mar 2026 16:37:13 +0700 Subject: [PATCH 047/131] v3batchdemo --- aster-finance-futures-api-v3.md | 73 ++++++++++------------------ aster-finance-futures-api-v3_CN.md | 76 +++++++++++------------------- 2 files changed, 52 insertions(+), 97 deletions(-) diff --git a/aster-finance-futures-api-v3.md b/aster-finance-futures-api-v3.md index dfc07c4..b282f35 100644 --- a/aster-finance-futures-api-v3.md +++ b/aster-finance-futures-api-v3.md @@ -9,7 +9,6 @@ - [Order Rate Limits](#order-rate-limits) - [API authentication type](#api-authentication-type) - [Authentication signature payload](#authentication-signature-payload) -- [Timing Security](#timing-security) - [Endpoints requiring signature](#endpoints-requiring-signature) - [POST /fapi/v3/order example](#example-of-post-fapiv3order) - [Public Endpoints Info](#public-endpoints-info) @@ -181,16 +180,6 @@ It is strongly recommended to use websocket stream for getting data as much as p * Rejected/unsuccessful orders are not guaranteed to have `X-MBX-ORDER-COUNT-**` headers in the response. * **The order rate limit is counted against each account**. -**Serious trading is about timing.** Networks can be unstable and unreliable, -which can lead to requests taking varying amounts of time to reach the -servers. With `recvWindow`, you can specify that the request must be -processed within a certain number of milliseconds or be rejected by the -server. - - - ## API authentication type * Each API has its own authentication type, which determines what kind of authentication is required when accessing it. @@ -215,29 +204,10 @@ It is recommended to use a small recvWindow of 5000 or less! ## Endpoints requiring signature * Security Type: TRADE, USER_DATA, USER_STREAM, MARKET_DATA -* After converting the API parameters to strings, sort them by their key values in ASCII order to generate the final string. Note: All parameter values must be treated as strings during the signing process. * After generating the string, combine it with the authentication signature parameters user, signer, and nonce, then use Web3’s ABI parameter encoding to generate the bytecode. * After generating the bytecode, use the Keccak algorithm to generate the hash. * Use the private key of **API wallet address** to sign the hash using web3’s ECDSA signature algorithm, generating the final signature. -### Timing Security - -* A `SIGNED` endpoint also requires a parameter, `timestamp`, to be sent which - should be the millisecond timestamp of when the request was created and sent. -* An additional parameter, `recvWindow`, may be sent to specify the number of - milliseconds after `timestamp` the request is valid for. If `recvWindow` - is not sent, **it defaults to 5000**. - -> The logic is as follows: - -```javascript -if (timestamp < (serverTime + 1000) && (serverTime - timestamp) <= recvWindow){ - // process request - } - else { - // reject request - } -``` ## Example of POST /fapi/v3/order @@ -270,6 +240,7 @@ long microsecond = now.getEpochSecond() * 1000000 + now.getNano() / 1000; ```python import time + import requests from eth_account.messages import encode_structured_data from eth_account import Account @@ -302,15 +273,23 @@ headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'PythonApp/1.0' } -order_url = 'https://fapi.asterdex.com/fapi/v3/order' +host = 'https://fapi3.asterdex.com' # config your user and agent info here user = '*' signer = '*' private_key = "*" +place_order = {"url":"/fapi/v3/order","method":"POST","params":{"symbol": "SOLUSDT", "type": "LIMIT", "side": "BUY", + "timeInForce": "GTC", "quantity": "0.1", "price": "71"}} +batch_orders = {"url":"/fapi/v3/batchOrders","method":"POST","params":{"symbol": "SOLUSDT", + "batchOrders":"[{'symbol':'SOLUSDT','type':'LIMIT','side':'BUY','timeInForce':'GTC','quantity':'0.1','price':'71'},{'symbol':'SOLUSDT','type':'LIMIT','side':'BUY','timeInForce':'GTC','quantity':'0.1','price':'71'}]" }} + def get_url(my_dict) -> str: - return '&'.join(f'{key}={str(value)}'for key, value in my_dict.items()) + content = '' + for key, value in my_dict.items(): + content += key + '=' + str(value) + '&' + return content.rstrip('&') _last_ms = 0 _i = 0 @@ -327,29 +306,29 @@ def get_nonce(): return now_ms * 1_000_000 + _i -def send_by_url() : - param = 'symbol=ASTERUSDT&side=BUY&type=LIMIT&quantity=10&price=0.6&timeInForce=GTC' +def send_by_url(api) : + my_dict = api['params'] + url = host + api['url'] + param = get_url(my_dict) param += '&nonce=' + str(get_nonce()) param += '&user=' + user param += '&signer=' + signer + print(param) typed_data['message']['msg'] = param message = encode_structured_data(typed_data) signed = Account.sign_message(message, private_key=private_key) - print(signed.signature.hex()) - - url = order_url + '?' + param + '&signature=' + signed.signature.hex() + url = url + '?' + param + '&signature=' + signed.signature.hex() print(url) res = requests.post(url, headers=headers) print(res.text) -def send_by_body() : - my_dict = {"symbol": "ASTERUSDT", "type": "LIMIT", "side": "BUY", - "timeInForce": "GTC", "quantity": "10", "price": "0.6"} - +def send_by_body(api) : + my_dict = api['params'] + url = host +api['url'] my_dict['nonce'] = str(get_nonce()) my_dict['user'] = user my_dict['signer'] = signer @@ -364,13 +343,15 @@ def send_by_body() : my_dict['signature'] = signed.signature.hex() print(my_dict) - res = requests.post(order_url, data=my_dict, headers=headers) + res = requests.post(url, data=my_dict, headers=headers) print(res.text) if __name__ == '__main__': - send_by_url() - # send_by_body() + # send_by_url(place_order) + send_by_url(batch_orders) + # send_by_body(place_order) + # send_by_body(batch_orders) ``` ## Public Endpoints Info @@ -2056,8 +2037,6 @@ Change user's position mode (Hedge Mode or One-way Mode ) on ***EVERY symbol*** | Name | Type | Mandatory | Description | | ---------------- | ------ | --------- | ----------------------------------------- | | dualSidePosition | STRING | YES | "true": Hedge Mode; "false": One-way Mode | -| recvWindow | LONG | NO | | -| timestamp | LONG | YES | | ## Get Current Position Mode(USER_DATA) @@ -2080,8 +2059,6 @@ Get user's position mode (Hedge Mode or One-way Mode ) on ***EVERY symbol*** | Name | Type | Mandatory | Description | | ---------- | ---- | --------- | ----------- | -| recvWindow | LONG | NO | | -| timestamp | LONG | YES | | ## Change Multi-Assets Mode (TRADE) diff --git a/aster-finance-futures-api-v3_CN.md b/aster-finance-futures-api-v3_CN.md index ef4da52..529e0ca 100644 --- a/aster-finance-futures-api-v3_CN.md +++ b/aster-finance-futures-api-v3_CN.md @@ -9,7 +9,6 @@ - [接口鉴权类型](#接口鉴权类型) - [鉴权签名体](#鉴权签名体) - [需要签名的接口](#需要签名的接口) - - [时间同步安全](#时间同步安全) - [POST /fapi/v3/order 的示例](#post-fapiv3order-的示例) - [公开API参数](#公开api参数) - [术语解释](#术语解释) @@ -171,15 +170,7 @@ ### 下单频率限制 * 每个下单请求回报将包含一个`X-MBX-ORDER-COUNT-(intervalNum)(intervalLetter)`的头,其中包含当前账户已用的下单限制数量。 * 被拒绝或不成功的下单并不保证回报中包含以上头内容。 -* **下单频率限制是基于每个账户计数的。** - -**关于交易时效性** -互联网状况并不100%可靠,不可完全依赖,因此你的程序本地到服务器的时延会有抖动. -这是我们设置`recvWindow`的目的所在,如果你从事高频交易,对交易时效性有较高的要求,可以灵活设置recvWindow以达到你的要求。 - - +* **下单频率限制是基于每个账户计数的。**> ## 接口鉴权类型 * 每个接口都有自己的鉴权类型,鉴权类型决定了访问时应当进行何种鉴权 @@ -206,21 +197,7 @@ signature | 签名 * 接口参数转字符串后按照key值ASCII编码后生成的字符串 请注意所有参数取值请以字符串的方式进行签名 * 生成字符串后在与鉴权签名参数的user,signer,nonce使用web3的abi参数编码生成字节码 * 生成字节码后使用Keccak算法生成hash -* 使用派生地址的私钥用web3的ecdsa签名算法对该hash进行签名生成signature - -### 时间同步安全 -* 签名接口均需要传递`timestamp`参数,其值应当是请求发送时刻的unix时间戳(毫秒) -* 服务器收到请求时会判断请求中的时间戳,如果是5000毫秒之前发出的,则请求会被认为无效。这个时间窗口值可以通过发送可选参数`recvWindow`来自定义。 - -> 逻辑伪代码: - - ```javascript - if (timestamp < (serverTime + 1000) && (serverTime - timestamp) <= recvWindow) { - // process request - } else { - // reject request - } - ``` +* 使用派生地址的私钥用web3的ecdsa签名算法对该hash进行签名生成signature` ## POST /fapi/v3/order 的示例 @@ -252,6 +229,7 @@ long microsecond = now.getEpochSecond() * 1000000 + now.getNano() / 1000; ```python import time + import requests from eth_account.messages import encode_structured_data from eth_account import Account @@ -284,15 +262,23 @@ headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'PythonApp/1.0' } -order_url = 'https://fapi.asterdex.com/fapi/v3/order' +host = 'https://fapi3.asterdex.com' # config your user and agent info here user = '*' signer = '*' private_key = "*" +place_order = {"url":"/fapi/v3/order","method":"POST","params":{"symbol": "SOLUSDT", "type": "LIMIT", "side": "BUY", + "timeInForce": "GTC", "quantity": "0.1", "price": "71"}} +batch_orders = {"url":"/fapi/v3/batchOrders","method":"POST","params":{"symbol": "SOLUSDT", + "batchOrders":"[{'symbol':'SOLUSDT','type':'LIMIT','side':'BUY','timeInForce':'GTC','quantity':'0.1','price':'71'},{'symbol':'SOLUSDT','type':'LIMIT','side':'BUY','timeInForce':'GTC','quantity':'0.1','price':'71'}]" }} + def get_url(my_dict) -> str: - return '&'.join(f'{key}={str(value)}'for key, value in my_dict.items()) + content = '' + for key, value in my_dict.items(): + content += key + '=' + str(value) + '&' + return content.rstrip('&') _last_ms = 0 _i = 0 @@ -309,29 +295,29 @@ def get_nonce(): return now_ms * 1_000_000 + _i -def send_by_url() : - param = 'symbol=ASTERUSDT&side=BUY&type=LIMIT&quantity=10&price=0.6&timeInForce=GTC' +def send_by_url(api) : + my_dict = api['params'] + url = host + api['url'] + param = get_url(my_dict) param += '&nonce=' + str(get_nonce()) param += '&user=' + user param += '&signer=' + signer + print(param) typed_data['message']['msg'] = param message = encode_structured_data(typed_data) signed = Account.sign_message(message, private_key=private_key) - print(signed.signature.hex()) - - url = order_url + '?' + param + '&signature=' + signed.signature.hex() + url = url + '?' + param + '&signature=' + signed.signature.hex() print(url) res = requests.post(url, headers=headers) print(res.text) -def send_by_body() : - my_dict = {"symbol": "ASTERUSDT", "type": "LIMIT", "side": "BUY", - "timeInForce": "GTC", "quantity": "10", "price": "0.6"} - +def send_by_body(api) : + my_dict = api['params'] + url = host +api['url'] my_dict['nonce'] = str(get_nonce()) my_dict['user'] = user my_dict['signer'] = signer @@ -346,13 +332,15 @@ def send_by_body() : my_dict['signature'] = signed.signature.hex() print(my_dict) - res = requests.post(order_url, data=my_dict, headers=headers) + res = requests.post(url, data=my_dict, headers=headers) print(res.text) if __name__ == '__main__': - send_by_url() - # send_by_body() + # send_by_url(place_order) + send_by_url(batch_orders) + # send_by_body(place_order) + # send_by_body(batch_orders) ``` ## 公开API参数 @@ -2090,8 +2078,6 @@ POST /fapi/v3/positionSide/dual (HMAC SHA256) 名称 | 类型 | 是否必需 | 描述 ---------- | ------ | -------- | ----------------- dualSidePosition | STRING | YES | "true": 双向持仓模式;"false": 单向持仓模式 -recvWindow | LONG | NO | -timestamp | LONG | YES | @@ -2114,14 +2100,6 @@ GET /fapi/v3/positionSide/dual (HMAC SHA256) **权重:** 30 -**参数:** - - 名称 | 类型 | 是否必需 | 描述 ----------- | ------ | -------- | ----------------- -recvWindow | LONG | NO | -timestamp | LONG | YES | - - ## 更改联合保证金模式(TRADE) > **响应:** From d5a0c89f2bc4d41c68c4815323ab7738e3c0701f Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Tue, 10 Mar 2026 11:56:04 +0700 Subject: [PATCH 048/131] removesymbol --- aster-finance-futures-api-v3.md | 2 +- aster-finance-futures-api-v3_CN.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/aster-finance-futures-api-v3.md b/aster-finance-futures-api-v3.md index b282f35..4a90604 100644 --- a/aster-finance-futures-api-v3.md +++ b/aster-finance-futures-api-v3.md @@ -282,7 +282,7 @@ private_key = "*" place_order = {"url":"/fapi/v3/order","method":"POST","params":{"symbol": "SOLUSDT", "type": "LIMIT", "side": "BUY", "timeInForce": "GTC", "quantity": "0.1", "price": "71"}} -batch_orders = {"url":"/fapi/v3/batchOrders","method":"POST","params":{"symbol": "SOLUSDT", +batch_orders = {"url":"/fapi/v3/batchOrders","method":"POST","params":{ "batchOrders":"[{'symbol':'SOLUSDT','type':'LIMIT','side':'BUY','timeInForce':'GTC','quantity':'0.1','price':'71'},{'symbol':'SOLUSDT','type':'LIMIT','side':'BUY','timeInForce':'GTC','quantity':'0.1','price':'71'}]" }} def get_url(my_dict) -> str: diff --git a/aster-finance-futures-api-v3_CN.md b/aster-finance-futures-api-v3_CN.md index 529e0ca..8445b74 100644 --- a/aster-finance-futures-api-v3_CN.md +++ b/aster-finance-futures-api-v3_CN.md @@ -271,7 +271,7 @@ private_key = "*" place_order = {"url":"/fapi/v3/order","method":"POST","params":{"symbol": "SOLUSDT", "type": "LIMIT", "side": "BUY", "timeInForce": "GTC", "quantity": "0.1", "price": "71"}} -batch_orders = {"url":"/fapi/v3/batchOrders","method":"POST","params":{"symbol": "SOLUSDT", +batch_orders = {"url":"/fapi/v3/batchOrders","method":"POST","params":{ "batchOrders":"[{'symbol':'SOLUSDT','type':'LIMIT','side':'BUY','timeInForce':'GTC','quantity':'0.1','price':'71'},{'symbol':'SOLUSDT','type':'LIMIT','side':'BUY','timeInForce':'GTC','quantity':'0.1','price':'71'}]" }} def get_url(my_dict) -> str: From 6191fe5aa6015f5eadd9426794d027823b726c0c Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Wed, 11 Mar 2026 22:34:52 +0700 Subject: [PATCH 049/131] gitbook --- Difference between V1 and V3 interfaces.md | 108 +++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 Difference between V1 and V3 interfaces.md diff --git a/Difference between V1 and V3 interfaces.md b/Difference between V1 and V3 interfaces.md new file mode 100644 index 0000000..dc8176f --- /dev/null +++ b/Difference between V1 and V3 interfaces.md @@ -0,0 +1,108 @@ +# Aster API V1 vs V3 + +This page provides a quick comparison between Aster `V1` and `V3`, focusing on authentication, endpoint structure, capability coverage, and the most important architectural value behind V3. + +> **Key takeaways** +> +> 1. Authentication moves from `API Key + HMAC` to `API Wallet / Agent + Web3-style signing` +> 2. The futures structure is upgraded on top of `Aster L1`, giving `V3` stronger `Take Order` performance while consolidating the main paths into `/fapi/v3/*` + +--- + +## Overview + +### How To Understand It + +- `V1` is the standard API Key model. +- `V3` introduces the API Wallet / Agent model, and its authentication flow is closer to on-chain signing. +- `V3` futures are built on top of `Aster L1`, which gives stronger `Take Order` performance. +- `V3` goes through the blockchain, which makes historical trades traceable in the future, with stronger security and visibility. +- `V3` uses `nonce` to prevent replay attacks, making requests more secure. +- `V3` supports `Noop`, which can cancel orders faster. +- Most business capabilities still exist in both versions. +- The biggest change is not order semantics, but the authentication layer. + +--- + +## Authentication + +### V1 + +In `V1`, authentication follows the typical `API Key + Secret` model: + +- Send `X-MBX-APIKEY` in the request header +- Include `timestamp` in request parameters +- Optionally include `recvWindow` +- Generate `signature` using `HMAC SHA256` + +The signing payload is usually based on request parameters, which means `query string + request body`. + +### V3 + +In `V3`, authentication is no longer centered only around `apiSecret`. + +In addition to business parameters, requests also include: + +- `user`: main account wallet address +- `signer`: API wallet address +- `nonce`: microsecond timestamp +- `signature`: signed by the API wallet private key +- `timestamp` + +The signing flow can be understood as: + +1. Convert all business parameters into strings +2. Sort them by ASCII key order +3. Encode them together with `user`, `signer`, and `nonce` +4. Generate a Keccak hash +5. Sign it with ECDSA using the API wallet private key + +`nonce` also plays an important role in V3, because it prevents replay attacks and makes requests more secure. + +> **Why this matters** +> +> `V1` is well suited to the standard API Key integration model. +> `V3` is built around signer identity and is better aligned with the Aster L1 architecture. + +### Core Value Of V3 + +- `V3` futures are built on top of `Aster L1`, giving stronger `Take Order` performance. +- `V3` goes through the blockchain, so historical trades can be traced in the future, with stronger security and visibility. +- `V3` uses `nonce` to prevent replay and make requests more secure. +- `V3` supports `Noop`, which can cancel orders faster. + +## Migration Notes + +A practical migration order is: + +1. Build a dedicated signing module first +2. Centralize the authentication context: + - `user` + - `signer` + - `signerPrivateKey` + - `timestamp` + - `nonce` +3. Get one simple order or query flow working first +4. Validate the signing logic with a simple trade flow +5. Then move to batch and fund-related operations + +### Common Mistakes + +The most common issues during V3 migration are: + +- incorrect parameter sorting +- mixing milliseconds and microseconds +- forgetting `user` or `signer` +- assuming V3 is still plain HMAC +- relying too much on endpoint titles instead of the authentication section + +--- + +- `V1` is fundamentally the standard `API Key` model. +- `V3` introduces the `API Wallet / Agent` model, and its authentication flow is closer to on-chain signing. +- The two versions remain broadly aligned in business capability, with the main difference concentrated in the authentication layer. +- On futures, `V3` is built on top of `Aster L1`, which gives it stronger `Take Order` performance and a more unified endpoint structure. +- `V3` goes through the blockchain, making future historical trade traceability possible with stronger security and visibility. +- `V3` uses `nonce` to prevent replay and improve request security. +- `V3` supports `Noop`, which can cancel orders faster. +- Fund-related APIs still require extra attention because they often involve additional wallet-based signing. From 253aeaeb1fd386050fa693b37f962125adb87cb4 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Thu, 12 Mar 2026 11:30:22 +0700 Subject: [PATCH 050/131] spotv3 --- aster-finance-futures-api-v3.md | 50 +- aster-finance-futures-api-v3_CN.md | 58 +- aster-finance-spot-api-v3.md | 2582 +++++++++++++++++++++++++ aster-finance-spot-api.md | 3 - aster-finance-spot-api_CN-v3.md | 2804 ++++++++++++++++++++++++++++ aster-finance-spot-api_CN.md | 4 +- 6 files changed, 5453 insertions(+), 48 deletions(-) create mode 100644 aster-finance-spot-api-v3.md create mode 100644 aster-finance-spot-api_CN-v3.md diff --git a/aster-finance-futures-api-v3.md b/aster-finance-futures-api-v3.md index 4a90604..62d62f6 100644 --- a/aster-finance-futures-api-v3.md +++ b/aster-finance-futures-api-v3.md @@ -24,6 +24,7 @@ - [PERCENT_PRICE](#percent_price) - [MIN_NOTIONAL](#min_notional) - [Market Data Endpoints](#market-data-endpoints) + - [Noop](#noop) - [Test Connectivity](#test-connectivity) - [Check Server Time](#check-server-time) - [Exchange Information](#exchange-information) @@ -240,6 +241,7 @@ long microsecond = now.getEpochSecond() * 1000000 + now.getNano() / 1000; ```python import time +import urllib import requests from eth_account.messages import encode_structured_data @@ -280,16 +282,10 @@ user = '*' signer = '*' private_key = "*" -place_order = {"url":"/fapi/v3/order","method":"POST","params":{"symbol": "SOLUSDT", "type": "LIMIT", "side": "BUY", - "timeInForce": "GTC", "quantity": "0.1", "price": "71"}} +place_order = {"url":"/fapi/v3/order","method":"POST","params":{"symbol": "ASTERUSDT", "type": "LIMIT", "side": "BUY", + "timeInForce": "GTC", "quantity": "20", "price": "0.5"}} batch_orders = {"url":"/fapi/v3/batchOrders","method":"POST","params":{ - "batchOrders":"[{'symbol':'SOLUSDT','type':'LIMIT','side':'BUY','timeInForce':'GTC','quantity':'0.1','price':'71'},{'symbol':'SOLUSDT','type':'LIMIT','side':'BUY','timeInForce':'GTC','quantity':'0.1','price':'71'}]" }} - -def get_url(my_dict) -> str: - content = '' - for key, value in my_dict.items(): - content += key + '=' + str(value) + '&' - return content.rstrip('&') + "batchOrders":"[{'symbol':'ASTERUSDT','type':'LIMIT','side':'BUY','timeInForce':'GTC','quantity':'20','price':'0.5'},{'symbol':'ASTERUSDT','type':'LIMIT','side':'BUY','timeInForce':'GTC','quantity':'20','price':'0.5'}]" }} _last_ms = 0 _i = 0 @@ -310,10 +306,11 @@ def send_by_url(api) : my_dict = api['params'] url = host + api['url'] - param = get_url(my_dict) - param += '&nonce=' + str(get_nonce()) - param += '&user=' + user - param += '&signer=' + signer + my_dict['nonce'] = str(get_nonce()) + my_dict['user'] = user + my_dict['signer'] = signer + + param = urllib.parse.urlencode(my_dict) print(param) typed_data['message']['msg'] = param @@ -333,8 +330,8 @@ def send_by_body(api) : my_dict['user'] = user my_dict['signer'] = signer - content = get_url(my_dict) - typed_data['message']['msg'] = content + param = urllib.parse.urlencode(my_dict) + typed_data['message']['msg'] = param message = encode_structured_data(typed_data) signed = Account.sign_message(message, private_key=private_key) @@ -348,8 +345,8 @@ def send_by_body(api) : print(res.text) if __name__ == '__main__': - # send_by_url(place_order) - send_by_url(batch_orders) + send_by_url(place_order) + # send_by_url(batch_orders) # send_by_body(place_order) # send_by_body(batch_orders) ``` @@ -627,6 +624,25 @@ Since `MARKET` orders have no price, the mark price is used. # Market Data Endpoints +## Noop + +> **Response:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +``POST /fapi/v3/noop`` + +By using this request, it is possible to efficiently cancel previously sent transactions that are still in the queue and have not completed the on chain operation (Nonce should be equal to this request,no guarantee of success +) + +**Weight:** +1 + ## Test Connectivity > **Response:** diff --git a/aster-finance-futures-api-v3_CN.md b/aster-finance-futures-api-v3_CN.md index 8445b74..e4e24e1 100644 --- a/aster-finance-futures-api-v3_CN.md +++ b/aster-finance-futures-api-v3_CN.md @@ -23,6 +23,7 @@ - [PERCENT_PRICE 价格振幅过滤器](#percent_price-价格振幅过滤器) - [MIN_NOTIONAL 最小名义价值](#min_notional-最小名义价值) - [行情接口](#行情接口) + - [Noop](#noop) - [测试服务器连通性 PING](#测试服务器连通性-ping) - [获取服务器时间](#获取服务器时间) - [获取交易规则和交易对](#获取交易规则和交易对) @@ -192,16 +193,8 @@ signer | API钱包地址 nonce | 当前时间戳,单位为微秒 signature | 签名 -## 需要签名的接口 -* TRADE 与 USER_DATA,USER_STREAM,MARKET_DATA -* 接口参数转字符串后按照key值ASCII编码后生成的字符串 请注意所有参数取值请以字符串的方式进行签名 -* 生成字符串后在与鉴权签名参数的user,signer,nonce使用web3的abi参数编码生成字节码 -* 生成字节码后使用Keccak算法生成hash -* 使用派生地址的私钥用web3的ecdsa签名算法对该hash进行签名生成signature` - ## POST /fapi/v3/order 的示例 -#### 所有参数均通过from body请求(Python 3.9.6) #### 示例 : 以下参数为api注册信息,user,signer,privateKey仅供示范(privateKey为signer的私钥) @@ -229,6 +222,7 @@ long microsecond = now.getEpochSecond() * 1000000 + now.getNano() / 1000; ```python import time +import urllib import requests from eth_account.messages import encode_structured_data @@ -269,16 +263,10 @@ user = '*' signer = '*' private_key = "*" -place_order = {"url":"/fapi/v3/order","method":"POST","params":{"symbol": "SOLUSDT", "type": "LIMIT", "side": "BUY", - "timeInForce": "GTC", "quantity": "0.1", "price": "71"}} +place_order = {"url":"/fapi/v3/order","method":"POST","params":{"symbol": "ASTERUSDT", "type": "LIMIT", "side": "BUY", + "timeInForce": "GTC", "quantity": "20", "price": "0.5"}} batch_orders = {"url":"/fapi/v3/batchOrders","method":"POST","params":{ - "batchOrders":"[{'symbol':'SOLUSDT','type':'LIMIT','side':'BUY','timeInForce':'GTC','quantity':'0.1','price':'71'},{'symbol':'SOLUSDT','type':'LIMIT','side':'BUY','timeInForce':'GTC','quantity':'0.1','price':'71'}]" }} - -def get_url(my_dict) -> str: - content = '' - for key, value in my_dict.items(): - content += key + '=' + str(value) + '&' - return content.rstrip('&') + "batchOrders":"[{'symbol':'ASTERUSDT','type':'LIMIT','side':'BUY','timeInForce':'GTC','quantity':'20','price':'0.5'},{'symbol':'ASTERUSDT','type':'LIMIT','side':'BUY','timeInForce':'GTC','quantity':'20','price':'0.5'}]" }} _last_ms = 0 _i = 0 @@ -299,10 +287,11 @@ def send_by_url(api) : my_dict = api['params'] url = host + api['url'] - param = get_url(my_dict) - param += '&nonce=' + str(get_nonce()) - param += '&user=' + user - param += '&signer=' + signer + my_dict['nonce'] = str(get_nonce()) + my_dict['user'] = user + my_dict['signer'] = signer + + param = urllib.parse.urlencode(my_dict) print(param) typed_data['message']['msg'] = param @@ -322,8 +311,8 @@ def send_by_body(api) : my_dict['user'] = user my_dict['signer'] = signer - content = get_url(my_dict) - typed_data['message']['msg'] = content + param = urllib.parse.urlencode(my_dict) + typed_data['message']['msg'] = param message = encode_structured_data(typed_data) signed = Account.sign_message(message, private_key=private_key) @@ -337,8 +326,8 @@ def send_by_body(api) : print(res.text) if __name__ == '__main__': - # send_by_url(place_order) - send_by_url(batch_orders) + send_by_url(place_order) + # send_by_url(batch_orders) # send_by_body(place_order) # send_by_body(batch_orders) ``` @@ -611,6 +600,25 @@ MIN_NOTIONAL过滤器定义了交易对订单所允许的最小名义价值(成 # 行情接口 + +## Noop + +> **Response:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +``POST /fapi/v3/noop`` + +通过此请求,可以高效取消已发送但仍在队列中且尚未完成链上操作的交易(Nonce需与该请求一致,不保证成功) + +**Weight:** +1 + ## 测试服务器连通性 PING `` GET /fapi/v3/ping diff --git a/aster-finance-spot-api-v3.md b/aster-finance-spot-api-v3.md new file mode 100644 index 0000000..9b001b9 --- /dev/null +++ b/aster-finance-spot-api-v3.md @@ -0,0 +1,2582 @@ +# Spot API Overview + +* This document lists the base URL for the API endpoints: [**https://sapi.asterdex.com**](https://sapi.asterdex.com) +* All API responses are in JSON format. +* All times and timestamps are in UNIX time, in **milliseconds**. + +## API Key settings + +* Many endpoints require an API Key to access. +* When setting the API Key, for security reasons it is recommended to set an IP access whitelist. +* **Never reveal your API key/secret to anyone.** + +If an API Key is accidentally exposed, immediately delete that Key and generate a new one. + +### Attention +* TESTUSDT or any other symbols starting with TEST are symbols used for Aster’s INTERNAL TESTING ONLY. Please DO NOT trade on these symbols starting with TEST. Aster does not hold any accountability for loss of funds due to trading on these symbols. However, if you run into issues, you may contact support about this any time, we will try to help you recover your funds. + +### HTTP return codes + +* HTTP `4XX` status codes are used to indicate errors in the request content, behavior, or format. The problem lies with the requester. +* HTTP `403` status code indicates a violation of WAF restrictions (Web Application Firewall). +* HTTP `429` error code indicates a warning that the access frequency limit has been exceeded and the IP is about to be blocked. +* HTTP `418` indicates that after receiving a 429 you continued to access, so the IP has been blocked. +* HTTP `5XX` error codes are used to indicate issues on the Aster service side. + +### API error codes + +* When using the endpoint `/api/v3`, any endpoint may throw exceptions; + +The API error codes are returned in the following format: + +```javascript +{ + "code": -1121, + "msg": "Invalid symbol." +} +``` + +### Basic information about the endpoint + +* Endpoints with the `GET` method must send parameters in the `query string`. +* For `POST`, `PUT`, and `DELETE` endpoints, parameters can be sent in the `query string` with content type `application/x-www-form-urlencoded` , or in the `request body`. +* The order of parameters is not required. + +--- + +## Access restrictions + +### Basic information on access restrictions + +* The `rateLimits` array in `/api/v3/exchangeInfo` contains objects related to REQUEST\_WEIGHT and ORDERS rate limits for trading. These are further defined in the `enum definitions` section under `rateLimitType`. +* A 429 will be returned when any of the rate limits are violated. + +### IP access limits + +* Each request will include a header named `X-MBX-USED-WEIGHT-(intervalNum)(intervalLetter)` that contains the used weight of all requests from the current IP. +* Each endpoint has a corresponding weight, and some endpoints may have different weights depending on their parameters. The more resources an endpoint consumes, the higher its weight will be. +* Upon receiving a 429, you are responsible for stopping requests and must not abuse the API. +* **If you continue to violate access limits after receiving a 429, your IP will be banned and you will receive a 418 error code.** +* Repeated violations of the limits will result in progressively longer bans, **from a minimum of 2 minutes up to a maximum of 3 days**. +* The `Retry-After` header will be sent with responses bearing 418 or 429, and will give the wait time **in seconds** (if 429\) to avoid the ban, or, if 418, until the ban ends. +* **Access restrictions are based on IP, not API Key** + +You are advised to use WebSocket messages to obtain the corresponding data as much as possible to reduce the load and rate-limit pressure from requests. + +### Order rate limits + +* Each successful order response will include a `X-MBX-ORDER-COUNT-(intervalNum)(intervalLetter)` header containing the number of order limit units currently used by the account. +* When the number of orders exceeds the limit, you will receive a response with status 429 but without the `Retry-After` header. Please check the order rate limits in `GET api/v3/exchangeInfo` (rateLimitType \= ORDERS) and wait until the ban period ends. +* Rejected or unsuccessful orders are not guaranteed to include the above header in the response. +* **Order placement rate limits are counted per account.** + +### WebSocket connection limits + +* The WebSocket server accepts a maximum of 5 messages per second. Messages include: + * PING frame + * PONG frame + * Messages in JSON format, such as subscribe and unsubscribe. +* If a user sends messages that exceed the limit, the connection will be terminated. IPs that are repeatedly disconnected may be blocked by the server. +* A single connection can subscribe to up to **1024** Streams. + +--- + +## API authentication types + +* Each API has its own authentication type, which determines what kind of authentication should be performed when accessing it. +* The authentication type will be indicated next to each endpoint name in this document; if not specifically stated, it defaults to `NONE`. + +| Security Type | Description | +| ------------- | ----------------------------------------- | +| NONE | API that does not require authentication | +| SPOT_TRADE | A valid signer and signature are required | +| USER_DATA | A valid signer and signature are required | +| USER_STREAM | A valid signer and signature are required | +| MARKET_DATA | A valid signer and signature are required | + +--- + +## SIGNED (TRADE AND USER\_DATA) Endpoint security + +* After generating the string, combine it with the authentication signature parameters user, signer, and nonce, then use Web3’s ABI parameter encoding to generate the bytecode. +* After generating the bytecode, use the Keccak algorithm to generate the hash. +* Use the private key of **API wallet address** to sign the hash using web3’s ECDSA signature algorithm, generating the final signature. + + +## Example of POST /api/v3/order + + +#### The following parameters are API registration details. The values for user, signer, and privateKey are for demonstration purposes only (the privateKey corresponds to the signer). + +| Key | Value | Desc +| ---------- | ------------------------------------------------------------------ | ---------- | +| user | 0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e |Login wallet address | +| signer | 0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0 |[Click Here](https://www.asterdex.com/en/api-wallet) | +| privateKey | 0x4fd0a42218f3eae43a6ce26d22544e986139a01e5b34a62db53757ffca81bae1 |[Click Here](https://www.asterdex.com/en/api-wallet) | + +#### The nonce parameter is the current system time in microseconds. If it exceeds the system time or lags behind it by more than 10 seconds, the request is considered invalid. +```python +#python +nonce = math.trunc(time.time()*1000000) +print(nonce) +#1748310859508867 +``` +```java +#python +//java +Instant now = Instant.now(); +long microsecond = now.getEpochSecond() * 1000000 + now.getNano() / 1000; +``` + +#### Example: Post an order (using Python as an example). + + +```python +import time +import urllib + +import requests +from eth_account.messages import encode_structured_data +from eth_account import Account + +typed_data = { + "types": { + "EIP712Domain": [ + {"name": "name", "type": "string"}, + {"name": "version", "type": "string"}, + {"name": "chainId", "type": "uint256"}, + {"name": "verifyingContract", "type": "address"} + ], + "Message": [ + { "name": "msg", "type": "string" } + ] + }, + "primaryType": "Message", + "domain": { + "name": "AsterSignTransaction", + "version": "1", + "chainId": 1666, + "verifyingContract": "0x0000000000000000000000000000000000000000" + }, + "message": { + "msg": "$msg" + } +} + +headers = { + 'Content-Type': 'application/x-www-form-urlencoded', + 'User-Agent': 'PythonApp/1.0' +} +host = 'https://sapi.asterdex.com' + +# config your user and agent info here +user = '*' +signer = '*' +private_key = "*" + +place_order = {"url":"/api/v3/order","method":"POST","params":{"symbol": "ASTERUSDT", "type": "LIMIT", "side": "BUY", + "timeInForce": "GTC", "quantity": "100", "price": "0.4"}} +_last_ms = 0 +_i = 0 + +def get_nonce(): + global _last_ms, _i + now_ms = int(time.time()) + + if now_ms == _last_ms: + _i += 1 + else: + _last_ms = now_ms + _i = 0 + + return now_ms * 1_000_000 + _i + +def send_by_url(api) : + my_dict = api['params'] + url = host + api['url'] + + my_dict['nonce'] = str(get_nonce()) + my_dict['user'] = user + my_dict['signer'] = signer + + param = urllib.parse.urlencode(my_dict) + print(param) + typed_data['message']['msg'] = param + message = encode_structured_data(typed_data) + signed = Account.sign_message(message, private_key=private_key) + + url = url + '?' + param + '&signature=' + signed.signature.hex() + print(url) + res = requests.post(url, headers=headers) + + print(res.text) + +def send_by_body(api) : + my_dict = api['params'] + url = host +api['url'] + my_dict['nonce'] = str(get_nonce()) + my_dict['user'] = user + my_dict['signer'] = signer + + param = urllib.parse.urlencode(my_dict) + typed_data['message']['msg'] = param + message = encode_structured_data(typed_data) + + signed = Account.sign_message(message, private_key=private_key) + print(signed.signature.hex()) + + my_dict['signature'] = signed.signature.hex() + + print(my_dict) + res = requests.post(url, data=my_dict, headers=headers) + + print(res.text) + +if __name__ == '__main__': + send_by_url(place_order) + # send_by_body(place_order) + +``` + +## Public API parameters + +### Terminology + +The terminology in this section applies throughout the document. New users are encouraged to read it carefully for better understanding. + +* `base asset` refers to the asset being traded in a trading pair, i.e., the asset name written first; for example, in `BTCUSDT`, `BTC` is the `base asset`. +* `quote asset` refers to the pricing asset of a trading pair, i.e., the asset name written at the latter part; for example, in `BTCUSDT`, `USDT` is the `quote asset`. + +### Enumeration definition + +**Trading pair status (status):** + +* TRADING \- after trade + +**Trading pair type:** + +* SPOT \- spot + +**Order status (status):** + +| Status | Description | +| :---- | :---- | +| NEW | Order accepted by the matching engine | +| PARTIALLY\_FILLED | Part of the order was filled | +| FILLED | The order was fully filled | +| CANCELED | The user canceled the order | +| REJECTED | The order was not accepted by the matching engine and was not processed | +| EXPIRED | Order canceled by the trading engine, for example: Limit FOK order not filled, Market order not fully filled, orders canceled during exchange maintenance | + +**Order types (orderTypes, type):** + +* LIMIT \- Limit Order +* MARKET \- Market Order +* STOP \- Limit Stop Order +* TAKE\_PROFIT \- Limit Take-Profit Order +* STOP\_MARKET \- Market Stop Order +* TAKE\_PROFIT\_MARKET \- Market Take-Profit Order + +**Order response type (newOrderRespType):** + +* ACK +* RESULT +* FULL + +**Order direction (direction side):** + +* BUY \- Buy +* SELL \- Sell + +**Valid types (timeInForce):** + +This defines how long an order can remain valid before expiring. + +| Status | Description | +| :---- | :---- | +| GTC (Good ‘Til Canceled) | The order remains active until it is fully executed or manually canceled. | +| IOC (Immediate or Cancel) | The order will execute immediately for any amount available. Any unfilled portion is automatically canceled. | +| FOK (Fill or Kill) | The order must be fully executed immediately. If it cannot be filled in full, it is canceled right away. | +| GTX (Good till crossing, Post only) | The post-only limit order will only be placed if it can be added as a maker order and not as a taker order. | + +**K-line interval:** + +m (minutes), h (hours), d (days), w (weeks), M (months) + +* 1m +* 3m +* 5m +* 15m +* 30m +* 1h +* 2h +* 4h +* 6h +* 8h +* 12h +* 1d +* 3d +* 1w +* 1M + +**Rate limit type (rateLimitType)** + +REQUEST\_WEIGHT + +```json + { + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200 + } +``` + +ORDERS + +```json + { + "rateLimitType": "ORDERS", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 100 + } +``` + +* REQUEST\_WEIGHT \- The maximum sum of request weights allowed within a unit time + +* ORDERS \- Order placement frequency limit per time unit + +**Interval restriction (interval)** + +* MINUTE \- Minute + +--- + +## Filters + +Filters, i.e. Filter, define a set of trading rules. There are two types: filters for trading pairs `symbol filters`, and filters for the entire exchange `exchange filters` (not supported yet) + +### Trading pair filters + +#### PRICE\_FILTER Price filter + +**Format in the /exchangeInfo response:** + +```javascript + { + "minPrice": "556.72", + "maxPrice": "4529764", + "filterType": "PRICE_FILTER", + "tickSize": "0.01"   + } +``` + +The `Price Filter` checks the validity of the `price` parameter in an order. It consists of the following three parts: + +* `minPrice` defines the minimum allowed value for `price`/`stopPrice`. +* `maxPrice` defines the maximum allowed value for `price`/`stopPrice`. +* `tickSize` defines the step interval for `price`/`stopPrice`, meaning the price must equal minPrice plus an integer multiple of tickSize. + +Each of the above items can be 0; when 0 it means that item is not constrained. + +The logical pseudocode is as follows: + +* `price` \>= `minPrice` +* `price` \<= `maxPrice` +* (`price`\-`minPrice`) % `tickSize` \== 0 + +#### PERCENT\_PRICE price amplitude filter + +**Format in the /exchangeInfo response:** + +```javascript + { + "multiplierDown": "0.9500", + "multiplierUp": "1.0500", + "multiplierDecimal": "4", + "filterType": "PERCENT_PRICE" +  } +``` + +The `PERCENT_PRICE` filter defines the valid range of prices based on the index price. + +For the "price percentage" to apply, the "price" must meet the following conditions: + +* `price` \<=`indexPrice` \*`multiplierUp` +* `price`\> \=`indexPrice` \*`multiplierDown` + +#### LOT\_SIZE order size + +**Format in the /exchangeInfo response:** + +```javascript + { + "stepSize": "0.00100000", +   "filterType": "LOT_SIZE", + "maxQty": "100000.00000000", +   "minQty": "0.00100000" + } +``` + +Lots is an auction term. The `LOT_SIZE` filter validates the `quantity` (i.e., the amount) parameter in orders. It consists of three parts: + +* `minQty` indicates the minimum allowed value for `quantity`. +* `maxQty` denotes the maximum allowed value for `quantity`. +* `stepSize` denotes the allowed step increment for `quantity`. + +The logical pseudocode is as follows: + +* `quantity` \>= `minQty` +* `quantity` \<= `maxQty` +* (`quantity`\-`minQty`) % `stepSize` \== 0 + +#### MARKET\_LOT\_SIZE \- Market order size + +\***/exchangeInfo response format:** + +```javascript + { + "stepSize": "0.00100000", +   "filterType": "MARKET_LOT_SIZE" + "maxQty": "100000.00000000", + "minQty": "0.00100000" + } +``` + +The `MARKET_LOT_SIZE` filter defines the `quantity` (i.e., the "lots" in an auction) rules for `MARKET` orders on a trading pair. There are three parts: + +* `minQty` defines the minimum allowed `quantity`. +* `maxQty` defines the maximum allowed quantity. +* `stepSize` defines the increments by which the quantity can be increased or decreased. + +In order to comply with the `market lot size`, the `quantity` must satisfy the following conditions: + +* `quantity` \>= `minQty` +* `quantity` \<= `maxQty` +* (`quantity`\-`minQty`) % `stepSize` \== 0 + +# Market data API + +## Test server connectivity + +**Response** + +```javascript +{} +``` + +`GET /api/v3/ping` + +Test whether the REST API can be reached. + +**Weight:** 1 + +**Parameters:** NONE + +## Get server time + +**Response** + +```javascript +{ + "serverTime": 1499827319559 +} +``` + +`GET /api/v3/time` + +Test if the REST API can be reached and retrieve the server time. + +**Weight:** 1 + +**Parameters:** NONE + +## Trading specification information + +**Response** + +```javascript +{ + "timezone": "UTC", + "serverTime": 1756197279679, + "rateLimits": [{ + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 6000 + }, + { + "rateLimitType": "ORDERS", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 6000 + }, + { + "rateLimitType": "ORDERS", + "interval": "SECOND", + "intervalNum": 10, + "limit": 300 + } + ], + "exchangeFilters": [], + "assets": [{ + "asset": "USD" + }, { + "asset": "USDT" + }, + { + "asset": "BNB" + } + ], + "symbols": [{ + "status": "TRADING", + "baseAsset": "BNB", + "quoteAsset": "USDT", + "pricePrecision": 8, + "quantityPrecision": 8, + "baseAssetPrecision": 8, + "quotePrecision": 8, + "filters": [{ + "minPrice": "0.01000000", + "maxPrice": "100000", + "filterType": "PRICE_FILTER", + "tickSize": "0.01000000" + }, + { + "stepSize": "0.00100000", + "filterType": "LOT_SIZE", + "maxQty": "1000", + "minQty": "1" + }, + { + "stepSize": "0.00100000", + "filterType": "MARKET_LOT_SIZE", + "maxQty": "900000", + "minQty": "0.00100000" + }, + { + "limit": 200, + "filterType": "MAX_NUM_ORDERS" + }, + { + "minNotional": "5", + "filterType": "MIN_NOTIONAL" + }, + { + "maxNotional": "100", + "filterType": "MAX_NOTIONAL" + }, + { + "maxNotional": "100", + "minNotional": "5", + "avgPriceMins": 5, + "applyMinToMarket": true, + "filterType": "NOTIONAL", + "applyMaxToMarket": true + }, + { + "multiplierDown": "0", + "multiplierUp": "5", + "multiplierDecimal": "0", + "filterType": "PERCENT_PRICE" + }, + { + "bidMultiplierUp": "5", + "askMultiplierUp": "5", + "bidMultiplierDown": "0", + "avgPriceMins": 5, + "multiplierDecimal": "0", + "filterType": "PERCENT_PRICE_BY_SIDE", + "askMultiplierDown": "0" + } + ], + "orderTypes": [ + "LIMIT", + "MARKET", + "STOP", + "STOP_MARKET", + "TAKE_PROFIT", + "TAKE_PROFIT_MARKET" + ], + "timeInForce": [ + "GTC", + "IOC", + "FOK", + "GTX" + ], + "symbol": "BNBUSDT", + "ocoAllowed": false + }] +} +``` + +`GET /api/v3/exchangeInfo` + +Retrieve trading rules and trading pair information. + +**Weight:** 1 + +**Parameters:** None + +## Depth information + +**Response** + +```javascript +{ + "lastUpdateId": 1027024, + "E":1589436922972, // Message output time + "T":1589436922959, // Transaction time + "bids": [ + [ + "4.00000000", // PRICE + "431.00000000" // QTY + ] + ], + "asks": [ + [ + "4.00000200", + "12.00000000" + ] + ] +} +``` + +`GET /api/v3/depth` + +**Weight:** + +Based on limit adjustments: + +| Limitations | Weight | +| :---- | :---- | +| 5, 10, 20, 50 | 2 | +| 100 | 5 | +| 500 | 10 | +| 1000 | 20 | + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| limit | INT | NO | Default 100\. Optional values: \[5, 10, 20, 50, 100, 500, 1000\] | + +## Recent trades list + +**Response** + +```javascript +[ + { + "id": 657, + "price": "1.01000000", + "qty": "5.00000000", + "baseQty": "4.95049505", + "time": 1755156533943, + "isBuyerMaker": false + } +] +``` + +`GET /api/v3/trades` + +Get recent trades + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| limit | INT | NO | Default 500; maximum 1000 | + +## Query historical trades (MARKET\_DATA) + +**Response** + +```javascript +[ + { + "id": 1140, + "price": "1.10000000", + "qty": "7.27200000", + "baseQty": "6.61090909", + "time": 1756094288700, + "isBuyerMaker": false + } +] +``` + +`GET /api/v3/historicalTrades` + +Retrieve historical trades + +**Weight:** 20 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| limit | INT | NO | Default 500; maximum 1000\. | +| fromId | LONG | NO | Return starting from which trade id. Defaults to returning the most recent trade records. | + +## Recent trades (aggregated) + +**Response** + +```javascript +[ + { + "a": 26129, // Aggregate tradeId + "p": "0.01633102", // Price + "q": "4.70443515", // Quantity + "f": 27781, // First tradeId + "l": 27781, // Last tradeId + "T": 1498793709153, // Timestamp + "m": true, // Was the buyer the maker? + } +] +``` + +`GET /api/v3/aggTrades` + +The difference between aggregated trades and individual trades is that trades with the same price, same side, and same time are combined into a single entry. + +**Weight:** 20 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| fromId | LONG | NO | Return results starting from the trade ID that includes fromId | +| startTime | LONG | NO | Return results starting from trades after that time | +| endTime | LONG | NO | Return the trade records up to that moment | +| limit | INT | NO | Default 500; maximum 1000\. | + +* If you send startTime and endTime, the interval must be less than one hour. +* If no filter parameters (fromId, startTime, endTime) are sent, the most recent trade records are returned by default + +## K-line data + +**Response** + +```javascript +[ + [ + 1499040000000, // Open time + "0.01634790", // Open + "0.80000000", // High + "0.01575800", // Low + "0.01577100", // Close + "148976.11427815", // Volume + 1499644799999, // Close time + "2434.19055334", // Quote asset volume + 308, // Number of trades + "1756.87402397", // Taker buy base asset volume + "28.46694368", // Taker buy quote asset volume + ] +] +``` + +`GET /api/v3/klines` + +Each K-line represents a trading pair. The open time of each K-line can be regarded as a unique ID. + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| interval | ENUM | YES | See the enumeration definition: K-line interval | +| startTime | LONG | NO | | +| endTime | LONG | NO | | +| limit | INT | NO | Default 500; maximum 1500\. | + +* If startTime and endTime are not sent, the most recent trades are returned by default + +## 24h price change + +**Response** + +```javascript +{ + "symbol": "BTCUSDT", //symbol + "priceChange": "-94.99999800", //price change + "priceChangePercent": "-95.960", //price change percent + "weightedAvgPrice": "0.29628482", //weighted avgPrice + "prevClosePrice": "3.89000000", //prev close price + "lastPrice": "4.00000200", //last price + "lastQty": "200.00000000", //last qty + "bidPrice": "866.66000000", //first bid price + "bidQty": "72.05100000", //first bid qty + "askPrice": "866.73000000", //first ask price + "askQty": "1.21700000", //first ask qty + "openPrice": "99.00000000", //open price + "highPrice": "100.00000000", //high price + "lowPrice": "0.10000000", //low price + "volume": "8913.30000000", //volume + "quoteVolume": "15.30000000", //quote volume + "openTime": 1499783499040, //open time + "closeTime": 1499869899040, //close time + "firstId": 28385, // first id + "lastId": 28460, // last id + "count": 76, // count + "baseAsset": "BTC", //base asset + "quoteAsset": "USDT" //quote asset +} +``` + +`GET /api/v3/ticker/24hr` + +24-hour rolling window price change data. Please note that omitting the symbol parameter will return data for all trading pairs; in that case the returned data is an example array for the respective pairs, which is not only large in volume but also has a very high weight. + +**Weight:** 1 \= single trading pair; **40** \= When the trading pair parameter is missing (returns all trading pairs) + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | NO | | + +* Please note that omitting the symbol parameter will return data for all trading pairs + +## Latest price + +**Response** + +```javascript +{ + "symbol": "ADAUSDT", + "price": "1.30000000", + "time": 1649666690902 +} +``` + +OR + +```javascript +[ + { + "symbol": "ADAUSDT", + "price": "1.30000000", + "time": 1649666690902 + } +] +``` + +`GET /api/v3/ticker/price` + +Get the latest price for a trading pair + +**Weight:** 1 \= Single trading pair; **2** \= No symbol parameter (returns all pairs) + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | NO | | + +* If no trading pair parameter is sent, information for all trading pairs will be returned + +## Current best order + +**Response** + +```javascript +{ + "symbol": "LTCBTC", + "bidPrice": "4.00000000", + "bidQty": "431.00000000", + "askPrice": "4.00000200", + "askQty": "9.00000000" + "time": 1589437530011 // Timestamp +} +``` + +OR + +```javascript +[ + { + "symbol": "LTCBTC", + "bidPrice": "4.00000000", + "bidQty": "431.00000000", + "askPrice": "4.00000200", + "askQty": "9.00000000", + "time": 1589437530011 // Timestamp + } +] +``` + +`GET /api/v3/ticker/bookTicker` + +Return the current best orders (highest bid, lowest ask) + +**Weight:** 1 \= Single trading pair; **2** \= No symbol parameter (returns all pairs) + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | NO | | + +* If no trading pair parameter is sent, information for all trading pairs will be returned + +## Get symbol fees + +**Response** + +```javascript +{ + "symbol": "APXUSDT", + "makerCommissionRate": "0.000200",     + "takerCommissionRate": "0.000700" +} +``` + +`GET /api/v3/commissionRate` + +Get symbol fees + +**Weight:** 20 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| recvWindow | LONG | NO | The assigned value cannot be greater than 60000 | +| timestamp | LONG | YES | | + +# Spot account and trading API + +## Place order (TRADE) + +**Response ACK:** + +```javascript +{ + "symbol": "BTCUSDT", + "orderId": 28, + "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP", + "updateTime": 1507725176595, + "price": "0.00000000", + "avgPrice": "0.0000000000000000", + "origQty": "10.00000000", + "cumQty": "0", + "executedQty": "10.00000000", + "cumQuote": "10.00000000", + "status": "FILLED", + "timeInForce": "GTC", + "stopPrice": "0", + "origType": "LIMIT", + "type": "LIMIT", + "side": "SELL", +} +``` + +`POST /api/v3/order (HMAC SHA256)` + +Send order + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| side | ENUM | YES | See enum definition: Order direction | +| type | ENUM | YES | See enumeration definition: Order type | +| timeInForce | ENUM | NO | See enum definition: Time in force | +| quantity | DECIMAL | NO | | +| quoteOrderQty | DECIMAL | NO | | +| price | DECIMAL | NO | | +| newClientOrderId | STRING | NO | Client-customized unique order ID. If not provided, one will be generated automatically. | +| stopPrice | DECIMAL | NO | Only STOP, STOP\_MARKET, TAKE\_PROFIT, TAKE\_PROFIT\_MARKET require this parameter | +| recvWindow | LONG | NO | The value cannot be greater than 60000 | +| timestamp | LONG | YES | | + +Depending on the order `type`, certain parameters are mandatory: + +| Type | Mandatory parameters | +| :---- | :---- | +| LIMIT | timeInForce, quantity, price | +| MARKET | quantity or quoteOrderQty | +| STOP and TAKE\_PROFIT | quantity, price, stopPrice | +| STOP\_MARKET and TAKE\_PROFIT\_MARKET | quantity, stopPrice | + +Other information: + +* Place a `MARKET` `SELL` market order; the user controls the amount of base assets to sell with the market order via `QUANTITY`. + * For example, when placing a `MARKET` `SELL` market order on the `BTCUSDT` pair, use `QUANTITY` to let the user specify how much BTC they want to sell. +* For a `MARKET` `BUY` market order, the user controls how much of the quote asset they want to spend with `quoteOrderQty`; `QUANTITY` will be calculated by the system based on market liquidity. For example, when placing a `MARKET` `BUY` market order on the `BTCUSDT` pair, use `quoteOrderQty` to let the user choose how much USDT to use to buy BTC. +* A `MARKET` order using `quoteOrderQty` will not violate the `LOT_SIZE` limit rules; the order will be executed as closely as possible to the given `quoteOrderQty`. +* Unless a previous order has already been filled, orders set with the same `newClientOrderId` will be rejected. + +## Cancel order (TRADE) + +**Response** + +```javascript +{ + "symbol": "BTCUSDT", + "orderId": 28, + "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP", + "updateTime": 1507725176595, + "price": "0.00000000", + "avgPrice": "0.0000000000000000", + "origQty": "10.00000000", + "cumQty": "0", + "executedQty": "10.00000000", + "cumQuote": "10.00000000", + "status": "CANCELED", + "timeInForce": "GTC", + "stopPrice": "0", + "origType": "LIMIT", + "type": "LIMIT", + "side": "SELL", +} +``` + +`DELETE /api/v3/order (HMAC SHA256)` + +Cancel active orders + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| orderId | LONG | NO | | +| origClientOrderId | STRING | NO | | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +At least one of `orderId` or `origClientOrderId` must be sent. + +## Query order (USER\_DATA) + +**Response** + +```javascript +{ + "orderId": 38, + "symbol": "ADA25SLP25", + "status": "FILLED", + "clientOrderId": "afMd4GBQyHkHpGWdiy34Li", + "price": "20", + "avgPrice": "12.0000000000000000", + "origQty": "10", + "executedQty": "10", + "cumQuote": "120", + "timeInForce": "GTC", + "type": "LIMIT", + "side": "BUY", + "stopPrice": "0", + "origType": "LIMIT", + "time": 1649913186270, + "updateTime": 1649913186297 +} +``` + +`GET /api/v3/order (HMAC SHA256)` + +Query order status + +* Please note that orders meeting the following conditions will not be returned: + * The final status of the order is `CANCELED` or `EXPIRED`, **and** + * The order has no trade records, **and** + * Order creation time \+ 7 days \< current time + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| orderId | LONG | NO | | +| origClientOrderId | STRING | NO | | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +Note: + +* You must send at least one of `orderId` or `origClientOrderId`. + +## Current open orders (USER\_DATA) + +**Response** + +```javascript +[ + { + "orderId": 349661, + "symbol": "BNBUSDT", + "status": "NEW", + "clientOrderId": "LzypgiMwkf3TQ8wwvLo8RA", + "price": "1.10000000", + "avgPrice": "0.0000000000000000", + "origQty": "5",   + "executedQty": "0", + "cumQuote": "0", + "timeInForce": "GTC", + "type": "LIMIT", + "side": "BUY", + "stopPrice": "0", + "origType": "LIMIT", + "time": 1756252940207, + "updateTime": 1756252940207, + } +] +``` + +`GET /api/v3/openOrders (HMAC SHA256)` + +Retrieve all current open orders for trading pairs. Use calls without a trading pair parameter with caution. + +**Weight:** + +* With symbol ***1*** +* Without ***40***   + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | NO | | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +* If the symbol parameter is not provided, it will return the order books for all trading pairs. + +## Cancel All Open Orders (TRADE) + +> **Response** + +```javascript +{ + "code": 200, + "msg": "The operation of cancel all open order is done." +} +``` + +`` +DEL /api/v3/allOpenOrders (HMAC SHA256) +`` + +**Weight:** +- ***1*** + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +orderIdList | STRING | NO | orderid array string +origClientOrderIdList | STRING | NO | clientOrderId array string +recvWindow | LONG | NO | +timestamp | LONG | YES | + + +## Query all orders (USER\_DATA) + +**Response** + +```javascript +[ + { + "orderId": 349661, + "symbol": "BNBUSDT", + "status": "NEW", + "clientOrderId": "LzypgiMwkf3TQ8wwvLo8RA", + "price": "1.10000000", + "avgPrice": "0.0000000000000000", + "origQty": "5",   + "executedQty": "0", + "cumQuote": "0", + "timeInForce": "GTC", + "type": "LIMIT", + "side": "BUY", + "stopPrice": "0", + "origType": "LIMIT", + "time": 1756252940207, + "updateTime": 1756252940207, + } +] +``` + +`GET /api/v3/allOrders (HMAC SHA256)` + +Retrieve all account orders; active, canceled, or completed. + +* Please note that orders meeting the following conditions will not be returned: + * Order creation time \+ 7 days \< current time + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| orderId | LONG | NO | | +| startTime | LONG | NO | | +| endTime | LONG | NO | | +| limit | INT | NO | Default 500; maximum 1000 | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +* The maximum query time range must not exceed 7 days. +* By default, query data is from the last 7 days. + + +## Perp-spot transfer (TRADE) + +**Response:** + +```javascript +{ + "tranId": 21841, //Tran Id + "status": "SUCCESS" //Status +} +``` + +`POST /api/v3/asset/wallet/transfer (HMAC SHA256)` + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| amount | DECIMAL | YES | Quantity | +| asset | STRING | YES | Asset | +| clientTranId | STRING | YES | Transaction ID | +| kindType | STRING | YES | Transaction type | +| timestamp | LONG | YES | Timestamp | + +* kindType FUTURE_SPOT(future to spot)/SPOT_FUTURE(spot to future) + +## Get withdraw fee (NONE) +> **Response:** +```javascript +{ + "tokenPrice": 1.00019000, + "gasCost": 0.5000, + "gasUsdValue": 0.5 +} +``` + +`` +GET /api/v3/aster/withdraw/estimateFee +`` + +**Weight:** +1 + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +chainId | STRING | YES | +asset | STRING | YES | + +**Notes:** +* chainId: 1(ETH),56(BSC),42161(Arbi) +* gasCost: The minimum fee required for a withdrawal + +## Withdraw (USER_DATA) +> **Response:** +```javascript +{ + "withdrawId": "1014729574755487744", + "hash":"0xa6d1e617a3f69211df276fdd8097ac8f12b6ad9c7a49ba75bbb24f002df0ebb" +} +``` + +`` +POST /api/v3/aster/user-withdraw (HMAC SHA256) +`` + +**Weight:** +1 + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +chainId | STRING | YES | 1(ETH),56(BSC),42161(Arbi) +asset | STRING | YES | +amount | STRING | YES | +fee | STRING | YES | +receiver | STRING | YES | The address of the current account +nonce | STRING | YES | The current time in microseconds +userSignature | STRING | YES | +recvWindow | LONG | NO | +timestamp | LONG | YES | + + +**Note:** +* chainId: 1(ETH),56(BSC),42161(Arbi) +* receiver: The address of the current account +* If the futures account balance is insufficient, funds will be transferred from the spot account to the perp account for withdrawal. +* userSignature demo + +```shell +const domain = { + name: 'Aster', + version: '1', + chainId: 56, + verifyingContract: ethers.ZeroAddress, + } + +const currentTime = Date.now() * 1000 + +const types = { + Action: [ + {name: "type", type: "string"}, + {name: "destination", type: "address"}, + {name: "destination Chain", type: "string"}, + {name: "token", type: "string"}, + {name: "amount", type: "string"}, + {name: "fee", type: "string"}, + {name: "nonce", type: "uint256"}, + {name: "aster chain", type: "string"}, + ], + } + const value = { + 'type': 'Withdraw', + 'destination': '0xD9cA6952F1b1349d27f91E4fa6FB8ef67b89F02d', + 'destination Chain': 'BSC', + 'token': 'USDT', + 'amount': '10.123400', + 'fee': '1.234567891', + 'nonce': currentTime, + 'aster chain': 'Mainnet', + } + + +const signature = await signer.signTypedData(domain, types, value) +``` + +## Get User Create Apikey nonce (NONE) + +> **Response:** +```javascript + +111111 + +``` + +`` +POST /api/v3/getNonce +`` + +**Weight:** +1 + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +address | STRING | YES | +userOperationType | STRING | YES | CREATE_API_KEY +network | STRING | NO | + +**Notes:** +* userOperationType: CREATE_API_KEY +* network: For the Solana network, SOL must be provided; otherwise, this field can be ignored. + +## Create Apikey (NONE) + +> **Response:** +```javascript +{ + "apiKey": "bb3b24d0a3dec88cb06be58a257e4575cb0b1bb256ad6fd90ae8fd0ee1d102ae", + "apiSecret": "9fe8f5642ae1961674ea0cb7f957fa99dc8e0421b607c985a963ad2ced90ae1c" +} +``` + +`` +POST /api/v3/createApiKey +`` + +**Weight:** +1 + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +address | STRING | YES | +userOperationType | STRING | YES | CREATE_API_KEY +network | STRING | NO | +userSignature | STRING | YES | +apikeyIP | STRING | NO | +desc | STRING | YES | +recvWindow | LONG | NO | +timestamp | LONG | YES | + +**Note:** +* userOperationType: CREATE_API_KEY +* network: For the Solana network, SOL must be provided; otherwise, this field can be ignored. +* desc: The same account cannot be duplicated, and the length must not exceed 20 characters. +* apikeyIP: An array of IP addresses, separated by commas. +* Rate limit: 60 requests per minute per IP. +* userSignature: EVM demo + +```shell +const nonce = 111111 +const message = 'You are signing into Astherus ${nonce}'; +const signature = await signer.signMessage(message); +``` + +## Account information (USER\_DATA) + +**Response** + +```javascript +{ + "feeTier": 0, + "canTrade": true, + "canDeposit": true, + "canWithdraw": true, + "canBurnAsset": true, + "updateTime": 0, +   "balances": [ + { + "asset": "BTC", + "free": "4723846.89208129", + "locked": "0.00000000" + }, + { + "asset": "LTC", + "free": "4763368.68006011", + "locked": "0.00000000" + } + ] +} +``` + +`GET /api/v3/account (HMAC SHA256)` + +Retrieve current account information + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +## Account trade history (USER\_DATA) + +**Response** + +```javascript +[ + { + "symbol": "BNBUSDT", + "id": 1002, + "orderId": 266358, + "side": "BUY", + "price": "1", + "qty": "2", + "quoteQty": "2", + "commission": "0.00105000", + "commissionAsset": "BNB", + "time": 1755656788798, + "counterpartyId": 19, + "createUpdateId": null, + "maker": false, + "buyer": true + } +] +``` + +`GET /api/v3/userTrades (HMAC SHA256)` + +Retrieve the trade history for a specified trading pair of an account + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | NO | | +| orderId | LONG | NO | Must be used together with the parameter symbol | +| startTime | LONG | NO | | +| endTime | LONG | NO | | +| fromId | LONG | NO | Starting trade ID. Defaults to fetching the most recent trade. | +| limit | INT | NO | Default 500; maximum 1000 | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +* If both `startTime` and `endTime` are not sent, only data from the last 7 days will be returned. +* The maximum interval between startTime and endTime is 7 days. +* `fromId` cannot be sent together with `startTime` or `endTime`.       + +--- + +# WebSocket market data feed + +* The base URL for all wss endpoints listed in this document is: **wss://sstream.asterdex.com** +* Streams have either a single raw stream or a combined stream +* Single raw streams format is \*\*/ws/\*\* +* The URL format for combined streams is \*\*/stream?streams=//\*\* +* When subscribing to combined streams, the event payload is wrapped in this format: \*\*{"stream":"","data":}\*\* +* All trading pairs in stream names are **lowercase** +* Each link to **sstream.asterdex.com** is valid for no more than 24 hours; please handle reconnections appropriately +* Every 3 minutes the server sends a ping frame; the client must reply with a pong frame within 10 minutes, otherwise the server will close the connection. The client is allowed to send unpaired pong frames (i.e., the client may send pong frames at a frequency higher than once every 10 minutes to keep the connection alive). + +## Real-time subscribe/unsubscribe data streams + +* The following messages can be sent via WebSocket to subscribe or unsubscribe to data streams. Examples are shown below. +* The `id` in the response content is an unsigned integer that serves as the unique identifier for exchanges of information. +* If the `result` in the response content is `null`, it indicates the request was sent successfully. + +### Subscribe to a stream + +**Response** + +```javascript +{ + "result": null, + "id": 1 +} +``` + +* **Request** { "method": "SUBSCRIBE", "params": \[ "btcusdt@aggTrade", "btcusdt@depth" \], "id": 1 } + +### Unsubscribe from a stream + +**Response** + +```javascript +{ + "result": null, + "id": 312 +} +``` + +* **Request** { "method": "UNSUBSCRIBE", "params": \[ "btcusdt@depth" \], "id": 312 } + +### Subscribed to the feed + +**Response** + +```javascript +{ + "result": [ + "btcusdt@aggTrade" + ], + "id": 3 +} +``` + +* **Request** + + { "method": "LIST\_SUBSCRIPTIONS", "id": 3 } + +### Set properties + +Currently, the only configurable property is whether to enable the `combined` ("combined") stream. When connecting using `/ws/` ("raw stream"), the combined property is set to `false`, while connecting using `/stream/` sets the property to `true`. + +**Response** + +```javascript +{ +"result": null, +"id": 5 +} +``` + +* **Request** { "method": "SET\_PROPERTY" "params": \[ "combined", true \], "id": 5 } + +### Retrieve properties + +**Response** + +```javascript +{ + "result": true, // Indicates that combined is set to true. + "id": 2 +} +``` + +* **Request** + + { "method": "GET\_PROPERTY", "params": \[ "combined" \], "id": 2 } + +\#\#\# Error message + +| Error message | Description | +| :---- | :---- | +| {"code": 0, "msg": "Unknown property"} | Parameters applied in SET\_PROPERTY or GET\_PROPERTY are invalid | +| {"code": 1, "msg": "Invalid value type: expected Boolean", "id": '%s'} | Only true or false are accepted | +| {"code": 2, "msg": "Invalid request: property name must be a string"} | The provided attribute name is invalid | +| {"code": 2, "msg": "Invalid request: request ID must be an unsigned integer"} | Parameter ID not provided or ID has an invalid type | +| {"code": 2, "msg": "Invalid request: unknown variant %s, expected one of SUBSCRIBE, UNSUBSCRIBE, LIST\_SUBSCRIPTIONS, SET\_PROPERTY, GET\_PROPERTY at line 1 column 28"} | Typo warning, or the provided value is not of the expected type | +| {"code": 2, "msg": "Invalid request: too many parameters"} | Unnecessary parameters were provided in the data | +| {"code": 2, "msg": "Invalid request: property name must be a string"} | Property name not provided | +| {"code": 2, "msg": "Invalid request: missing field method at line 1 column 73"} | Data did not provide method | +| {"code":3,"msg":"Invalid JSON: expected value at line %s column %s"} | JSON syntax error | + +## Collection transaction flow + +**Payload:** + +```javascript +{ + "e": "aggTrade", // Event type + "E": 123456789, // Event time + "s": "BNBBTC", // Symbol + "a": 12345, // Aggregate trade ID + "p": "0.001", // Price + "q": "100", // Quantity + "f": 100, // First trade ID + "l": 105, // Last trade ID + "T": 123456785, // Trade time + "m": true, // Is the buyer the market maker? + "M": true // Ignore +} +``` + +The collection transaction stream pushes transaction information and is an aggregation of a single order. + +**Stream name:** `@aggTrade` + +**Update speed:** real-time + +## Tick-by-tick trades + +**Payload:** + +```javascript +{ + "e": "trade", // Event type + "E": 123456789, // Event time + "s": "BNBBTC", // Symbol + "t": 12345, // Trade ID + "p": "0.001", // Price + "q": "100", // Quantity + "T": 123456785, // Trade time + "m": true, // Is the buyer the market maker? +} +``` + +**Stream name:** `@trade` + +Each trade stream pushes the details of every individual trade. A **trade**, also called a transaction, is defined as a match between exactly one taker and one maker. + +## K-line streams + +**Payload:** + +```javascript +{ + "e": "kline", // Event type + "E": 123456789, // Event time + "s": "BNBBTC", // Symbol + "k": { + "t": 123400000, // Kline start time + "T": 123460000, // Kline close time + "s": "BNBBTC", // Symbol + "i": "1m", // Interval + "f": 100, // First trade ID + "L": 200, // Last trade ID + "o": "0.0010", // Open price + "c": "0.0020", // Close price + "h": "0.0025", // High price + "l": "0.0015", // Low price + "v": "1000", // Base asset volume + "n": 100, // Number of trades + "x": false, // Is this kline closed? + "q": "1.0000", // Quote asset volume + "V": "500", // Taker buy base asset volume + "Q": "0.500", // Taker buy quote asset volume + "B": "123456" // Ignore + } +} +``` + +The K-line stream pushes per-second updates for the requested type of K-line (the latest candle). + +**Stream name:** `@kline_` + +**Update speed:** 2000ms + +**K-line interval parameter:** + +m (minutes), h (hours), d (days), w (weeks), M (months) + +* 1m +* 3m +* 5m +* 15m +* 30m +* 1h +* 2h +* 4h +* 6h +* 8h +* 12h +* 1d +* 3d +* 1w +* 1M + +## Simplified ticker by symbol + +**Payload:** + +```javascript + { + "e": "24hrMiniTicker", // Event type + "E": 123456789, // Event time + "s": "BNBBTC", // Symbol + "c": "0.0025", // Close price + "o": "0.0010", // Open price + "h": "0.0025", // High price + "l": "0.0010", // Low price + "v": "10000", // Total traded base asset volume + "q": "18" // Total traded quote asset volume + } +``` + +Refreshed simplified 24-hour ticker information by symbol + +**Stream name:** `@miniTicker` + +**Update speed:** 1000ms + +## Compact tickers for all symbols in the entire market + +**Payload:** + +```javascript +[ + { + // Same as @miniTicker payload + } +] +``` + +Same as above, but pushes all trading pairs. Note that only updated tickers will be pushed. + +**Stream name:** \!miniTicker@arr + +**Update speed:** 1000ms + +## Full ticker per symbol + +**Payload:** + +```javascript +{ + "e": "24hrTicker", // Event type + "E": 123456789, // Event time + "s": "BNBBTC", // Symbol + "p": "0.0015", // Price change + "P": "250.00", // Price change percent + "w": "0.0018", // Weighted average price + "c": "0.0025", // Last price + "Q": "10", // Last quantity + "o": "0.0010", // Open price + "h": "0.0025", // High price + "l": "0.0010", // Low price + "v": "10000", // Total traded base asset volume + "q": "18", // Total traded quote asset volume + "O": 0, // Statistics open time + "C": 86400000, // Statistics close time + "F": 0, // First trade ID + "L": 18150, // Last trade Id + "n": 18151 // Total number of trades +} +``` + +Pushes per-second tag statistics for a single trading pair over a rolling 24-hour window. + +**Stream name:** `@ticker` + +**Update speed:** 1000ms + +## Complete ticker for all trading pairs on the entire market + +**Payload:** + +```javascript +[ + { + // Same as @ticker payload + } +] +``` + +Pushes the full 24-hour refreshed ticker information for all trading pairs across the entire market. Note that tickers without updates will not be pushed. + +**Stream name:** `!ticker@arr` + +**Update speed:** 1000ms + +## Best order book information by symbol + +**Payload:** + +```javascript +{ + "u":400900217, // order book updateId + "s":"BNBUSDT", // symbol + "b":"25.35190000", // best bid price + "B":"31.21000000", // best bid qty + "a":"25.36520000", // best ask price + "A":"40.66000000" // best ask qty +} +``` + +Real-time push of best order book information for the specified trading pair + +**Stream name:** `@bookTicker` + +**Update speed:** Real-time + +## Best order book information across the entire market + +**Payload:** + +```javascript +{ + // 同 @bookTicker payload +} +``` + +Real-time push of the best order information for all trading pairs + +**Stream name:** `!bookTicker` + +**Update speed:** Real-time + +## Limited depth information + +**Payload:** + +```javascript +{ + "e": "depthUpdate", // Event type + "E": 123456789, // Event time + "T": 123456788, // Transaction time + "s": "BTCUSDT", // Symbol + "U": 100, // First update ID in event + "u": 120, // Final update ID in event + "pu": 99, // Final update Id in last stream(ie `u` in last stream) +  "bids": [ // Bids to be updated + [ + "0.0024", // Price level to be updated + "10" // Quantity + ] + ], + "asks": [ // Asks to be updated + [ + "0.0026", // Price level to be updated + "100" // Quantity + ] + ] +} +``` + +Limited depth information pushed every second or every 100 milliseconds. Levels indicate how many levels of bid/ask information, optional 5/10/20 levels. + +**Stream names:** `@depth` or `@depth@100ms`. + +**Update speed:** 1000ms or 100ms + +## Incremental depth information + +**Payload:** + +```javascript +{ + "e": "depthUpdate", // Event type + "E": 123456789, // Event time + "T": 123456788, // Transaction time + "s": "BTCUSDT", // Symbol + "U": 100, // First update ID in event + "u": 120, // Final update ID in event + "pu": 99, // Final update Id in last stream(ie `u` in last stream) + "b": [ // Bids to be updated + [ + "5.4", // Price level to be updated + "10" // Quantity + ] + ], + "a": [ // Asks to be updated + [ + "5.6", // Price level to be updated + "100" // Quantity + ] + ] +} +``` + +Pushes the changed parts of the orderbook (if any) every second or every 100 milliseconds + +**Stream name:** `@depth` or `@depth@100ms` + +**Update speed:** 1000ms or 100ms + +## How to correctly maintain a local copy of an order book + +1. Subscribe to **wss://sstream.asterdex.com/ws/bnbbtc@depth** +2. Start caching the received updates. For the same price level, later updates overwrite earlier ones. +3. Fetch the REST endpoint [**https://sapi.asterdex.com/api/v3/depth?symbol=BNBBTC\&limit=1000**](https://sapi.asterdex.com/api/v3/depth?symbol=BNBBTC&limit=1000) to obtain a 1000-level depth snapshot +4. Discard from the currently cached messages those with `u` \<= the `lastUpdateId` obtained in step 3 (drop older, expired information) +5. Apply the depth snapshot to your local order book copy, and resume updating the local copy from the first WebSocket event whose `U` \<= `lastUpdateId`\+1 **and** `u` \>= `lastUpdateId`\+1 +6. Each new event’s `U` should equal exactly the previous event’s `u`\+1; otherwise packets may have been lost \- restart initialization from step 3 +7. The order quantity in each event represents the current order quantity at that price as an **absolute value**, not a relative change +8. If the order quantity at a given price is 0, it means the orders at that price have been canceled or filled, and that price level should be removed + +# WebSocket account information push + +* The base URL for the API endpoints listed in this document is: [**https://sapi.asterdex.com**](https://sapi.asterdex.com) +* The `listenKey` used to subscribe to account data is valid for 60 minutes from the time of creation +* You can extend the 60-minute validity of a `listenKey` by sending a `PUT` request +* You can immediately close the current data stream and invalidate the `listenKey` by sending a `DELETE` for a `listenKey` +* Sending a `POST` on an account with a valid `listenKey` will return the currently valid `listenKey` and extend its validity by 60 minutes +* The WebSocket interface baseurl: **wss://sstream.asterdex.com** +* The stream name for subscribing to the user account data stream is \*\*/ws/\*\* +* Each connection is valid for no more than 24 hours; please handle disconnections and reconnections appropriately + +## Listen Key (spot account) + +### Generate Listen Key (USER\_STREAM) + +**Response** + +```javascript +{ + "listenKey": "pqia91ma19a5s61cv6a81va65sdf19v8a65a1a5s61cv6a81va65sdf19v8a65a1" +} +``` + +`POST /api/v3/listenKey` + +Start a new data stream. The data stream will be closed after 60 minutes unless a keepalive is sent. If the account already has a valid `listenKey`, that `listenKey` will be returned and its validity extended by 60 minutes. + +**Weight:** 1 + +**Parameters:** NONE + +### Extend Listen Key validity period (USER\_STREAM) + +**Response** + +```javascript +{} +``` + +`PUT /api/v3/listenKey` + +Validity extended to 60 minutes after this call. It is recommended to send a ping every 30 minutes. + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| listenKey | STRING | YES | | + +### Close Listen Key (USER\_STREAM) + +**Response** + +```javascript +{} +``` + +`DELETE /api/v3/listenKey` + +Close user data stream + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| listenKey | STRING | YES | | + +## Payload: ACCOUNT\_UPDATE + +An `outboundAccountPosition` event is sent whenever an account balance changes; it contains the assets that may have changed due to the event that generated the balance update. + +**Payload** + +```javascript +{ + "B":[ //Balance + { + "a":"SLP25",   //Asset + "f":"10282.42029415",   //Free + "l":"653.00000001"   //Locked + }, + { + "a":"ADA25", + "f":"9916.96229880", + "l":"34.00510000" + } + ], + "e":"outboundAccountPosition",   //Event type + "T":1649926447190,   //Time of last account update + "E":1649926447205   //Event Time + "m":"WITHDRAW" // Event reason type +} +``` + +## Payload: Order Update + +Orders are updated via the `executionReport` event + +**Payload** + +```javascript +{ + "s":"ADA25SLP25",   // symbol + "c":"Xzh0gnxT41PStbwqOtXnjD",  // client order id + "S":"SELL",   // order direction + "o":"LIMIT",   // order type + "f":"GTC",   // Time in force + "q":"10.001000",   // Order quantity + "p":"19.1000000000",   // Order price + "ap":"19.0999999955550656", //average price + "P":"0", //stop price + "x":"TRADE",   // Current execution type + "X":"PARTIALLY_FILLED",   // Current order status + "i":27,   // Order ID + "l":"1",   // Last executed quantity + "z":"8.999000",   // Cumulative filled quantity + "L":"19.1000000000",   // Last executed price + "n":"0.00382000",  // Commission amount + "N":"SLP25",   // Commission asset + "T":1649926447190,   //Trasanction Time + "t":18,   // transaction id + "m":true,   // is this trade the maker side? + "ot":"LIMIT", //original order type + "O":0,   // Order creation time + "Z":"171.88089996", // Cumulative quote asset transacted quantity + "Y":"19.1000000000000000",   // Last quote asset transacted quantity (i.e. lastPrice * lastQty) + "Q":"0",   // Quote Order Qty + "e":"executionReport",   // event + "E":1649926447209  // event time +} +``` + +**Execution type:** + +* NEW \- New Order +* CANCELED \- Order canceled +* REJECTED \- New order was rejected +* TRADE \- Order had a new fill +* EXPIRED \- Order expired (based on the order's Time In Force parameter) + +\#错误代码 + +error JSON payload: + +```javascript +{ + "code":-1121, + "msg":"Invalid symbol." +} +``` + +Errors consist of two parts: an error code and a message. The code is standardized, but the message may vary. + +## 10xx \- General server or network issues + +### \-1000 UNKNOWN + +* An unknown error occurred while processing the request. + +### \-1001 DISCONNECTED + +* Internal error; unable to process your request. Please try again. + +### \-1002 UNAUTHORIZED + +* You are not authorized to execute this request. + +### \-1003 TOO\_MANY\_REQUESTS + +* Too many requests queued. +* Too many requests; please use the WebSocket for live updates. +* Too many requests; current limit is %s requests per minute. Please use the WebSocket for live updates to avoid polling the API. +* Too many request weights; IP banned until %s. Please use the WebSocket for live updates to avoid bans. + +### \-1004 DUPLICATE\_IP + +* This IP is already on the white list. + +### \-1005 NO\_SUCH\_IP + +* No such IP has been whitelisted. + +### \-1006 UNEXPECTED\_RESP + +* An unexpected response was received from the message bus. Execution status unknown. + +### \-1007 TIMEOUT + +* Timeout waiting for response from backend server. Send status unknown; execution status unknown. + +### \-1014 UNKNOWN\_ORDER\_COMPOSITION + +* The current order parameter combination is not supported. + +### \-1015 TOO\_MANY\_ORDERS + +* Too many new orders. +* Too many new orders; the current limit is %s orders per %s. + +### \-1016 SERVICE\_SHUTTING\_DOWN + +* This service is no longer available. + +### \-1020 UNSUPPORTED\_OPERATION + +* This operation is not supported. + +### \-1021 INVALID\_TIMESTAMP + +* Timestamp for this request is outside of the recvWindow. +* The timestamp for this request was 1000ms ahead of the server's time. + +### \-1022 INVALID\_SIGNATURE + +* The signature for this request is invalid. + +### \-1023 START\_TIME\_GREATER\_THAN\_END\_TIME + +* The start time in the parameters is after the end time. + +## 11xx \- Request issues + +### \-1100 ILLEGAL\_CHARS + +* Illegal characters found in a parameter. +* Illegal characters found in parameter %s; legal range is %s. + +### \-1101 TOO\_MANY\_PARAMETERS + +* Too many parameters sent for this endpoint. +* Too many parameters; expected %s and received %s. +* Duplicate values for a parameter detected. + +### \-1102 MANDATORY\_PARAM\_EMPTY\_OR\_MALFORMED + +* A mandatory parameter was not sent, was empty/null, or malformed. +* Mandatory parameter %s was not sent, was empty/null, or malformed. +* Param %s or %s must be sent, but both were empty/null. + +### \-1103 UNKNOWN\_PARAM + +* An unknown parameter was sent. + +### \-1104 UNREAD\_PARAMETERS + +* Not all sent parameters were read. +* Not all sent parameters were read; read %s parameter(s) but %s parameter(s) were sent. + +### \-1105 PARAM\_EMPTY + +* A parameter was empty. +* Parameter %s was empty. + +### \-1106 PARAM\_NOT\_REQUIRED + +* A parameter was sent when not required.  + +### \-1111 BAD\_PRECISION  + +* The precision exceeds the maximum defined for this asset. + +### \-1112 NO\_DEPTH + +* No open orders for the trading pair. + +### \-1114 TIF\_NOT\_REQUIRED + +* TimeInForce parameter sent when not required. + +### \-1115 INVALID\_TIF + +* Invalid timeInForce. + +### \-1116 INVALID\_ORDER\_TYPE + +* Invalid orderType. + +### \-1117 INVALID\_SIDE + +* Invalid order side. + +### \-1118 EMPTY\_NEW\_CL\_ORD\_ID + +* New client order ID was empty. + +### \-1119 EMPTY\_ORG\_CL\_ORD\_ID + +* The client’s custom order ID is empty. + +### \-1120 BAD\_INTERVAL + +* Invalid time interval. + +### \-1121 BAD\_SYMBOL + +* Invalid trading pair. + +### \-1125 INVALID\_LISTEN\_KEY + +* This listenKey does not exist. + +### \-1127 MORE\_THAN\_XX\_HOURS + +* The query interval is too large. +* More than %s hours between startTime and endTime. + +### \-1128 OPTIONAL\_PARAMS\_BAD\_COMBO  + +* Combination of optional parameters invalid.  + +### \-1130 INVALID\_PARAMETER  + +* The parameter sent contains invalid data. +* Data sent for parameter %s is not valid.  + +### \-1136 INVALID\_NEW\_ORDER\_RESP\_TYPE  + +* Invalid newOrderRespType.  + +## 20xx \- Processing Issues  + +### \-2010 NEW\_ORDER\_REJECTED  + +* New order rejected. + +### \-2011 CANCEL\_REJECTED + +* Order cancellation rejected. + +### \-2013 NO\_SUCH\_ORDER + +* Order does not exist. + +### \-2014 BAD\_API\_KEY\_FMT + +* API-key format invalid. + +### \-2015 REJECTED\_MBX\_KEY + +* Invalid API key, IP, or permissions for action. + +### \-2016 NO\_TRADING\_WINDOW + +* No trading window could be found for the symbol. Try ticker/24hrs instead. + +### \-2018 BALANCE\_NOT\_SUFFICIENT + +* Balance is insufficient. + +### \-2020 UNABLE\_TO\_FILL + +* Unable to fill. + +### \-2021 ORDER\_WOULD\_IMMEDIATELY\_TRIGGER + +* Order would immediately trigger. + +### \-2022 REDUCE\_ONLY\_REJECT + +* ReduceOnly Order is rejected. + +### \-2024 POSITION\_NOT\_SUFFICIENT + +* Position is not sufficient. + +### \-2025 MAX\_OPEN\_ORDER\_EXCEEDED + +* Reached max open order limit. + +### \-2026 REDUCE\_ONLY\_ORDER\_TYPE\_NOT\_SUPPORTED + +* This OrderType is not supported when reduceOnly. + +## 40xx \- Filters and other Issues + +### \-4000 INVALID\_ORDER\_STATUS + +* Invalid order status. + +### \-4001 PRICE\_LESS\_THAN\_ZERO + +* Price less than 0\. + +### \-4002 PRICE\_GREATER\_THAN\_MAX\_PRICE + +* Price greater than max price. + +### \-4003 QTY\_LESS\_THAN\_ZERO + +* Quantity less than zero. + +### \-4004 QTY\_LESS\_THAN\_MIN\_QTY + +* Quantity less than minimum quantity. + +### \-4005 QTY\_GREATER\_THAN\_MAX\_QTY + +* Quantity greater than maximum quantity. + +### \-4006 STOP\_PRICE\_LESS\_THAN\_ZERO + +* Stop price less than zero. + +### \-4007 STOP\_PRICE\_GREATER\_THAN\_MAX\_PRICE + +* Stop price greater than max price. + +### \-4008 TICK\_SIZE\_LESS\_THAN\_ZERO + +* Tick size less than zero. + +### \-4009 MAX\_PRICE\_LESS\_THAN\_MIN\_PRICE + +* Max price less than min price. + +### \-4010 MAX\_QTY\_LESS\_THAN\_MIN\_QTY + +* Maximum quantity less than minimum quantity. + +### \-4011 STEP\_SIZE\_LESS\_THAN\_ZERO + +* Step size less than zero. + +### \-4012 MAX\_NUM\_ORDERS\_LESS\_THAN\_ZERO + +* Maximum order quantity less than 0\. + +### \-4013 PRICE\_LESS\_THAN\_MIN\_PRICE + +* Price less than minimum price. + +### \-4014 PRICE\_NOT\_INCREASED\_BY\_TICK\_SIZE + +* Price not increased by tick size. + +### \-4015 INVALID\_CL\_ORD\_ID\_LEN + +* Client order ID is not valid. +* Client order ID length should not be more than 36 characters. + +### \-4016 PRICE\_HIGHTER\_THAN\_MULTIPLIER\_UP + +* Price is higher than mark price multiplier cap. + +### \-4017 MULTIPLIER\_UP\_LESS\_THAN\_ZERO + +* Multiplier up less than zero. + +### \-4018 MULTIPLIER\_DOWN\_LESS\_THAN\_ZERO + +* Multiplier down less than zero. + +### \-4019 COMPOSITE\_SCALE\_OVERFLOW + +* Composite scale too large. + +### \-4020 TARGET\_STRATEGY\_INVALID + +* Target strategy invalid for orderType %s, reduceOnly %b' + +### \-4021 INVALID\_DEPTH\_LIMIT + +* Invalid depth limit. +* %s is not a valid depth limit. + +### \-4022 WRONG\_MARKET\_STATUS + +* Market status sent is not valid. + +### \-4023 QTY\_NOT\_INCREASED\_BY\_STEP\_SIZE + +* The increment of the quantity is not a multiple of the step size. + +### \-4024 PRICE\_LOWER\_THAN\_MULTIPLIER\_DOWN + +* Price is lower than mark price multiplier floor. + +### \-4025 MULTIPLIER\_DECIMAL\_LESS\_THAN\_ZERO + +* Multiplier decimal less than zero. + +### \-4026 COMMISSION\_INVALID + +* Commission invalid. +* Incorrect profit value. +* `%s` less than zero. +* `%s` absolute value greater than `%s`. + +### \-4027 INVALID\_ACCOUNT\_TYPE + +* Invalid account type. + +### \-4029 INVALID\_TICK\_SIZE\_PRECISION + +* Tick size precision is invalid. +* Price decimal precision is incorrect. + +### \-4030 INVALID\_STEP\_SIZE\_PRECISION + +* The number of decimal places for the step size is incorrect. + +### \-4031 INVALID\_WORKING\_TYPE + +* Invalid parameter working type: `%s` + +### \-4032 EXCEED\_MAX\_CANCEL\_ORDER\_SIZE + +* Exceeds the maximum order quantity that can be canceled. +* Invalid parameter working type: `%s` + +### \-4044 INVALID\_BALANCE\_TYPE + +* The balance type is incorrect. + +### \-4045 MAX\_STOP\_ORDER\_EXCEEDED + +* Reached the stop-loss order limit. + +### \-4055 AMOUNT\_MUST\_BE\_POSITIVE + +* The quantity must be a positive integer. + +### \-4056 INVALID\_API\_KEY\_TYPE + +* The API key type is invalid. + +### \-4057 INVALID\_RSA\_PUBLIC\_KEY + +* The API key is invalid. + +### \-4058 MAX\_PRICE\_TOO\_LARGE + +* maxPrice and priceDecimal too large, please check. + +### \-4060 INVALID\_POSITION\_SIDE + +* Invalid position side. + +### \-4061 POSITION\_SIDE\_NOT\_MATCH + +* The order's position direction does not match the user’s settings. + +### \-4062 REDUCE\_ONLY\_CONFLICT + +* Invalid or improper reduceOnly value. + +### \-4084 UPCOMING\_METHOD + +* Method is not allowed currently. Coming soon. + +### \-4086 INVALID\_PRICE\_SPREAD\_THRESHOLD + +* Invalid price spread threshold. + +### \-4087 REDUCE\_ONLY\_ORDER\_PERMISSION + +* Users can only place reduce-only orders. + +### \-4088 NO\_PLACE\_ORDER\_PERMISSION + +* User cannot place orders currently. + +### \-4114 INVALID\_CLIENT\_TRAN\_ID\_LEN + +* clientTranId is not valid. +* The customer's tranId length should be less than 64 characters. + +### \-4115 DUPLICATED\_CLIENT\_TRAN\_ID + +* clientTranId is duplicated. +* The client's tranId should be unique within 7 days. + +### \-4118 REDUCE\_ONLY\_MARGIN\_CHECK\_FAILED + +* ReduceOnly Order failed. Please check your existing position and open orders + +### \-4131 MARKET\_ORDER\_REJECT + +* The counterparty's best price does not meet the PERCENT\_PRICE filter limit. + +### \-4135 INVALID\_ACTIVATION\_PRICE + +* Invalid activation price. + +### \-4137 QUANTITY\_EXISTS\_WITH\_CLOSE\_POSITION + +* Quantity must be zero when closePosition is true. + +### \-4138 REDUCE\_ONLY\_MUST\_BE\_TRUE + +* Reduce only must be true when closePosition is true. + +### \-4139 ORDER\_TYPE\_CANNOT\_BE\_MKT + +* Order type cannot be a market order if it cannot be canceled. + +### \-4140 INVALID\_OPENING\_POSITION\_STATUS + +* Invalid symbol status for opening position. + +### \-4141 SYMBOL\_ALREADY\_CLOSED + +* Trading pair has been delisted. + +### \-4142 STRATEGY\_INVALID\_TRIGGER\_PRICE + +* Rejected: Take Profit or Stop order would be triggered immediately. + +### \-4164 MIN\_NOTIONAL + +* Order notional must be at least 5.0 (unless you select Reduce Only) +* Order notional must be no smaller than %s (unless you choose Reduce Only) + +### \-4165 INVALID\_TIME\_INTERVAL + +* Invalid time interval +* Maximum time interval is %s days + +### \-4183 PRICE\_HIGHTER\_THAN\_STOP\_MULTIPLIER\_UP + +* Limit price cannot be higher than the cap of %s. +* Take-Profit/Stop-Loss price cannot be higher than the cap of %s. + +### \-4184 PRICE\_LOWER\_THAN\_STOP\_MULTIPLIER\_DOWN + +* Price is below the stop price limit. +* Take-Profit/Stop-Loss price must be above the trigger price × multiplier floor. +* Order price (limit or TP/SL) can’t be below %s. + diff --git a/aster-finance-spot-api.md b/aster-finance-spot-api.md index 6c5bbb8..b905393 100644 --- a/aster-finance-spot-api.md +++ b/aster-finance-spot-api.md @@ -85,9 +85,6 @@ You are advised to use WebSocket messages to obtain the corresponding data as mu * Each API has its own authentication type, which determines what kind of authentication should be performed when accessing it. * The authentication type will be indicated next to each endpoint name in this document; if not specifically stated, it defaults to `NONE`. -* If API keys are required, they should be passed in the HTTP header using the `X-MBX-APIKEY` field. -* API keys and secret keys are **case-sensitive**. -* By default, API keys have access to all authenticated routes. | Authentication type | Description | | :---- | :---- | diff --git a/aster-finance-spot-api_CN-v3.md b/aster-finance-spot-api_CN-v3.md new file mode 100644 index 0000000..3a2eb85 --- /dev/null +++ b/aster-finance-spot-api_CN-v3.md @@ -0,0 +1,2804 @@ +# 基本信息 +## API 基本信息 +* 本篇列出接口的baseurl: **https://sapi.asterdex.com** +* 所有接口的响应都是 JSON 格式。 +* 所有时间、时间戳均为UNIX时间,单位为**毫秒**。 + +## API Key 设置 +* 很多接口需要API Key才可以访问. +* 设置API Key的同时,为了安全,建议设置IP访问白名单. +* **永远不要把你的API key/secret告诉给任何人** + + + +### 注意事项 +* TESTUSDT 或任何其他以 TEST 开头的交易对仅用于 Aster 的内部测试。请不要在这些以 TEST 开头的交易品种上进行交易。Aster 对因交易这些交易对而造成的资金损失不承担任何责任。但是,如果您遇到问题,您可以随时联系支持人员,我们将尽力帮助您收回资金。 + + +### HTTP 返回代码 +* HTTP `4XX` 错误码用于指示错误的请求内容、行为、格式。问题在于请求者。 +* HTTP `403` 错误码表示违反WAF限制(Web应用程序防火墙)。 +* HTTP `429` 错误码表示警告访问频次超限,即将被封IP。 +* HTTP `418` 表示收到429后继续访问,IP已经被封禁。 +* HTTP `5XX` 错误码用于指示Aster服务侧的问题。 + +### 接口错误代码 +* 使用接口 `/api/v3`, 每个接口都有可能抛出异常; +> API的错误代码返回形式如下: +```javascript +{ + "code": -1121, + "msg": "Invalid symbol." +} +``` + +### 接口的基本信息 + +* `GET` 方法的接口, 参数必须在 `query string`中发送。 +* `POST`, `PUT`, 和 `DELETE` 方法的接口,参数可以在内容形式为`application/x-www-form-urlencoded`的 `query string` 中发送,也可以在 `request body` 中发送。 +* 对参数的顺序不做要求。 + +--- +## 访问限制 +### 访问限制基本信息 + +* 在 `/api/v3/exchangeInfo` `rateLimits` 数组中包含与交易的有关REQUEST_WEIGHT和ORDERS速率限制相关的对象。这些在 `限制种类 (rateLimitType)` 下的 `枚举定义` 部分中进一步定义。 +* 违反任何一个速率限制时,将返回429。 + +### IP 访问限制 +* 每个请求的回报中包含一个`X-MBX-USED-WEIGHT-(intervalNum)(intervalLetter)`的头,其中包含当前IP所有请求的已使用权重。 +* 每一个接口均有一个相应的权重(weight),有的接口根据参数不同可能拥有不同的权重。越消耗资源的接口权重就会越大。 +* 收到429时,您有责任停止发送请求,不得滥用API。 +* **收到429后仍然继续违反访问限制,会被封禁IP,并收到418错误码** +* 频繁违反限制,封禁时间会逐渐延长,**从最短2分钟到最长3天**。 +* `Retry-After`的头会与带有418或429的响应发送,并且会给出**以秒为单位**的等待时长(如果是429)以防止禁令,或者如果是418,直到禁令结束。 +* **访问限制是基于IP的,而不是API Key** + + + + +### 下单频率限制 +* 每个成功的下单回报将包含一个`X-MBX-ORDER-COUNT-(intervalNum)(intervalLetter)`的头,其中包含当前账户已用的下单限制数量。 +* 当下单数超过限制时,会收到带有429但不含`Retry-After`头的响应。请检查 `GET api/v3/exchangeInfo` 的下单频率限制 (rateLimitType = ORDERS) 并等待封禁时间结束。 +* 被拒绝或不成功的下单并不保证回报中包含以上头内容。 +* **下单频率限制是基于每个账户计数的。** + +### WEB SOCKET 连接限制 + +* Websocket服务器每秒最多接受5个消息。消息包括: + * PING帧 + * PONG帧 + * JSON格式的消息, 比如订阅, 断开订阅. +* 如果用户发送的消息超过限制,连接会被断开连接。反复被断开连接的IP有可能被服务器屏蔽。 +* 单个连接最多可以订阅 **1024** 个Streams。 + + +## 接口鉴权类型 +* 每个接口都有自己的鉴权类型,鉴权类型决定了访问时应当进行何种鉴权 +* 如果需要鉴权,应当在请求体中添加signer + +鉴权类型 | 描述 +------------ | ------------ +NONE | 不需要鉴权的接口 +SPOT_TRADE | 需要有效的signer和签名 +USER_DATA | 需要有效的signer和签名 +USER_STREAM | 需要有效的signer和签名 +MARKET_DATA | 需要有效的signer和签名 + + +### POST /api/v3/order 的示例 + +#### 示例 : 以下参数为api注册信息,user,signer,privateKey仅供示范(privateKey为signer的私钥) + + +Key | Value | Desc +------------ | ------------ | ------------ +user | 0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e | 登陆钱包地址 +signer | 0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0 | [点击这里获取](https://www.asterdex.com/zh-CN/api-wallet) +privateKey | 0x4fd0a42218f3eae43a6ce26d22544e986139a01e5b34a62db53757ffca81bae1 | [点击这里获取](https://www.asterdex.com/zh-CN/api-wallet) + +#### 示例 : nonce参数为当前系统微秒值,超过系统时间,或者落后系统时间超过10s为非法请求 +```python +#python +nonce = math.trunc(time.time()*1000000) +print(nonce) +#1748310859508867 +``` +```java +//java +Instant now = Instant.now(); +long microsecond = now.getEpochSecond() * 1000000 + now.getNano() / 1000; +``` + +#### 示例 : 下单 (方法以python为例) + +```python +import time +import urllib + +import requests +from eth_account.messages import encode_structured_data +from eth_account import Account + +typed_data = { + "types": { + "EIP712Domain": [ + {"name": "name", "type": "string"}, + {"name": "version", "type": "string"}, + {"name": "chainId", "type": "uint256"}, + {"name": "verifyingContract", "type": "address"} + ], + "Message": [ + { "name": "msg", "type": "string" } + ] + }, + "primaryType": "Message", + "domain": { + "name": "AsterSignTransaction", + "version": "1", + "chainId": 1666, + "verifyingContract": "0x0000000000000000000000000000000000000000" + }, + "message": { + "msg": "$msg" + } +} + +headers = { + 'Content-Type': 'application/x-www-form-urlencoded', + 'User-Agent': 'PythonApp/1.0' +} +host = 'https://sapi.asterdex.com' + +# config your user and agent info here +user = '*' +signer = '*' +private_key = "*" + +place_order = {"url":"/api/v3/order","method":"POST","params":{"symbol": "ASTERUSDT", "type": "LIMIT", "side": "BUY", + "timeInForce": "GTC", "quantity": "100", "price": "0.4"}} +_last_ms = 0 +_i = 0 + +def get_nonce(): + global _last_ms, _i + now_ms = int(time.time()) + + if now_ms == _last_ms: + _i += 1 + else: + _last_ms = now_ms + _i = 0 + + return now_ms * 1_000_000 + _i + +def send_by_url(api) : + my_dict = api['params'] + url = host + api['url'] + + my_dict['nonce'] = str(get_nonce()) + my_dict['user'] = user + my_dict['signer'] = signer + + param = urllib.parse.urlencode(my_dict) + print(param) + typed_data['message']['msg'] = param + message = encode_structured_data(typed_data) + signed = Account.sign_message(message, private_key=private_key) + + url = url + '?' + param + '&signature=' + signed.signature.hex() + print(url) + res = requests.post(url, headers=headers) + + print(res.text) + +def send_by_body(api) : + my_dict = api['params'] + url = host +api['url'] + my_dict['nonce'] = str(get_nonce()) + my_dict['user'] = user + my_dict['signer'] = signer + + param = urllib.parse.urlencode(my_dict) + typed_data['message']['msg'] = param + message = encode_structured_data(typed_data) + + signed = Account.sign_message(message, private_key=private_key) + print(signed.signature.hex()) + + my_dict['signature'] = signed.signature.hex() + + print(my_dict) + res = requests.post(url, data=my_dict, headers=headers) + + print(res.text) + +if __name__ == '__main__': + send_by_url(place_order) + # send_by_body(place_order) + +``` + +## 公开 API 参数 +### 术语 + +这里的术语适用于全部文档,建议特别是新手熟读,也便于理解。 + +* `base asset` 指一个交易对的交易对象,即写在靠前部分的资产名, 比如`BTCUSDT`, `BTC`是`base asset`。 +* `quote asset` 指一个交易对的定价资产,即写在靠后部分的资产名, 比如`BTCUSDT`, `USDT`是`quote asset`。 + +### 枚举定义 +**交易对状态 (状态 status):** + +* TRADING 交易中 + + +**交易对类型:** + +* SPOT 现货 + +**订单状态 (状态 status):** + +状态 | 描述 +-----------| -------------- +`NEW` | 订单被交易引擎接受 +`PARTIALLY_FILLED`| 部分订单被成交 +`FILLED` | 订单完全成交 +`CANCELED` | 用户撤销了订单 +`REJECTED` | 订单没有被交易引擎接受,也没被处理 +`EXPIRED` | 订单被交易引擎取消, 比如
LIMIT FOK 订单没有成交
市价单没有完全成交
交易所维护期间被取消的订单 + + +**订单类型 (orderTypes, type):** + +* LIMIT 限价单 +* MARKET 市价单 +* STOP 限价止损单 +* TAKE_PROFIT 限价止盈单 +* STOP_MARKET 市价止损单 +* TAKE_PROFIT_MARKET 市价止盈单 + +**订单返回类型 (newOrderRespType):** + +* ACK +* RESULT +* FULL + +**订单方向 (方向 side):** + +* BUY 买入 +* SELL 卖出 + +**有效方式 (timeInForce):** + +这里定义了订单多久能够失效 + +Status | Description +-----------| -------------- +`GTC` | 成交为止
订单会一直有效,直到被成交或者取消。 +`IOC` | 无法立即成交的部分就撤销
订单在失效前会尽量多的成交。 +`FOK` | 无法全部立即成交就撤销
如果无法全部成交,订单会失效。 +`GTX` | 直到挂单成交
限价只挂单。 + +**K线间隔:** + +m -> 分钟; h -> 小时; d -> 天; w -> 周; M -> 月 + +* 1m +* 3m +* 5m +* 15m +* 30m +* 1h +* 2h +* 4h +* 6h +* 8h +* 12h +* 1d +* 3d +* 1w +* 1M + +**限制种类 (rateLimitType)** + +> REQUEST_WEIGHT +```json + { + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200 + } +``` + +> ORDERS +```json + { + "rateLimitType": "ORDERS", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 100 + } +``` + + +* REQUEST_WEIGHT 单位时间请求权重之和上限 + +* ORDERS 单位时间下单次数限制 + + +**限制间隔 (interval)** + +* MINUTE 分 + +--- +## 过滤器 +过滤器,即Filter,定义了一系列交易规则。 +共有两类,分别是针对交易对的过滤器`symbol filters`,和针对整个交易所的过滤器`exchange filters`(暂不支持) + +### 交易对过滤器   + +#### PRICE_FILTER 价格过滤器 + +> **/exchangeInfo 响应中的格式:** +```javascript + { + "minPrice": "556.72", + "maxPrice": "4529764", + "filterType": "PRICE_FILTER", + "tickSize": "0.01"   + } +``` + +`价格过滤器` 用于检测订单中 `price` 参数的合法性。包含以下三个部分: + +* `minPrice` 定义了 `price`/`stopPrice` 允许的最小值。 +* `maxPrice` 定义了 `price`/`stopPrice` 允许的最大值。 +* `tickSize` 定义了 `price`/`stopPrice` 的步进间隔,即price必须等于minPrice+(tickSize的整数倍) + +以上每一项均可为0,为0时代表这一项不再做限制。 + +逻辑伪代码如下: + +* `price` >= `minPrice` +* `price` <= `maxPrice` +* (`price`-`minPrice`) % `tickSize` == 0 + + +#### PERCENT_PRICE 价格振幅过滤器 + +> **/exchangeInfo 响应中的格式:** +```javascript + { + "multiplierDown": "0.9500", + "multiplierUp": "1.0500", + "multiplierDecimal": "4", + "filterType": "PERCENT_PRICE" +  } +``` + +`PERCENT_PRICE`过滤器基于指数价格来定义价格的有效范围。 + +为了通过"价格百分比","价格"必须符合以下条件: + +* `price` <=`indexPrice` *`multiplierUp` +* `price`> =`indexPrice` *`multiplierDown` + + +#### LOT_SIZE 订单尺寸 + +> **/exchangeInfo 响应中的格式:** +```javascript + { + "stepSize": "0.00100000", +   "filterType": "LOT_SIZE", + "maxQty": "100000.00000000", +   "minQty": "0.00100000" + } +``` + +Lots是拍卖术语,`LOT_SIZE` 过滤器对订单中的 `quantity` 也就是数量参数进行合法性检查。包含三个部分: + +* `minQty` 表示 `quantity` 允许的最小值。 +* `maxQty` 表示 `quantity` 允许的最大值。 +* `stepSize` 表示 `quantity` 允许的步进值。 + +逻辑伪代码如下: + +* `quantity` >= `minQty` +* `quantity` <= `maxQty` +* (`quantity`-`minQty`) % `stepSize` == 0 + + + + +#### MARKET_LOT_SIZE 市价订单尺寸 + +> ***/exchangeInfo 响应中的格式:** +```javascript + { + "stepSize": "0.00100000", +   "filterType": "MARKET_LOT_SIZE" + "maxQty": "100000.00000000", + "minQty": "0.00100000" + } +``` + + +`MARKET_LOT_SIZE`过滤器为交易对上的`MARKET`订单定义了`数量`(即拍卖中的"手数")规则。 共有3部分: + +* `minQty`定义了允许的最小`quantity`。 +* `maxQty`定义了允许的最大数量。 +* `stepSize`定义了可以增加/减少数量的间隔。 + +为了通过`market lot size`,`quantity`必须满足以下条件: + +* `quantity` >= `minQty` +* `quantity` <= `maxQty` +* (`quantity`-`minQty`) % `stepSize` == 0 + + + + + + + + + + +# 行情接口 +## 测试服务器连通性 +> **响应** +```javascript +{} +``` +`` +GET /api/v3/ping +`` + +测试能否联通 Rest API。 + +**权重:** +1 + +**参数:** +NONE + + +## 获取服务器时间 +> **响应** +```javascript +{ + "serverTime": 1499827319559 +} +``` +`` +GET /api/v3/time +`` + +测试能否联通 Rest API 并获取服务器时间。 + +**权重:** +1 + +**参数:** +NONE + + +## 交易规范信息 + +> **响应** + +```javascript     +{ + "timezone": "UTC", + "serverTime": 1756197279679, + "rateLimits": [{ + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 6000 + }, + { + "rateLimitType": "ORDERS", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 6000 + }, + { + "rateLimitType": "ORDERS", + "interval": "SECOND", + "intervalNum": 10, + "limit": 300 + } + ], + "exchangeFilters": [], + "assets": [{ + "asset": "USD" + }, { + "asset": "USDT" + }, + { + "asset": "BNB" + } + ], + "symbols": [{ + "status": "TRADING", + "baseAsset": "BNB", + "quoteAsset": "USDT", + "pricePrecision": 8, + "quantityPrecision": 8, + "baseAssetPrecision": 8, + "quotePrecision": 8, + "filters": [{ + "minPrice": "0.01000000", + "maxPrice": "100000", + "filterType": "PRICE_FILTER", + "tickSize": "0.01000000" + }, + { + "stepSize": "0.00100000", + "filterType": "LOT_SIZE", + "maxQty": "1000", + "minQty": "1" + }, + { + "stepSize": "0.00100000", + "filterType": "MARKET_LOT_SIZE", + "maxQty": "900000", + "minQty": "0.00100000" + }, + { + "limit": 200, + "filterType": "MAX_NUM_ORDERS" + }, + { + "minNotional": "5", + "filterType": "MIN_NOTIONAL" + }, + { + "maxNotional": "100", + "filterType": "MAX_NOTIONAL" + }, + { + "maxNotional": "100", + "minNotional": "5", + "avgPriceMins": 5, + "applyMinToMarket": true, + "filterType": "NOTIONAL", + "applyMaxToMarket": true + }, + { + "multiplierDown": "0", + "multiplierUp": "5", + "multiplierDecimal": "0", + "filterType": "PERCENT_PRICE" + }, + { + "bidMultiplierUp": "5", + "askMultiplierUp": "5", + "bidMultiplierDown": "0", + "avgPriceMins": 5, + "multiplierDecimal": "0", + "filterType": "PERCENT_PRICE_BY_SIDE", + "askMultiplierDown": "0" + } + ], + "orderTypes": [ + "LIMIT", + "MARKET", + "STOP", + "STOP_MARKET", + "TAKE_PROFIT", + "TAKE_PROFIT_MARKET" + ], + "timeInForce": [ + "GTC", + "IOC", + "FOK", + "GTX" + ], + "symbol": "BNBUSDT", + "ocoAllowed": false + }] +} +``` + +`` +GET /api/v3/exchangeInfo +`` + +获取交易规则和交易对信息。 + +**权重:** +1 + +**参数:** +无 + + +## 深度信息 + +> **响应** + +```javascript +{ + "lastUpdateId": 1027024, + "E":1589436922972, // 消息时间 + "T":1589436922959, // 撮合引擎时间 + "bids": [ + [ + "4.00000000", // 价位 + "431.00000000" // 挂单量 + ] + ], + "asks": [ + [ + "4.00000200", + "12.00000000" + ] + ] +} +``` +`` +GET /api/v3/depth +`` + +**权重:** + +基于限制调整: + +限制 | 权重 +------------ | ------------ +5, 10, 20, 50 | 2 +100 | 5 +500 | 10 +1000 | 20 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +limit | INT | NO | 默认 100. 可选值:[5, 10, 20, 50, 100, 500, 1000] + + +## 近期成交列表 + +> **响应** + +```javascript +[ + { + "id": 657, + "price": "1.01000000", + "qty": "5.00000000", + "baseQty": "4.95049505", + "time": 1755156533943, + "isBuyerMaker": false + } +] +``` +`` +GET /api/v3/trades +`` + +获取近期成交 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +limit | INT | NO | 默认 500;最大1000 + + +## 查询历史成交 (MARKET_DATA) + +> **响应** + +```javascript +[ + { + "id": 1140, + "price": "1.10000000", + "qty": "7.27200000", + "baseQty": "6.61090909", + "time": 1756094288700, + "isBuyerMaker": false + } +] +``` +`` +GET /api/v3/historicalTrades +`` + +获取历史成交。 + +**权重:** +20 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +limit | INT | NO | 默认 500; 最大值 1000. +fromId | LONG | NO | 从哪一条成交id开始返回. 缺省返回最近的成交记录。 + + +## 近期成交(归集) + +> **响应** + +```javascript +[ + { + "a": 26129, // 归集成交ID + "p": "0.01633102", // 成交价 + "q": "4.70443515", // 成交量 + "f": 27781, // 被归集的首个成交ID + "l": 27781, // 被归集的末个成交ID + "T": 1498793709153, // 成交时间 + "m": true, // 是否为主动卖出单 + } +] +``` +`` +GET /api/v3/aggTrades +`` + +归集交易与逐笔交易的区别在于,同一价格、同一方向、同一时间的trade会被聚合为一条 + +**权重:** +20 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +fromId | LONG | NO | 从包含fromId的成交id开始返回结果 +startTime | LONG | NO | 从该时刻之后的成交记录开始返回结果 +endTime | LONG | NO | 返回该时刻为止的成交记录 +limit | INT | NO | 默认 500; 最大 1000. +* 如果发送startTime和endTime,间隔必须小于一小时。 +* 如果没有发送任何筛选参数(fromId, startTime,endTime),默认返回最近的成交记录 + + +## K线数据 + +> **响应** +```javascript +[ + [ + 1499040000000, // 开盘时间 + "0.01634790", // 开盘价 + "0.80000000", // 最高价 + "0.01575800", // 最低价 + "0.01577100", // 收盘价(当前K线未结束的即为最新价) + "148976.11427815", // 成交量 + 1499644799999, // 收盘时间 + "2434.19055334", // 成交额 + 308, // 成交笔数 + "1756.87402397", // 主动买入成交量 + "28.46694368", // 主动买入成交额 + ] +] +``` +`` +GET /api/v3/klines +`` + +每根K线代表一个交易对。 +每根K线的开盘时间可视为唯一ID + + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +interval | ENUM | YES | 详见枚举定义:K线间隔 +startTime | LONG | NO | +endTime | LONG | NO | +limit | INT | NO | 默认 500; 最大 1500. +* 如果未发送 startTime 和 endTime ,默认返回最近的交易。 + + + +## 24hr 价格变动情况 + +> **响应** + +```javascript +{ + "symbol": "BTCUSDT", + "priceChange": "-94.99999800", //24小时价格变动 + "priceChangePercent": "-95.960", //24小时价格变动百分比 + "weightedAvgPrice": "0.29628482", //加权平均价 + "prevClosePrice": "3.89000000", //上一次结束价格 + "lastPrice": "4.00000200", //最近一次成交价 + "lastQty": "200.00000000", //最近一次成交额 + "bidPrice": "866.66000000", //最高的买入价格 + "bidQty": "72.05100000", //最高的买入价格的数量 + "askPrice": "866.73000000", //最低的卖出价 + "askQty": "1.21700000", //最低的卖出价格的数量 + "openPrice": "99.00000000", //24小时内第一次成交的价格 + "highPrice": "100.00000000", //24小时最高价 + "lowPrice": "0.10000000", //24小时最低价 + "volume": "8913.30000000", //24小时成交量 + "quoteVolume": "15.30000000", //24小时成交额 + "openTime": 1499783499040, //24小时内,第一笔交易的发生时间 + "closeTime": 1499869899040, //24小时内,最后一笔交易的发生时间 + "firstId": 28385, // 首笔成交id + "lastId": 28460, // 末笔成交id + "count": 76, // 成交笔数 + "baseAsset": "BTC", //基础代币 + "quoteAsset": "USDT" //报价代币 +} +``` + +`` +GET /api/v3/ticker/24hr +`` + +24 小时滚动窗口价格变动数据。 请注意,不携带symbol参数会返回全部交易对数据,此时返回的数据为示例相应的数组,不仅数据庞大,而且权重极高 + +**权重:** +1 单一交易对; +**40** 交易对参数缺失; + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | NO | +* 请注意,不携带symbol参数会返回全部交易对数据 + +## 最新价格 + +> **响应** + +```javascript +{ + "symbol": "ADAUSDT", + "price": "1.30000000", + "time": 1649666690902 +} +``` + +> OR + +```javascript +[ + { + "symbol": "ADAUSDT", + "price": "1.30000000", + "time": 1649666690902 + } +] +``` + +`` +GET /api/v3/ticker/price +`` + +获取交易对最新价格 + +**权重:** +1 单一交易对; +**2** 交易对参数缺失; + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | NO | +* 不发送交易对参数,则会返回所有交易对信息 + + +## 当前最优挂单 +> **响应** +```javascript +{ + "symbol": "LTCBTC", + "bidPrice": "4.00000000", + "bidQty": "431.00000000", + "askPrice": "4.00000200", + "askQty": "9.00000000" + "time": 1589437530011 // 交易时间 +} +``` +> OR +```javascript +[ + { + "symbol": "LTCBTC", + "bidPrice": "4.00000000", + "bidQty": "431.00000000", + "askPrice": "4.00000200", + "askQty": "9.00000000", + "time": 1589437530011 // 交易时间 + } +] +``` + +`` +GET /api/v3/ticker/bookTicker +`` + +返回当前最优的挂单(最高买单,最低卖单) + +**权重:** +1 单一交易对; +**2** 交易对参数缺失; + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | NO | +* 不发送交易对参数,则会返回所有交易对信息 + +## 获取Symbol手续费 + +> **响应** + +```javascript +{ + "symbol": "APXUSDT", + "makerCommissionRate": "0.000200",     + "takerCommissionRate": "0.000700" +} +``` +`` +GET /api/v3/commissionRate +`` + +获取Symbol手续费。 + +**权重:** +20 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +recvWindow | LONG | NO |赋值不能大于 ```60000``` +timestamp | LONG | YES | + + + + + +# 现货账户和交易接口 + + +## 下单 (TRADE) + +> **Response ACK:** + +```javascript +{ + "symbol": "BTCUSDT", // 交易对 + "orderId": 28, // 系统的订单ID + "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP", // 客户自己设置的ID + "updateTime": 1507725176595, // 交易的时间戳 + "price": "0.00000000", // 订单价格 + "avgPrice": "0.0000000000000000", //平均价格 + "origQty": "10.00000000", // 用户设置的原始订单数量 + "cumQty": "0", //累计数量 + "executedQty": "10.00000000", // 交易的订单数量 + "cumQuote": "10.00000000", // 累计交易的金额 + "status": "FILLED", // 订单状态 + "timeInForce": "GTC", // 订单的时效方式 + "stopPrice": "0", //触发价格 + "origType": "LIMIT", //触发前订单类型 + "type": "LIMIT", // 订单类型, 比如市价单,现价单等 + "side": "SELL", // 订单方向,买还是卖 +} +``` + +`` +POST /api/v3/order (HMAC SHA256) +`` + +发送下单。 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +side | ENUM | YES | 详见枚举定义:订单方向 +type | ENUM | YES | 详见枚举定义:订单类型 +timeInForce | ENUM | NO | 详见枚举定义:有效方式 +quantity | DECIMAL | NO | +quoteOrderQty|DECIMAL|NO| +price | DECIMAL | NO | +newClientOrderId | STRING | NO | 客户自定义的唯一订单ID。 如果未发送,则自动生成 +stopPrice | DECIMAL | NO | 仅 `STOP`, `STOP_MARKET` , `TAKE_PROFIT`,`TAKE_PROFIT_MARKET` 需要此参数。 +recvWindow | LONG | NO |赋值不能大于 ```60000``` +timestamp | LONG | YES | + +基于订单 `type`不同,强制要求某些参数: + +类型 | 强制要求的参数 +------------ | ------------ +`LIMIT` | `timeInForce`, `quantity`, `price` +`MARKET` | `quantity` 或 `quoteOrderQty` +`STOP`和`TAKE_PROFIT` | `quantity`, `price`, `stopPrice` +`STOP_MARKET`和`TAKE_PROFIT_MARKET` | `quantity`, `stopPrice` + +其他信息: + +* 下`MARKET` `SELL`市价单,用户通过`QUANTITY`控制想用市价单卖出的基础资产数量。 + * 比如在`BTCUSDT`交易对上下一个`MARKET` `SELL`市价单, 通过`QUANTITY`让用户指明想卖出多少BTC。 +* 下`MARKET` `BUY`的市价单,用户使用 `quoteOrderQty` 控制想用市价单买入的报价资产数量,`QUANTITY`将由系统根据市场流动性计算出来。 +  * 比如在`BTCUSDT`交易对上下一个`MARKET` `BUY`市价单, 通过`quoteOrderQty`让用户选择想使用多少USDT买入BTC。 +* 使用 `quoteOrderQty` 的市价单`MARKET`不会突破`LOT_SIZE`的限制规则; 报单会按给定的`quoteOrderQty`尽可能接近地被执行。 +* 除非之前的订单已经成交, 不然设置了相同的`newClientOrderId`订单会被拒绝。 + + + +## 撤销订单 (TRADE) + +> **响应** + +```javascript +{ + "symbol": "BTCUSDT", // 交易对 + "orderId": 28, // 系统的订单ID + "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP", // 客户自己设置的ID + "updateTime": 1507725176595, // 交易的时间戳 + "price": "0.00000000", // 订单价格 + "avgPrice": "0.0000000000000000", //平均价格 + "origQty": "10.00000000", // 用户设置的原始订单数量 + "cumQty": "0", //累计数量 + "executedQty": "10.00000000", // 交易的订单数量 + "cumQuote": "10.00000000", // 累计交易的金额 + "status": "CANCELED", // 订单状态 + "timeInForce": "GTC", // 订单的时效方式 + "stopPrice": "0", //触发价格 + "origType": "LIMIT", //触发前订单类型 + "type": "LIMIT", // 订单类型, 比如市价单,现价单等 + "side": "SELL", // 订单方向,买还是卖 +} +``` + +`` +DELETE /api/v3/order (HMAC SHA256) +`` + +取消有效订单。 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +orderId | LONG | NO | +origClientOrderId | STRING | NO | +recvWindow | LONG | NO | +timestamp | LONG | YES | + +`orderId` 或 `origClientOrderId` 必须至少发送一个 + +## 查询订单 (USER_DATA) + +> **响应** +```javascript +{ + "orderId": 38,   // 系统订单号 + "symbol": "ADA25SLP25",  // 交易对 + "status": "FILLED",  // 订单状态 + "clientOrderId": "afMd4GBQyHkHpGWdiy34Li",  // 用户自定义的订单号 + "price": "20",  // 委托价格 + "avgPrice": "12.0000000000000000",  // 平均成交价 + "origQty": "10",  // 原始委托数量 + "executedQty": "10",  // 成交量 + "cumQuote": "120",  // 成交金额 + "timeInForce": "GTC",  // 有效方法 + "type": "LIMIT",  // 订单类型 + "side": "BUY",  // 买卖方向 + "stopPrice": "0",  // 触发价 + "origType": "LIMIT",  // 触发前订单类型 + "time": 1649913186270,  // 订单时间 + "updateTime": 1649913186297  // 更新时间 +} +``` + +`` +GET /api/v3/order (HMAC SHA256) +`` + +查询订单状态。 + +* 请注意,如果订单满足如下条件,不会被查询到: + * 订单的最终状态为 `CANCELED` 或者 `EXPIRED`, **并且** + * 订单没有任何的成交记录, **并且** + * 订单生成时间 + 7天 < 当前时间 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +orderId | LONG | NO | +origClientOrderId | STRING | NO | +recvWindow | LONG | NO | +timestamp | LONG | YES | + +注意: + +* 至少需要发送 `orderId` 与 `origClientOrderId`中的一个 + + +## 查询当前挂单 (USER_DATA) + +> **响应** +```javascript +{ + "orderId": 38,   // 系统订单号 + "symbol": "ADA25SLP25",  // 交易对 + "status": "NEW",  // 订单状态 + "clientOrderId": "afMd4GBQyHkHpGWdiy34Li",  // 用户自定义的订单号 + "price": "20",  // 委托价格 + "avgPrice": "12.0000000000000000",  // 平均成交价 + "origQty": "10",  // 原始委托数量 + "executedQty": "10",  // 成交量 + "cumQuote": "120",  // 成交金额 + "timeInForce": "GTC",  // 有效方法 + "type": "LIMIT",  // 订单类型 + "side": "BUY",  // 买卖方向 + "stopPrice": "0",  // 触发价 + "origType": "LIMIT",  // 触发前订单类型 + "time": 1649913186270,  // 订单时间 + "updateTime": 1649913186297  // 更新时间 +} +``` + +`` +GET /api/v3/openOrder (HMAC SHA256) +`` + +查询订单状态。 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +orderId | LONG | NO | +origClientOrderId | STRING | NO | +recvWindow | LONG | NO | +timestamp | LONG | YES | + +注意: + +* 至少需要发送 `orderId` 与 `origClientOrderId`中的一个 + + +## 当前所有挂单 (USER_DATA) + +> **响应** + +```javascript +[ + { + "orderId": 349661, // 系统订单号 + "symbol": "BNBUSDT", // 交易对 + "status": "NEW", // 订单状态 + "clientOrderId": "LzypgiMwkf3TQ8wwvLo8RA", // 用户自定义的订单号 + "price": "1.10000000", // 委托价格 + "avgPrice": "0.0000000000000000", // 平均成交价 + "origQty": "5",  // 原始委托数量 + "executedQty": "0", // 成交量 + "cumQuote": "0", // 成交金额 + "timeInForce": "GTC", // 有效方法 + "type": "LIMIT", // 订单类型 + "side": "BUY", // 买卖方向 + "stopPrice": "0", // 触发价 + "origType": "LIMIT", // 触发前订单类型 + "time": 1756252940207, // 订单时间 + "updateTime": 1756252940207, // 更新时间 + } +] +``` + +`` +GET /api/v3/openOrders (HMAC SHA256) +`` + +获取交易对的所有当前挂单, 请小心使用不带交易对参数的调用。 + +**权重:** +- 带symbol ***1*** +- 不带 ***40***   + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | NO | +recvWindow | LONG | NO | +timestamp | LONG | YES | + +* 不带symbol参数,会返回所有交易对的挂单 + + + +## 取消当前所有挂单 (USER_DATA) + +> **响应** + +```javascript +{ + "code": 200, + "msg": "The operation of cancel all open order is done." +} +``` + +`` +DEL /api/v3/allOpenOrders (HMAC SHA256) +`` + +**权重:** +- ***1*** + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +orderIdList | STRING | NO | id数组字符串 +origClientOrderIdList | STRING | NO | clientOrderId数组字符串 +recvWindow | LONG | NO | +timestamp | LONG | YES | + + +## 查询所有订单 (USER_DATA) +> **响应** +```javascript +[ + { + "orderId": 349661, // 系统订单号 + "symbol": "BNBUSDT", // 交易对 + "status": "NEW", // 订单状态 + "clientOrderId": "LzypgiMwkf3TQ8wwvLo8RA", // 用户自定义的订单号 + "price": "1.10000000", // 委托价格 + "avgPrice": "0.0000000000000000", // 平均成交价 + "origQty": "5",  // 原始委托数量 + "executedQty": "0", // 成交量 + "cumQuote": "0", // 成交金额 + "timeInForce": "GTC", // 有效方法 + "type": "LIMIT", // 订单类型 + "side": "BUY", // 买卖方向 + "stopPrice": "0", // 触发价 + "origType": "LIMIT", // 触发前订单类型 + "time": 1756252940207, // 订单时间 + "updateTime": 1756252940207, // 更新时间 + } +] +``` + +`` +GET /api/v3/allOrders (HMAC SHA256) +`` + +获取所有帐户订单; 有效,已取消或已完成。 + +* 请注意,如果订单满足如下条件,不会被查询到: + * 订单生成时间 + 7天 < 当前时间 + +**权重:** +5 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +orderId | LONG | NO | +startTime | LONG | NO | +endTime | LONG | NO | +limit | INT | NO | 默认 500; 最大 1000. +recvWindow | LONG | NO | +timestamp | LONG | YES |   + +* 查询时间范围最大不得超过7天 +* 默认查询最近7天内的数据 + + + +`` +GET /api/v3/transactionHistory (HMAC SHA256) +`` +> **响应** + +```javascript +[ + { + "tranId": 1759115482304540227, //划转ID + "tradeId": null, //流水ID + "asset": "ASTER", //资产 + "symbol": "", //交易对 + "balanceDelta": "-500.00000000", //资金流数量,正数代表流入,负数代表流出 + "balanceInfo": "TRADE_SOURCE", //流水描述 + "time": 1759115482000, // 时间 + "type": "TRADE_SOURCE" //资金流类型 + } +] +``` + +查询交易流水 + +**权重:** +30 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +asset | STRING | NO | 资产 +type | STRING | NO | 类别 +startTime | LONG | NO | 开始时间 +endTime | LONG | NO | 结束时间 +limit | LONG | NO | 返回的结果集数量 默认值:100 最大值:1000 +recvWindow | LONG | NO | +timestamp | LONG | YES | + +注意: + +* `type` 取值 `TRADE_TARGET`,`TRADE_SOURCE`,`TRANSFER_SPOT_TO_FUTURE`,`TRANSFER_FUTURE_TO_SPOT`,`TRANSFER_SPOT_TO_SPOT`,`AIRDROP`,`DIVIDEND`,`TRANSFER_REFUND`,`INTERNAL_TRANSFER`,`TRANSFER`,`SWAP`,`COMMISSION_REBATE`,`CASH_BACK` 中的一种 +* 如果`startTime` 和 `endTime` 均未发送, 只会返回最近7天的数据。 + +## 期货现货互转 (TRADE) + +> **响应:** + +```javascript +{ + "tranId": 21841, //交易id + "status": "SUCCESS" //状态 +} +``` + +`` +POST /api/v3/asset/wallet/transfer (HMAC SHA256) +`` + +**权重:** +5 + +**参数:** + + +名称 | 类型 | 是否必需 | 描述 +---------------- | ------- | -------- | ---- +amount | DECIMAL | YES | 数量 +asset | STRING | YES | 资产 +clientTranId | STRING | YES | 交易id +kindType | STRING | YES | 交易类型 +recvWindow | LONG | NO | +timestamp | LONG | YES | 时间戳 + +注意: +* kindType 取值为FUTURE_SPOT(期货转现货),SPOT_FUTURE(现货转期货) + +## 现货提现手续费 (NONe) +> **响应** +```javascript +{ + "tokenPrice": 1.00019000, + "gasCost": 0.5000, + "gasUsdValue": 0.5 +} +``` + +`` +GET /api/v3/aster/withdraw/estimateFee +`` + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +chainId | STRING | YES | +asset | STRING | YES | + +注意: +* chainId: 1(ETH),56(BSC),42161(Arbi) +* gasCost: 提现所需的最少数量的手续费 + +## 现货提现 (USER_DATA) +> **响应** +```javascript +{ + "withdrawId": "1014729574755487744", + "hash":"0xa6d1e617a3f69211df276fdd8097ac8f12b6ad9c7a49ba75bbb24f002df0ebb" +} +``` + +`` +POST /api/v3/aster/user-withdraw (HMAC SHA256) +`` + +**权重:** +5 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +chainId | STRING | YES | +asset | STRING | YES | +amount | STRING | YES | +fee | STRING | YES | +receiver | STRING | YES | +nonce | STRING | YES | 当前时间的微秒值 +userSignature | STRING | YES | +recvWindow | LONG | NO | +timestamp | LONG | YES | + +注意: +* chainId: 1(ETH),56(BSC),42161(Arbi) +* receiver : 当前账户的地址 +* 如果期货余额不足,会从spot账户划转到期货账户,进行提现 +* userSignature demo + +```shell +const domain = { + name: 'Aster', + version: '1', + chainId: 56, + verifyingContract: ethers.ZeroAddress, + } + +const currentTime = Date.now() * 1000 + +const types = { + Action: [ + {name: "type", type: "string"}, + {name: "destination", type: "address"}, + {name: "destination Chain", type: "string"}, + {name: "token", type: "string"}, + {name: "amount", type: "string"}, + {name: "fee", type: "string"}, + {name: "nonce", type: "uint256"}, + {name: "aster chain", type: "string"}, + ], + } + const value = { + 'type': 'Withdraw', + 'destination': '0xD9cA6952F1b1349d27f91E4fa6FB8ef67b89F02d', + 'destination Chain': 'BSC', + 'token': 'USDT', + 'amount': '10.123400', + 'fee': '1.234567891', + 'nonce': currentTime, + 'aster chain': 'Mainnet', + } + + +const signature = await signer.signTypedData(domain, types, value) +``` + +## 获取创建apikey nonce (NONE) +> **响应** +```javascript + +111111 + +``` + +`` +POST /api/v3/getNonce +`` + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +address | STRING | YES | +userOperationType | STRING | YES | CREATE_API_KEY +network | STRING | NO | + +注意: +* userOperationType 仅可取值: CREATE_API_KEY +* network: sol网络必须传入SOL,其他忽略 +* 限流单IP一分钟60次 + + +## 创建apikey (NONE) +> **响应** +```javascript +{ + "apiKey": "bb3b24d0a3dec88cb06be58a257e4575cb0b1bb256ad6fd90ae8fd0ee1d102ae", + "apiSecret": "9fe8f5642ae1961674ea0cb7f957fa99dc8e0421b607c985a963ad2ced90ae1c" +} +``` + +`` +POST /api/v3/createApiKey +`` + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +address | STRING | YES | +userOperationType | STRING | YES | CREATE_API_KEY +network | STRING | NO | +userSignature | STRING | YES | +apikeyIP | STRING | NO | +desc | STRING | YES | +recvWindow | LONG | NO | +timestamp | LONG | YES | + +注意: +* userOperationType 仅可取值: CREATE_API_KEY +* network: sol网络必须传入SOL,其他忽略 +* desc: 同一账户不能重复,长度不能超过20个字符 +* apikeyIP ip数组以,分隔 +* 限流单IP一分钟60次 +* userSignature evm demo + +```shell + +const nonce = 111111 +const message = 'You are signing into Astherus ${nonce}' ; + +const signature = await signer.signMessage(message); +``` + + +## 账户信息 (USER_DATA) +> **响应** +```javascript +{ + "feeTier": 0, + "canTrade": true, + "canDeposit": true, + "canWithdraw": true, + "canBurnAsset": true, + "updateTime": 0, +   "balances": [ + { + "asset": "BTC", + "free": "4723846.89208129", + "locked": "0.00000000" + }, + { + "asset": "LTC", + "free": "4763368.68006011", + "locked": "0.00000000" + } + ] +} +``` + +`` +GET /api/v3/account (HMAC SHA256) +`` + +获取当前账户信息。 + +**权重:** +5 + +**参数:** + +名称 | 类型 | 是否必需| 描述 +------------ | ------------ | ------------ | ------------ +recvWindow | LONG | NO | +timestamp | LONG | YES | + + +## 账户成交历史 (USER_DATA) +> **响应** +```javascript +[ + { + "symbol": "BNBUSDT", + "id": 1002, + "orderId": 266358, + "side": "BUY", + "price": "1", + "qty": "2", + "quoteQty": "2", + "commission": "0.00105000", + "commissionAsset": "BNB", + "time": 1755656788798, + "counterpartyId": 19, + "createUpdateId": null, + "maker": false, + "buyer": true + } +] +``` + +`` +GET /api/v3/userTrades (HMAC SHA256) +`` + +获取账户指定交易对的成交历史 + +**权重:** +5 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | NO | +orderId|LONG|NO| 必须要和参数`symbol`一起使用. +startTime | LONG | NO | +endTime | LONG | NO | +fromId | LONG | NO | 起始Trade id。 默认获取最新交易。 +limit | INT | NO | 默认 500; 最大 1000. +recvWindow | LONG | NO | +timestamp | LONG | YES | + +* 如果`startTime` 和 `endTime` 均未发送, 只会返回最近7天的数据。 +* startTime 和 endTime 的最大间隔为7天 +* 不能同时传`fromId`与`startTime` 或 `endTime` +       + + + + +--- +# Websocket 行情推送 + +* 本篇所列出的所有wss接口的baseurl为: **wss://sstream.asterdex.com** +* Streams有单一原始 stream 或组合 stream +* 单一原始 streams 格式为 **/ws/\** +* 组合streams的URL格式为 **/stream?streams=\/\/\** +* 订阅组合streams时,事件payload会以这样的格式封装: **{"stream":"\","data":\}** +* stream名称中所有交易对均为 **小写** +* 每个到 **sstream.asterdex.com** 的链接有效期不超过24小时,请妥善处理断线重连。 +* 每3分钟,服务端会发送ping帧,客户端应当在10分钟内回复pong帧,否则服务端会主动断开链接。允许客户端发送不成对的pong帧(即客户端可以以高于10分钟每次的频率发送pong帧保持链接)。 + +## 实时订阅/取消数据流 + +* 以下数据可以通过websocket发送以实现订阅或取消订阅数据流。示例如下。 +* 响应内容中的`id`是无符号整数,作为往来信息的唯一标识。 +* 如果相应内容中的 `result` 为 `null`,表示请求发送成功。 + + +### 订阅一个信息流 +> **响应** + ```javascript + { + "result": null, + "id": 1 + } + ``` +* **请求** + { + "method": "SUBSCRIBE", + "params": + [ + "btcusdt@aggTrade", + "btcusdt@depth" + ], + "id": 1 + } + + +### 取消订阅一个信息流 + +> **响应** + + ```javascript + { + "result": null, + "id": 312 + } + ``` + +* **请求** + { + "method": "UNSUBSCRIBE", + "params": + [ + "btcusdt@depth" + ], + "id": 312 + } + + +### 已订阅信息流 + +> **响应** + + ```javascript + { + "result": [ + "btcusdt@aggTrade" + ], + "id": 3 + } + ``` + +* **请求** + + { + "method": "LIST_SUBSCRIPTIONS", + "id": 3 + } + + +### 设定属性 +当前,唯一可以设置的属性是设置是否启用`combined`("组合")信息流。 +当使用`/ws/`("原始信息流")进行连接时,combined属性设置为`false`,而使用 `/stream/`进行连接时则将属性设置为`true`。 + +> **响应** + + ```javascript +{ + "result": null, + "id": 5 +} + ``` + +* **请求** + { + "method": "SET_PROPERTY", + "params": + [ + "combined", + true + ], + "id": 5 + } + + +### 检索属性 + +> **响应** + ```javascript + { + "result": true, // Indicates that combined is set to true. + "id": 2 + } + ``` + +* **请求** + + { + "method": "GET_PROPERTY", + "params": + [ + "combined" + ], + "id": 2 + } + + +###错误信息 + +错误信息 | 描述 +---|--- +{"code": 0, "msg": "Unknown property"} | `SET_PROPERTY` 或 `GET_PROPERTY`中应用的参数无效 +{"code": 1, "msg": "Invalid value type: expected Boolean", "id": '%s'} | 仅接受`true`或`false` +{"code": 2, "msg": "Invalid request: property name must be a string"}| 提供的属性名无效 +{"code": 2, "msg": "Invalid request: request ID must be an unsigned integer"}| 参数`id`未提供或`id`值是无效类型 +{"code": 2, "msg": "Invalid request: unknown variant %s, expected one of `SUBSCRIBE`, `UNSUBSCRIBE`, `LIST_SUBSCRIPTIONS`, `SET_PROPERTY`, `GET_PROPERTY` at line 1 column 28"} | 错字提醒,或提供的值不是预期类型 +{"code": 2, "msg": "Invalid request: too many parameters"}| 数据中提供了不必要参数 +{"code": 2, "msg": "Invalid request: property name must be a string"} | 未提供属性名 +{"code": 2, "msg": "Invalid request: missing field `method` at line 1 column 73"} | 数据未提供`method` +{"code":3,"msg":"Invalid JSON: expected value at line %s column %s"} | JSON 语法有误. + + +## 归集交易流 + + +> **Payload:** +```javascript +{ + "e": "aggTrade", // 事件类型 + "E": 123456789, // 事件时间 + "s": "BNBBTC", // 交易对 + "a": 12345, // 归集交易ID + "p": "0.001", // 成交价格 + "q": "100", // 成交数量 + "f": 100, // 被归集的首个交易ID + "l": 105, // 被归集的末次交易ID + "T": 123456785, // 成交时间 + "m": true, // 买方是否是做市方。如true,则此次成交是一个主动卖出单,否则是一个主动买入单。 +} +``` + +归集交易 stream 推送交易信息,是对单一订单的集合。 + +**Stream 名称:** `@aggTrade` + +**Update Speed:** 实时 + + +## 逐笔交易 + + +> **Payload:** +```javascript +{ + "e": "trade", // 事件类型 + "E": 123456789, // 事件时间 + "s": "BNBBTC", // 交易对 + "t": 12345, // 交易ID + "p": "0.001", // 成交价格 + "q": "100", // 成交数量 + "T": 123456785, // 成交时间 + "m": true, // 买方是否是做市方。如true,则此次成交是一个主动卖出单,否则是一个主动买入单。 +} +``` + +**Stream Name:** `@trade` + +逐笔交易推送每一笔成交的信息。**成交**,或者说交易的定义是仅有一个吃单者与一个挂单者相互交易 + + +## K线 Streams +> **Payload:** +```javascript +{ + "e": "kline", // 事件类型 + "E": 123456789, // 事件时间 + "s": "BNBBTC", // 交易对 + "k": { + "t": 123400000, // 这根K线的起始时间 + "T": 123460000, // 这根K线的结束时间 + "s": "BNBBTC", // 交易对 + "i": "1m", // K线间隔 + "f": 100, // 这根K线期间第一笔成交ID + "L": 200, // 这根K线期间末一笔成交ID + "o": "0.0010", // 这根K线期间第一笔成交价 + "c": "0.0020", // 这根K线期间末一笔成交价 + "h": "0.0025", // 这根K线期间最高成交价 + "l": "0.0015", // 这根K线期间最低成交价 + "v": "1000", // 这根K线期间成交量 + "n": 100, // 这根K线期间成交笔数 + "x": false, // 这根K线是否完结(是否已经开始下一根K线) + "q": "1.0000", // 这根K线期间成交额 + "V": "500", // 主动买入的成交量 + "Q": "0.500", // 主动买入的成交额 + "B": "123456" // 忽略此参数 + } +} +``` + +K线stream逐秒推送所请求的K线种类(最新一根K线)的更新。 + +**Stream Name:** `@kline_` + +**Update Speed:** 2000ms + +**K线图间隔参数:** + +m -> 分钟; h -> 小时; d -> 天; w -> 周; M -> 月 + +* 1m +* 3m +* 5m +* 15m +* 30m +* 1h +* 2h +* 4h +* 6h +* 8h +* 12h +* 1d +* 3d +* 1w +* 1M + + +## 按 Symbol 的精简Ticker + +> **Payload:** +```javascript + { + "e": "24hrMiniTicker", // 事件类型 + "E": 123456789, // 事件时间 + "s": "BNBBTC", // 交易对 + "c": "0.0025", // 最新成交价格 + "o": "0.0010", // 24小时前开始第一笔成交价格 + "h": "0.0025", // 24小时内最高成交价 + "l": "0.0010", // 24小时内最低成交价 + "v": "10000", // 成交量 + "q": "18" // 成交额 + } +``` + +按Symbol刷新的最近24小时精简ticker信息 + +**Stream 名称:** `@miniTicker` + +**Update Speed:** 1000ms + + +## 全市场所有Symbol的精简Ticker + +> **Payload:** +```javascript +[ + { + // 数组每一个元素对应一个交易对,内容与 \@miniTicker相同 + } +] +``` + +同上,只是推送所有交易对.需要注意的是,只有更新的ticker才会被推送. + +**Stream名称:** !miniTicker@arr + +**Update Speed:** 1000ms + +## 按Symbol的完整Ticker + +> **Payload:** +```javascript +{ + "e": "24hrTicker", // 事件类型 + "E": 123456789, // 事件时间 + "s": "BNBBTC", // 交易对 + "p": "0.0015", // 24小时价格变化 + "P": "250.00", // 24小时价格变化(百分比) + "w": "0.0018", // 平均价格 + "c": "0.0025", // 最新成交价格 + "Q": "10", // 最新成交交易的成交量 + "o": "0.0010", // 整整24小时前,向后数的第一次成交价格 + "h": "0.0025", // 24小时内最高成交价 + "l": "0.0010", // 24小时内最低成交价 + "v": "10000", // 24小时内成交量 + "q": "18", // 24小时内成交额 + "O": 0, // 统计开始时间 + "C": 86400000, // 统计结束时间 + "F": 0, // 24小时内第一笔成交交易ID + "L": 18150, // 24小时内最后一笔成交交易ID + "n": 18151 // 24小时内成交数 +} +``` + +每秒推送单个交易对的过去24小时滚动窗口标签统计信息。 + +**Stream 名称:** `@ticker` + +**Update Speed:** 1000ms + +## 全市场所有交易对的完整Ticker + +> **Payload:** +```javascript +[ + { + // Same as @ticker payload + } +] +``` + +推送全市场所有交易对刷新的24小时完整ticker信息。需要注意的是,没有更新的ticker不会被推送。 + +**Stream Name:** `!ticker@arr` + +**Update Speed:** 1000ms + + +## 按Symbol的最优挂单信息 + +> **Payload:** +```javascript +{ + "u":400900217, // order book updateId + "s":"BNBUSDT", // 交易对 + "b":"25.35190000", // 买单最优挂单价格 + "B":"31.21000000", // 买单最优挂单数量 + "a":"25.36520000", // 卖单最优挂单价格 + "A":"40.66000000" // 卖单最优挂单数量 +} +``` + +实时推送指定交易对最优挂单信息 + +**Stream Name:** `@bookTicker` + +**Update Speed:** 实时 + +## 全市场最优挂单信息 +> **Payload:** +```javascript +{ + // 同 @bookTicker payload +} +``` + +实时推送所有交易对最优挂单信息 + +**Stream Name:** `!bookTicker` + +**Update Speed:** 实时 + + +## 有限档深度信息 + +> **Payload:** +```javascript +{ + "e": "depthUpdate", // Event type + "E": 123456789, // Event time + "T": 123456788, // Transaction time + "s": "BTCUSDT", // Symbol + "U": 100, // First update ID in event + "u": 120, // Final update ID in event + "pu": 99, // Final update Id in last stream(ie `u` in last stream) +  "bids": [ // Bids to be updated + [ + "0.0024", // Price level to be updated + "10" // Quantity + ] + ], + "asks": [ // Asks to be updated + [ + "0.0026", // Price level to be updated + "100" // Quantity + ] + ] +} +``` + +每秒或每100毫秒推送有限档深度信息。levels表示几档买卖单信息, 可选 5/10/20档 + +**Stream Names:** `@depth` 或 `@depth@100ms`. + +**Update Speed:** 1000ms 或 100ms + + +## 增量深度信息 +> **Payload:** +```javascript +{ + "e": "depthUpdate", // Event type + "E": 123456789, // Event time + "T": 123456788, // Transaction time + "s": "BTCUSDT", // Symbol + "U": 100, // First update ID in event + "u": 120, // Final update ID in event + "pu": 99, // Final update Id in last stream(ie `u` in last stream) + "b": [ // Bids to be updated + [ + "5.4", // Price level to be updated + "10" // Quantity + ] + ], + "a": [ // Asks to be updated + [ + "5.6", // Price level to be updated + "100" // Quantity + ] + ] +} +``` + +每秒或每100毫秒推送orderbook的变化部分(如果有) + +**Stream Name:** `@depth` 或 `@depth@100ms` + +**Update Speed:** 1000ms 或 100ms + +## 如何正确在本地维护一个orderbook副本 +1. 订阅 **wss://sstream.asterdex.com/ws/bnbbtc@depth** +2. 开始缓存收到的更新。同一个价位,后收到的更新覆盖前面的。 +3. 访问Rest接口 **https://sapi.asterdex.com/api/v3/depth?symbol=BNBBTC&limit=1000** 获得一个1000档的深度快照 +4. 将目前缓存到的信息中`u` <= 步骤3中获取到的快照中的`lastUpdateId`的部分丢弃(丢弃更早的信息,已经过期)。 +5. 将深度快照中的内容更新到本地orderbook副本中,并从websocket接收到的第一个`U` <= `lastUpdateId`+1 **且** `u` >= `lastUpdateId`+1 的event开始继续更新本地副本。 +6. 每一个新event的`U`应该恰好等于上一个event的`u`+1,否则可能出现了丢包,请从step3重新进行初始化。 +7. 每一个event中的挂单量代表这个价格目前的挂单量**绝对值**,而不是相对变化。 +8. 如果某个价格对应的挂单量为0,表示该价位的挂单已经撤单或者被吃,应该移除这个价位。 + + + + + + +# Websocket账户信息推送 + +* 本篇所列出API接口的base url : **https://sapi.asterdex.com** +* 用于订阅账户数据的 `listenKey` 从创建时刻起有效期为60分钟 +* 可以通过 `PUT` 一个 `listenKey` 延长60分钟有效期 +* 可以通过`DELETE`一个 `listenKey` 立即关闭当前数据流,并使该`listenKey` 无效 +* 在具有有效`listenKey`的帐户上执行`POST`将返回当前有效的`listenKey`并将其有效期延长60分钟 +* websocket接口的baseurl: **wss://sstream.asterdex.com** +* U订阅账户数据流的stream名称为 **/ws/\** +* 每个链接有效期不超过24小时,请妥善处理断线重连。 + + +## Listen Key(现货账户) + +### 生成 Listen Key (USER_STREAM) + +> **响应** +```javascript +{ + "listenKey": "pqia91ma19a5s61cv6a81va65sdf19v8a65a1a5s61cv6a81va65sdf19v8a65a1" +} +``` + +`` +POST /api/v3/listenKey +`` + +开始一个新的数据流。除非发送 keepalive,否则数据流于60分钟后关闭。如果该帐户具有有效的`listenKey`,则将返回该`listenKey`并将其有效期延长60分钟。 + +**权重:** +1 + +**参数:** +NONE + +### 延长 Listen Key 有效期 (USER_STREAM) + +> **响应** +```javascript +{} +``` + +`` +PUT /api/v3/listenKey +`` + +有效期延长至本次调用后60分钟,建议每30分钟发送一个 ping 。 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +listenKey | STRING | YES + + +### 关闭 Listen Key (USER_STREAM) + +> **响应** +```javascript +{} +``` + +`` +DELETE /api/v3/listenKey +`` + +关闭用户数据流。 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +listenKey | STRING | YES + + +## Payload: 账户更新 + +每当帐户余额发生更改时,都会发送一个事件`outboundAccountPosition`,其中包含可能由生成余额变动的事件而变动的资产。 + +> **Payload** +```javascript +{ + "B":[// 余额 + { + "a":"SLP25",   // 资产名称 + "f":"10282.42029415",   // 可用余额 + "l":"653.00000001"   // 冻结余额 + }, + { + "a":"ADA25", + "f":"9916.96229880", + "l":"34.00510000" + } + ], + "e":"outboundAccountPosition",   // 事件类型 + "T":1649926447190,   // 账户末次更新时间戳 + "E":1649926447205   // 事件时间 + "m":"WITHDRAW" // 事件推出原因 +} +``` + + +## Payload: 订单更新 + +订单通过`executionReport`事件进行更新。 + +> **Payload** + +```javascript +{ + "s":"ADA25SLP25",   // 交易对 + "c":"Xzh0gnxT41PStbwqOtXnjD",  // 客户端自定订单ID + "S":"SELL",   // 订单方向 + "o":"LIMIT",   // 订单类型 + "f":"GTC",   // 有效方式 + "q":"10.001000",   // 订单原始数量 + "p":"19.1000000000",   // 订单原始价格 + "ap":"19.0999999955550656", //平均价格 + "P":"0",  // 条件订单触发价格 + "x":"TRADE",   // 本次事件的具体执行类型 + "X":"PARTIALLY_FILLED",   // 订单的当前状态 + "i":27,   // 订单ID + "l":"1",     // 订单末次成交量 + "z":"8.999000",   // 订单累计已成交量 + "L":"19.1000000000",   // 订单末次成交价格 + "n":"0.00382000",   // 手续费数量 + "N":"SLP25",   // 手续费资产类型 + "T":1649926447190,   // 成交时间 + "t":18,   // 成交ID + "m":true,   // 该成交是作为挂单成交吗? + "ot":"LIMIT", //初始订单类型 + "O":0,   // 订单时间 + "Z":"171.88089996",   // 累计报价资产交易数量 + "Y":"19.1000000000000000",   // 最近报价交易数量 + "Q":"0",   // 报价数量 + "e":"executionReport",   // 事件类型 + "E":1649926447209  // 事件时间 +} +``` + + +**执行类型:** +* NEW 新订单 +* CANCELED 订单被取消 +* REJECTED 新订单被拒绝 +* TRADE 订单有新成交 +* EXPIRED 订单失效(根据订单的Time In Force参数) + + + + + + +#错误代码 + +> error JSON payload: + +```javascript +{ + "code":-1121, + "msg":"Invalid symbol." +} +``` + +错误由两部分组成:错误代码和消息。 代码是通用的,但是消息可能会有所不同。 + + +## 10xx - 常规服务器或网络问题 +### -1000 UNKNOWN + * An unknown error occured while processing the request. + * 处理请求时发生未知错误。 + +### -1001 DISCONNECTED + * Internal error; unable to process your request. Please try again. + * 内部错误; 无法处理您的请求。 请再试一次. + +### -1002 UNAUTHORIZED + * You are not authorized to execute this request. + * 您无权执行此请求。 + +### -1003 TOO_MANY_REQUESTS + * Too many requests queued. + * 排队的请求过多。 + * Too many requests; please use the websocket for live updates. + * 请求权重过多; 请使用websocket获取最新更新。 + * Too many requests; current limit is %s requests per minute. Please use the websocket for live updates to avoid polling the API. + * 请求权重过多; 当前限制为每分钟%s请求权重。 请使用websocket进行实时更新,以避免轮询API。 + * Way too many requests; IP banned until %s. Please use the websocket for live updates to avoid bans. + * 请求权重过多; IP被禁止,直到%s。 请使用websocket进行实时更新,以免被禁。 + +### -1004 DUPLICATE_IP + * This IP is already on the white list + * IP地址已经在白名单 + +### -1005 NO_SUCH_IP + * No such IP has been white listed + * 白名单上没有此IP地址 + +### -1006 UNEXPECTED_RESP + * An unexpected response was received from the message bus. Execution status unknown. + * 从消息总线收到意外的响应。执行状态未知。 + +### -1007 TIMEOUT + * Timeout waiting for response from backend server. Send status unknown; execution status unknown. + * 等待后端服务器响应超时。 发送状态未知; 执行状态未知。 + +### -1014 UNKNOWN_ORDER_COMPOSITION + * Unsupported order combination. + * 不支持当前的下单参数组合 + +### -1015 TOO_MANY_ORDERS + * Too many new orders. + * 新订单太多。 + * Too many new orders; current limit is %s orders per %s. + * 新订单太多; 当前限制为每%s %s个订单。 + +### -1016 SERVICE_SHUTTING_DOWN + * This service is no longer available. + * 该服务不可用。 + +### -1020 UNSUPPORTED_OPERATION + * This operation is not supported. + * 不支持此操作。 + +### -1021 INVALID_TIMESTAMP + * Timestamp for this request is outside of the recvWindow. + * 此请求的时间戳在recvWindow之外。 + * Timestamp for this request was 1000ms ahead of the server's time. + * 此请求的时间戳比服务器时间提前1000毫秒。 + +### -1022 INVALID_SIGNATURE + * Signature for this request is not valid. + * 此请求的签名无效。 + +### -1023 START_TIME_GREATER_THAN_END_TIME + * Start time is greater than end time. + * 参数里面的开始时间在结束时间之后 + + +## 11xx - Request issues +### -1100 ILLEGAL_CHARS + * Illegal characters found in a parameter. + * 在参数中发现非法字符。 + * Illegal characters found in parameter '%s'; legal range is '%s'. + * 在参数`%s`中发现非法字符; 合法范围是`%s`。 + +### -1101 TOO_MANY_PARAMETERS + * Too many parameters sent for this endpoint. + * 为此端点发送的参数太多。 + * Too many parameters; expected '%s' and received '%s'. + * 参数太多;预期为`%s`并收到了`%s`。 + * Duplicate values for a parameter detected. + * 检测到的参数值重复。 + +### -1102 MANDATORY_PARAM_EMPTY_OR_MALFORMED + * A mandatory parameter was not sent, was empty/null, or malformed. + * 未发送强制性参数,该参数为空/空或格式错误。 + * Mandatory parameter '%s' was not sent, was empty/null, or malformed. + * 强制参数`%s`未发送,为空/空或格式错误。 + * Param '%s' or '%s' must be sent, but both were empty/null! + * 必须发送参数`%s`或`%s`,但两者均为空! + +### -1103 UNKNOWN_PARAM + * An unknown parameter was sent. + * 发送了未知参数。 + +### -1104 UNREAD_PARAMETERS + * Not all sent parameters were read. + * 并非所有发送的参数都被读取。 + * Not all sent parameters were read; read '%s' parameter(s) but was sent '%s'. + * 并非所有发送的参数都被读取; 读取了`%s`参数,但被发送了`%s`。 + +### -1105 PARAM_EMPTY + * A parameter was empty. + * 参数为空。 + * Parameter '%s' was empty. + * 参数`%s`为空。 + +### -1106 PARAM_NOT_REQUIRED + * A parameter was sent when not required. + * 发送了不需要的参数。 + * Parameter '%s' sent when not required. + * 发送了不需要参数`%s`。 + +### -1111 BAD_PRECISION + * Precision is over the maximum defined for this asset. + * 精度超过为此资产定义的最大值。 + +### -1112 NO_DEPTH + * No orders on book for symbol. + * 交易对没有挂单。 + +### -1114 TIF_NOT_REQUIRED + * TimeInForce parameter sent when not required. + * 发送的`TimeInForce`参数不需要。 + +### -1115 INVALID_TIF + * Invalid timeInForce. + * 无效的`timeInForce` + +### -1116 INVALID_ORDER_TYPE + * Invalid orderType. + * 无效订单类型。 + +### -1117 INVALID_SIDE + * Invalid side. + * 无效买卖方向。 + +### -1118 EMPTY_NEW_CL_ORD_ID + * New client order ID was empty. + * 新的客户订单ID为空。 + +### -1119 EMPTY_ORG_CL_ORD_ID + * Original client order ID was empty. + * 客户自定义的订单ID为空。 + +### -1120 BAD_INTERVAL + * Invalid interval. + * 无效时间间隔。 + +### -1121 BAD_SYMBOL + * Invalid symbol. + * 无效的交易对。 + +### -1125 INVALID_LISTEN_KEY + * This listenKey does not exist. + * 此`listenKey`不存在。 + +### -1127 MORE_THAN_XX_HOURS + * Lookup interval is too big. + * 查询间隔太大。 + * More than %s hours between startTime and endTime. + * 从开始时间到结束时间之间超过`%s`小时。 + +### -1128 OPTIONAL_PARAMS_BAD_COMBO + * Combination of optional parameters invalid. + * 可选参数组合无效。 + +### -1130 INVALID_PARAMETER + * Invalid data sent for a parameter. + * 发送的参数为无效数据。 + * Data sent for parameter '%s' is not valid. + * 发送参数`%s`的数据无效。 + +### -1136 INVALID_NEW_ORDER_RESP_TYPE + * Invalid newOrderRespType. + * 无效的 newOrderRespType。 + + +## 20xx - Processing Issues +### -2010 NEW_ORDER_REJECTED + * NEW_ORDER_REJECTED + * 新订单被拒绝 + +### -2011 CANCEL_REJECTED + * CANCEL_REJECTED + * 取消订单被拒绝 + +### -2013 NO_SUCH_ORDER + * Order does not exist. + * 订单不存在。 + +### -2014 BAD_API_KEY_FMT + * API-key format invalid. + * API-key 格式无效。 + +### -2015 REJECTED_MBX_KEY + * Invalid API-key, IP, or permissions for action. + * 无效的API密钥,IP或操作权限。 + +### -2016 NO_TRADING_WINDOW + * No trading window could be found for the symbol. Try ticker/24hrs instead. + * 找不到该交易对的交易窗口。 尝试改为24小时自动报价。 + +### -2018 BALANCE_NOT_SUFFICIENT + * Balance is insufficient. + * 余额不足 + +### -2020 UNABLE_TO_FILL + * Unable to fill. + * 无法成交 + +### -2021 ORDER_WOULD_IMMEDIATELY_TRIGGER + * Order would immediately trigger. + * 订单可能被立刻触发 + +### -2022 REDUCE_ONLY_REJECT + * ReduceOnly Order is rejected. + * `ReduceOnly`订单被拒绝 + +### -2024 POSITION_NOT_SUFFICIENT + * Position is not sufficient. + * 持仓不足 + +### -2025 MAX_OPEN_ORDER_EXCEEDED + * Reach max open order limit. + * 挂单量达到上限 + +### -2026 REDUCE_ONLY_ORDER_TYPE_NOT_SUPPORTED + * This OrderType is not supported when reduceOnly. + * 当前订单类型不支持`reduceOnly` + +## 40xx - Filters and other Issues +### -4000 INVALID_ORDER_STATUS + * Invalid order status. + * 订单状态不正确 + +### -4001 PRICE_LESS_THAN_ZERO + * Price less than 0. + * 价格小于0 + +### -4002 PRICE_GREATER_THAN_MAX_PRICE + * Price greater than max price. + * 价格超过最大值 + +### -4003 QTY_LESS_THAN_ZERO + * Quantity less than zero. + * 数量小于0 + +### -4004 QTY_LESS_THAN_MIN_QTY + * Quantity less than min quantity. + * 数量小于最小值 + +### -4005 QTY_GREATER_THAN_MAX_QTY + * Quantity greater than max quantity. + * 数量大于最大值 + +### -4006 STOP_PRICE_LESS_THAN_ZERO + * Stop price less than zero. + * 触发价小于最小值 + +### -4007 STOP_PRICE_GREATER_THAN_MAX_PRICE + * Stop price greater than max price. + * 触发价大于最大值 + +### -4008 TICK_SIZE_LESS_THAN_ZERO + * Tick size less than zero. + * 价格精度小于0 + +### -4009 MAX_PRICE_LESS_THAN_MIN_PRICE + * Max price less than min price. + * 最大价格小于最小价格 + +### -4010 MAX_QTY_LESS_THAN_MIN_QTY + * Max qty less than min qty. + * 最大数量小于最小数量 + +### -4011 STEP_SIZE_LESS_THAN_ZERO + * Step size less than zero. + * 步进值小于0 + +### -4012 MAX_NUM_ORDERS_LESS_THAN_ZERO + * Max num orders less than zero. + * 最大订单量小于0 + +### -4013 PRICE_LESS_THAN_MIN_PRICE + * Price less than min price. + * 价格小于最小价格 + +### -4014 PRICE_NOT_INCREASED_BY_TICK_SIZE + * Price not increased by tick size. + * 价格增量不是价格精度的倍数。 + +### -4015 INVALID_CL_ORD_ID_LEN + * Client order id is not valid. + * 客户订单ID有误。 + * Client order id length should not be more than 36 chars + * 客户订单ID长度应该不多于36字符 + +### -4016 PRICE_HIGHTER_THAN_MULTIPLIER_UP + * Price is higher than mark price multiplier cap. + +### -4017 MULTIPLIER_UP_LESS_THAN_ZERO + * Multiplier up less than zero. + * 价格上限小于0 + +### -4018 MULTIPLIER_DOWN_LESS_THAN_ZERO + * Multiplier down less than zero. + * 价格下限小于0 + +### -4019 COMPOSITE_SCALE_OVERFLOW + * Composite scale too large. + +### -4020 TARGET_STRATEGY_INVALID + * Target strategy invalid for orderType '%s',reduceOnly '%b'. + * 目标策略值不适合`%s`订单状态, 只减仓`%b`。 + +### -4021 INVALID_DEPTH_LIMIT + * Invalid depth limit. + * 深度信息的`limit`值不正确。 + * '%s' is not valid depth limit. + * `%s`不是合理的深度信息的`limit`值。 + +### -4022 WRONG_MARKET_STATUS + * market status sent is not valid. + * 发送的市场状态不正确。 + +### -4023 QTY_NOT_INCREASED_BY_STEP_SIZE + * Qty not increased by step size. + * 数量的递增值不是步进值的倍数。 + +### -4024 PRICE_LOWER_THAN_MULTIPLIER_DOWN + * Price is lower than mark price multiplier floor. + +### -4025 MULTIPLIER_DECIMAL_LESS_THAN_ZERO + * Multiplier decimal less than zero. + +### -4026 COMMISSION_INVALID + * Commission invalid. + * 收益值不正确 + * `%s` less than zero. + * `%s`少于0 + * `%s` absolute value greater than `%s` + * `%s`绝对值大于`%s` + +### -4027 INVALID_ACCOUNT_TYPE + * Invalid account type. + * 账户类型不正确。 + +### -4029 INVALID_TICK_SIZE_PRECISION + * Tick size precision is invalid. + * 价格精度小数点位数不正确。 + +### -4030 INVALID_STEP_SIZE_PRECISION + * Step size precision is invalid. + * 步进值小数点位数不正确。 + +### -4031 INVALID_WORKING_TYPE + * Invalid parameter working type + * 不正确的参数类型 + * Invalid parameter working type: `%s` + * 不正确的参数类型: `%s` + +### -4032 EXCEED_MAX_CANCEL_ORDER_SIZE + * Exceed maximum cancel order size. + * 超过可以取消的最大订单量。 + * Invalid parameter working type: `%s` + * 不正确的参数类型: `%s` + +### -4044 INVALID_BALANCE_TYPE + * Balance Type is invalid. + * 余额类型不正确。 + +### -4045 MAX_STOP_ORDER_EXCEEDED + * Reach max stop order limit. + * 达到止损单的上限。 + +### -4055 AMOUNT_MUST_BE_POSITIVE + * Amount must be positive. + * 数量必须是正整数 + +### -4056 INVALID_API_KEY_TYPE + * Invalid api key type. + * API key的类型不正确 + +### -4057 INVALID_RSA_PUBLIC_KEY + * Invalid api public key + * API key不正确 + +### -4058 MAX_PRICE_TOO_LARGE + * maxPrice and priceDecimal too large,please check. + * maxPrice和priceDecimal太大,请检查。 + +### -4060 INVALID_POSITION_SIDE + * Invalid position side. + * 仓位方向不正确。 + +### -4061 POSITION_SIDE_NOT_MATCH + * Order's position side does not match user's setting. + * 订单的持仓方向和用户设置不一致。 + +### -4062 REDUCE_ONLY_CONFLICT + * Invalid or improper reduceOnly value. + * 仅减仓的设置不正确。 + +### -4084 UPCOMING_METHOD + * Method is not allowed currently. Upcoming soon. + * 方法不支持 + +### -4086 INVALID_PRICE_SPREAD_THRESHOLD + * Invalid price spread threshold + * 无效的价差阀值 + +### -4087 REDUCE_ONLY_ORDER_PERMISSION + * User can only place reduce only order + * 用户只能下仅减仓订单 + +### -4088 NO_PLACE_ORDER_PERMISSION + * User can not place order currently + * 用户当前不能下单 + +### -4114 INVALID_CLIENT_TRAN_ID_LEN + * clientTranId is not valid + * clientTranId不正确 + * Client tran id length should be less than 64 chars + * 客户的tranId长度应该小于64个字符 + +### -4115 DUPLICATED_CLIENT_TRAN_ID + * clientTranId is duplicated + * clientTranId重复 + * Client tran id should be unique within 7 days + * 客户的tranId应在7天内唯一 + +### -4118 REDUCE_ONLY_MARGIN_CHECK_FAILED + * ReduceOnly Order Failed. Please check your existing position and open orders + * 仅减仓订单失败。请检查现有的持仓和挂单 + +### -4131 MARKET_ORDER_REJECT + * The counterparty's best price does not meet the PERCENT_PRICE filter limit + * 交易对手的最高价格未达到PERCENT_PRICE过滤器限制 + +### -4135 INVALID_ACTIVATION_PRICE + * Invalid activation price + * 无效的激活价格 + +### -4137 QUANTITY_EXISTS_WITH_CLOSE_POSITION + * Quantity must be zero with closePosition equals true + * 数量必须为0,当closePosition为true时 + +### -4138 REDUCE_ONLY_MUST_BE_TRUE + * Reduce only must be true with closePosition equals true + * Reduce only 必须为true,当closePosition为true时 + +### -4139 ORDER_TYPE_CANNOT_BE_MKT + * Order type can not be market if it's unable to cancel + * 订单类型不能为市价单如果不能取消 + +### -4140 INVALID_OPENING_POSITION_STATUS + * Invalid symbol status for opening position + * 无效的交易对状态 + +### -4141 SYMBOL_ALREADY_CLOSED + * Symbol is closed + * 交易对已下架 + +### -4142 STRATEGY_INVALID_TRIGGER_PRICE + * REJECT: take profit or stop order will be triggered immediately + * 拒绝:止盈止损单将立即被触发 + +### -4164 MIN_NOTIONAL + * Order's notional must be no smaller than 5.0 (unless you choose reduce only) + * 订单的名义价值不可以小于5,除了使用reduce only + * Order's notional must be no smaller than %s (unless you choose reduce only) + * 订单的名义价值不可以小于`%s`,除了使用reduce only + +### -4165 INVALID_TIME_INTERVAL + * Invalid time interval + * 无效的间隔 + * Maximum time interval is %s days + * 最大的时间间隔为 `%s` 天 + +### -4183 PRICE_HIGHTER_THAN_STOP_MULTIPLIER_UP + * Price is higher than stop price multiplier cap. + * 止盈止损订单价格不应高于触发价与报价乘数上限的乘积 + * Limit price can't be higher than %s. + * 止盈止损订单价格不应高于 `%s` + +### -4184 PRICE_LOWER_THAN_STOP_MULTIPLIER_DOWN + * Price is lower than stop price multiplier floor. + * 止盈止损订单价格不应低于触发价与报价乘数下限的乘积 + * Limit price can't be lower than %s. + * 止盈止损订单价格不应低于 `%s`f diff --git a/aster-finance-spot-api_CN.md b/aster-finance-spot-api_CN.md index 3da1a0a..ffaefd4 100644 --- a/aster-finance-spot-api_CN.md +++ b/aster-finance-spot-api_CN.md @@ -81,9 +81,7 @@ ## 接口鉴权类型 * 每个接口都有自己的鉴权类型,鉴权类型决定了访问时应当进行何种鉴权。 * 鉴权类型会在本文档中各个接口名称旁声明,如果没有特殊声明即默认为 `NONE`。 -* 如果需要 API-keys,应当在HTTP头中以 `X-MBX-APIKEY`字段传递。 -* API-keys 与 secret-keys **是大小写敏感的**。 -* 默认 API-keys 可访问所有鉴权路径. + 鉴权类型 | 描述 ------------ | ------------ From 3e3ad24e4f5629dea71c11e9d42bf219b3ff3450 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Thu, 12 Mar 2026 11:39:55 +0700 Subject: [PATCH 051/131] spotnoop --- aster-finance-spot-api-v3.md | 19 +++++++++++++++++++ aster-finance-spot-api_CN-v3.md | 19 +++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/aster-finance-spot-api-v3.md b/aster-finance-spot-api-v3.md index 9b001b9..ab3b5d2 100644 --- a/aster-finance-spot-api-v3.md +++ b/aster-finance-spot-api-v3.md @@ -458,6 +458,25 @@ In order to comply with the `market lot size`, the `quantity` must satisfy the f # Market data API +## Noop + +> **Response:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +``POST /api/v3/noop`` + +By using this request, it is possible to efficiently cancel previously sent transactions that are still in the queue and have not completed the on chain operation (Nonce should be equal to this request,no guarantee of success +) + +**Weight:** +1 + ## Test server connectivity **Response** diff --git a/aster-finance-spot-api_CN-v3.md b/aster-finance-spot-api_CN-v3.md index 3a2eb85..830aeb2 100644 --- a/aster-finance-spot-api_CN-v3.md +++ b/aster-finance-spot-api_CN-v3.md @@ -452,6 +452,25 @@ Lots是拍卖术语,`LOT_SIZE` 过滤器对订单中的 `quantity` 也就是 # 行情接口 + +## Noop + +> **Response:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +``POST /api/v3/noop`` + +通过此请求,可以高效取消已发送但仍在队列中且尚未完成链上操作的交易(Nonce需与该请求一致,不保证成功) + +**Weight:** +1 + ## 测试服务器连通性 > **响应** ```javascript From 19ef27ad5068c0b21c7cbae577d47a02c9357281 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Thu, 12 Mar 2026 20:20:11 +0700 Subject: [PATCH 052/131] noopdemo --- aster-finance-futures-api-v3.md | 101 +++++++++++++++++++++++++++++ aster-finance-futures-api-v3_CN.md | 101 +++++++++++++++++++++++++++++ 2 files changed, 202 insertions(+) diff --git a/aster-finance-futures-api-v3.md b/aster-finance-futures-api-v3.md index 62d62f6..7caef0e 100644 --- a/aster-finance-futures-api-v3.md +++ b/aster-finance-futures-api-v3.md @@ -643,6 +643,107 @@ By using this request, it is possible to efficiently cancel previously sent tran **Weight:** 1 +#### Demo : Noop (python) + +```python +import time +import urllib + +import aiohttp +from eth_account.messages import encode_structured_data +from eth_account import Account +import asyncio + +typed_data = { + "types": { + "EIP712Domain": [ + {"name": "name", "type": "string"}, + {"name": "version", "type": "string"}, + {"name": "chainId", "type": "uint256"}, + {"name": "verifyingContract", "type": "address"} + ], + "Message": [ + { "name": "msg", "type": "string" } + ] + }, + "primaryType": "Message", + "domain": { + "name": "AsterSignTransaction", + "version": "1", + "chainId": 1666, + "verifyingContract": "0x0000000000000000000000000000000000000000" + }, + "message": { + "msg": "$msg" + } +} + +headers = { + 'Content-Type': 'application/x-www-form-urlencoded', + 'User-Agent': 'PythonApp/1.0' +} +host = 'https://fapi3.asterdex.com' + +# config your user and agent info here +user = '*' +signer = '*' +private_key = "**" + +noop = {'url':'/fapi/v3/noop','method':'POST','params':{}} +place_order = {"url":"/fapi/v3/order","method":"POST","params":{"symbol": "ASTERUSDT", "type": "LIMIT", "side": "BUY", + "timeInForce": "GTC", "quantity": "20", "price": "0.5"}} +_last_ms = 0 +_i = 0 + +def get_nonce(): + global _last_ms, _i + now_ms = int(time.time()) + + if now_ms == _last_ms: + _i += 1 + else: + _last_ms = now_ms + _i = 0 + + return now_ms * 1_000_000 + _i + +async def send_by_url(api,nonce) : + my_dict = api['params'] + url = host + api['url'] + + my_dict['nonce'] = nonce + my_dict['user'] = user + my_dict['signer'] = signer + param = urllib.parse.urlencode(my_dict) + + typed_data['message']['msg'] = param + message = encode_structured_data(typed_data) + signed = Account.sign_message(message, private_key=private_key) + + url = url + '?' + param + '&signature=' + signed.signature.hex() + print(url) + async with aiohttp.ClientSession() as session: + async with session.post(url, headers=headers) as resp: + text = await resp.text() + return {"status_code": resp.status, "text": text,'nonce': nonce} + +async def main(): + _place_order_nonce = get_nonce() + task_place_order =asyncio.create_task( send_by_url(place_order, _place_order_nonce)) + task_noop= asyncio.create_task( send_by_url(noop, _place_order_nonce)) + place_order_result, noop_result = await asyncio.gather(task_place_order, task_noop) + print(f"place_order_result : {place_order_result['text']},nonce: {place_order_result['nonce']}") + print(f"noop_result : {noop_result['text']},nonce: {noop_result['nonce']}") + +if __name__ == '__main__': + asyncio.run(main()) + +# This operation may not succeed every time. Please retry. +# place_order_result : {"code":-4225,"msg":"Nonce Expired"},nonce: 1773321233000000 +# noop_result : {"code": 200,"msg": "success"},nonce: 1773321233000000 + +``` + ## Test Connectivity > **Response:** diff --git a/aster-finance-futures-api-v3_CN.md b/aster-finance-futures-api-v3_CN.md index e4e24e1..d5bd74b 100644 --- a/aster-finance-futures-api-v3_CN.md +++ b/aster-finance-futures-api-v3_CN.md @@ -616,6 +616,107 @@ MIN_NOTIONAL过滤器定义了交易对订单所允许的最小名义价值(成 通过此请求,可以高效取消已发送但仍在队列中且尚未完成链上操作的交易(Nonce需与该请求一致,不保证成功) +#### 示例 : Noop (方法以python为例) + +```python +import time +import urllib + +import aiohttp +from eth_account.messages import encode_structured_data +from eth_account import Account +import asyncio + +typed_data = { + "types": { + "EIP712Domain": [ + {"name": "name", "type": "string"}, + {"name": "version", "type": "string"}, + {"name": "chainId", "type": "uint256"}, + {"name": "verifyingContract", "type": "address"} + ], + "Message": [ + { "name": "msg", "type": "string" } + ] + }, + "primaryType": "Message", + "domain": { + "name": "AsterSignTransaction", + "version": "1", + "chainId": 1666, + "verifyingContract": "0x0000000000000000000000000000000000000000" + }, + "message": { + "msg": "$msg" + } +} + +headers = { + 'Content-Type': 'application/x-www-form-urlencoded', + 'User-Agent': 'PythonApp/1.0' +} +host = 'https://fapi3.asterdex.com' + +# config your user and agent info here +user = '*' +signer = '*' +private_key = "**" + +noop = {'url':'/fapi/v3/noop','method':'POST','params':{}} +place_order = {"url":"/fapi/v3/order","method":"POST","params":{"symbol": "ASTERUSDT", "type": "LIMIT", "side": "BUY", + "timeInForce": "GTC", "quantity": "20", "price": "0.5"}} +_last_ms = 0 +_i = 0 + +def get_nonce(): + global _last_ms, _i + now_ms = int(time.time()) + + if now_ms == _last_ms: + _i += 1 + else: + _last_ms = now_ms + _i = 0 + + return now_ms * 1_000_000 + _i + +async def send_by_url(api,nonce) : + my_dict = api['params'] + url = host + api['url'] + + my_dict['nonce'] = nonce + my_dict['user'] = user + my_dict['signer'] = signer + param = urllib.parse.urlencode(my_dict) + + typed_data['message']['msg'] = param + message = encode_structured_data(typed_data) + signed = Account.sign_message(message, private_key=private_key) + + url = url + '?' + param + '&signature=' + signed.signature.hex() + print(url) + async with aiohttp.ClientSession() as session: + async with session.post(url, headers=headers) as resp: + text = await resp.text() + return {"status_code": resp.status, "text": text,'nonce': nonce} + +async def main(): + _place_order_nonce = get_nonce() + task_place_order =asyncio.create_task( send_by_url(place_order, _place_order_nonce)) + task_noop= asyncio.create_task( send_by_url(noop, _place_order_nonce)) + place_order_result, noop_result = await asyncio.gather(task_place_order, task_noop) + print(f"place_order_result : {place_order_result['text']},nonce: {place_order_result['nonce']}") + print(f"noop_result : {noop_result['text']},nonce: {noop_result['nonce']}") + +if __name__ == '__main__': + asyncio.run(main()) + +# This operation may not succeed every time. Please retry. +# place_order_result : {"code":-4225,"msg":"Nonce Expired"},nonce: 1773321233000000 +# noop_result : {"code": 200,"msg": "success"},nonce: 1773321233000000 + +``` + **Weight:** 1 From 60dd767a9576fa81cd58a93b4fd31fe0221e05c2 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Fri, 13 Mar 2026 10:09:26 +0700 Subject: [PATCH 053/131] MARKET_DATA no need auth --- aster-finance-futures-api-v3.md | 4 ++-- aster-finance-futures-api-v3_CN.md | 2 +- aster-finance-spot-api-v3.md | 2 +- aster-finance-spot-api_CN-v3.md | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/aster-finance-futures-api-v3.md b/aster-finance-futures-api-v3.md index 7caef0e..5563130 100644 --- a/aster-finance-futures-api-v3.md +++ b/aster-finance-futures-api-v3.md @@ -192,7 +192,7 @@ It is strongly recommended to use websocket stream for getting data as much as p | TRADE | A valid signer and signature are required | | USER_DATA | A valid signer and signature are required | | USER_STREAM | A valid signer and signature are required | -| MARKET_DATA | A valid signer and signature are required | +| MARKET_DATA | API that does not require authentication | ## Authentication signature payload @@ -204,7 +204,7 @@ It is strongly recommended to use websocket stream for getting data as much as p | signature | Signature | ## Endpoints requiring signature -* Security Type: TRADE, USER_DATA, USER_STREAM, MARKET_DATA +* Security Type: TRADE, USER_DATA, USER_STREAM * After generating the string, combine it with the authentication signature parameters user, signer, and nonce, then use Web3’s ABI parameter encoding to generate the bytecode. * After generating the bytecode, use the Keccak algorithm to generate the hash. * Use the private key of **API wallet address** to sign the hash using web3’s ECDSA signature algorithm, generating the final signature. diff --git a/aster-finance-futures-api-v3_CN.md b/aster-finance-futures-api-v3_CN.md index d5bd74b..4bcf35f 100644 --- a/aster-finance-futures-api-v3_CN.md +++ b/aster-finance-futures-api-v3_CN.md @@ -183,7 +183,7 @@ NONE | 不需要鉴权的接口 TRADE | 需要有效的signer和签名 USER_DATA | 需要有效的signer和签名 USER_STREAM | 需要有效的signer和签名 -MARKET_DATA | 需要有效的signer和签名 +MARKET_DATA | 不需要鉴权的接口 ## 鉴权签名体 参数 | 描述 diff --git a/aster-finance-spot-api-v3.md b/aster-finance-spot-api-v3.md index ab3b5d2..97f0e32 100644 --- a/aster-finance-spot-api-v3.md +++ b/aster-finance-spot-api-v3.md @@ -92,7 +92,7 @@ You are advised to use WebSocket messages to obtain the corresponding data as mu | SPOT_TRADE | A valid signer and signature are required | | USER_DATA | A valid signer and signature are required | | USER_STREAM | A valid signer and signature are required | -| MARKET_DATA | A valid signer and signature are required | +| MARKET_DATA | API that does not require authentication | --- diff --git a/aster-finance-spot-api_CN-v3.md b/aster-finance-spot-api_CN-v3.md index 830aeb2..b05162d 100644 --- a/aster-finance-spot-api_CN-v3.md +++ b/aster-finance-spot-api_CN-v3.md @@ -87,7 +87,7 @@ NONE | 不需要鉴权的接口 SPOT_TRADE | 需要有效的signer和签名 USER_DATA | 需要有效的signer和签名 USER_STREAM | 需要有效的signer和签名 -MARKET_DATA | 需要有效的signer和签名 +MARKET_DATA | 不需要鉴权的接口 ### POST /api/v3/order 的示例 From bc99b7a2f73403d0201e2d49ab87b71472114f85 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Tue, 17 Mar 2026 10:10:59 +0700 Subject: [PATCH 054/131] remove go demo --- v3-demo/main.go | 347 ------------------------------------------------ 1 file changed, 347 deletions(-) delete mode 100644 v3-demo/main.go diff --git a/v3-demo/main.go b/v3-demo/main.go deleted file mode 100644 index 54b8b6c..0000000 --- a/v3-demo/main.go +++ /dev/null @@ -1,347 +0,0 @@ -package main - -import ( - "encoding/hex" - "encoding/json" - "errors" - "fmt" - "io" - "math/big" - "net/http" - "net/url" - "sort" - "strconv" - "strings" - "time" - - "github.com/ethereum/go-ethereum/accounts/abi" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" -) - -//go version go1.24.1 darwin/arm64 -var ( - //your main wallet address (eoa) - //你的登陆钱包地址(erc20) - user = "*****" - //please get these parameters from https://www.asterdex.com/en/api-wallet - //下面这些参数在这里生成配置 https://www.asterdex.com/zh-CN/api-wallet - signer = "*******" - priKeyHex = "********" - - //请求的域名 - host = "https://fapi.asterdex.com" - cli = &http.Client{ - Timeout: 15 * time.Second, - } -) - -var placeOrder = map[string]interface{}{ - "url": "/fapi/v3/order", - "method": "POST", - "params": map[string]interface{}{ - "symbol": "BTCUSDT", - "positionSide": "BOTH", - "type": "LIMIT", - "side": "BUY", - "timeInForce": "GTC", - "quantity": "0.01", - "price": "110000.2", - }, -} - -var getOrder = map[string]interface{}{ - "url": "/fapi/v3/order", - "method": "GET", - "params": map[string]interface{}{ - "symbol": "SANDUSDT", - "orderId": "2194215", - "side": "BUY", - "type": "LIMIT", - }, -} - -func main() { - //get an order - if err := call(getOrder); err != nil { - fmt.Println("call failed:", err) - } - //place an order - if err := call(placeOrder); err != nil { - fmt.Println("call failed:", err) - } -} - -func call(api map[string]interface{}) error { - nonce := genNonce() - fmt.Println("nonce:", nonce) - // 复制一份 params,以免修改全局模板 - params := cloneInterface(api["params"]) - paramsMap, ok := params.(map[string]interface{}) - if !ok { - return errors.New("params must be map[string]interface{}") - } - - // sign 会修改 paramsMap(加入 user, signer, signature, timestamp, recvWindow) - if err := sign(paramsMap, nonce); err != nil { - return err - } - - // 发送请求 - urlPath, _ := api["url"].(string) - method, _ := api["method"].(string) - fullUrl := strings.TrimRight(host, "/") + urlPath - respBody, statusCode, err := send(fullUrl, method, paramsMap) - if err != nil { - return err - } - fmt.Printf("HTTP %d response: %s\n", statusCode, respBody) - return nil -} - -// sign 将在 params 中添加 timestamp, recvWindow, user, signer, signature -func sign(params map[string]interface{}, nonce uint64) error { - // 添加 recvWindow 和 timestamp (毫秒) - params["recvWindow"] = "50000" - timestamp := strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10) - //params["timestamp"] = "1759212310710" - params["timestamp"] = timestamp - - // 先做确定性的序列化(递归按 key 排序) - trimmed, err := normalizeAndStringify(params) - if err != nil { - return err - } - // trimmed 是 string,作为第一个 ABI 参数 - // 构造 ABI: (string, address, address, uint256) - argString := trimmed - fmt.Println(argString) - addrUser := common.HexToAddress(user) - addrSigner := common.HexToAddress(signer) - nonceBig := new(big.Int).SetUint64(nonce) - - // 定义 abi types - tString, err := abi.NewType("string", "", nil) - if err != nil { - return err - } - tAddress, err := abi.NewType("address", "", nil) - if err != nil { - return err - } - tUint256, err := abi.NewType("uint256", "", nil) - if err != nil { - return err - } - arguments := abi.Arguments{ - {Type: tString}, - {Type: tAddress}, - {Type: tAddress}, - {Type: tUint256}, - } - - // Pack - packed, err := arguments.Pack(argString, addrUser, addrSigner, nonceBig) - if err != nil { - return fmt.Errorf("abi pack error: %w", err) - } - - fmt.Println(hex.EncodeToString(packed)) - - // keccak256 - hash := crypto.Keccak256(packed) - - fmt.Println(hex.EncodeToString(hash)) - - prefixedMsg := fmt.Sprintf("\x19Ethereum Signed Message:\n%d%s", len(hash), hash) - - // 2. keccak256 哈希 - msgHash := crypto.Keccak256Hash([]byte(prefixedMsg)) - // Load private key - privKey, err := crypto.HexToECDSA(strings.TrimPrefix(priKeyHex, "0x")) - if err != nil { - return fmt.Errorf("invalid private key: %w", err) - } - - // Sign the hash (returns 65 bytes: R(32)|S(32)|V(1)) - sig, err := crypto.Sign(msgHash.Bytes(), privKey) - if err != nil { - return fmt.Errorf("sign error: %w", err) - } - - // crypto.Sign returns v as 0/1 in last byte — convert to 27/28 - if len(sig) != 65 { - return fmt.Errorf("unexpected signature length: %d", len(sig)) - } - sig[64] += 27 - - // hex-encode with 0x prefix - sigHex := "0x" + hex.EncodeToString(sig) - - // 将 user、signer、signature 插入 params - params["user"] = user - params["signer"] = signer - params["signature"] = sigHex - - //把 nonce 也放回 params - params["nonce"] = nonce - - fmt.Println("signature:", hex.EncodeToString(sig)) - - return nil -} - -// send HTTP 请求:POST -> body JSON; GET/DELETE -> params放 querystring -func send(fullUrl string, method string, params map[string]interface{}) (string, int, error) { - method = strings.ToUpper(method) - switch method { - case "POST": - form := url.Values{} - for k, v := range params { - form.Set(k, fmt.Sprintf("%v", v)) // interface{} -> string - } - req, err := http.NewRequest("POST", fullUrl, strings.NewReader(form.Encode())) - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - resp, err := cli.Do(req) - if err != nil { - return "", 0, err - } - defer resp.Body.Close() - body, _ := io.ReadAll(resp.Body) - return string(body), resp.StatusCode, nil - case "GET", "DELETE": - // 把 params 放到 querystring(递归转成 key=val 的方式;此处做最简单的 flat 化) - q := url.Values{} - flattenParams("", params, &q) - u, _ := url.Parse(fullUrl) - u.RawQuery = q.Encode() - fmt.Println(u.String()) - req, _ := http.NewRequest(method, u.String(), nil) - resp, err := cli.Do(req) - if err != nil { - return "", 0, err - } - defer resp.Body.Close() - body, _ := io.ReadAll(resp.Body) - return string(body), resp.StatusCode, nil - default: - return "", 0, fmt.Errorf("unsupported http method: %s", method) - } -} - -// flattenParams 将 map 递归展平成 query params -func flattenParams(prefix string, v interface{}, q *url.Values) { - switch val := v.(type) { - case map[string]interface{}: - // 保持 key 排序,确定性 - keys := make([]string, 0, len(val)) - for k := range val { - keys = append(keys, k) - } - sort.Strings(keys) - for _, k := range keys { - nk := k - if prefix != "" { - nk = prefix + "." + k - } - flattenParams(nk, val[k], q) - } - case []interface{}: - for i, item := range val { - nk := fmt.Sprintf("%s[%d]", prefix, i) - flattenParams(nk, item, q) - } - case string: - q.Add(prefix, val) - case bool: - q.Add(prefix, fmt.Sprintf("%v", val)) - case float64: - // JSON decode 默认数值为 float64 - q.Add(prefix, fmt.Sprintf("%v", val)) - case nil: - // skip nil - default: - // 尝试格式化为 string - q.Add(prefix, fmt.Sprintf("%v", val)) - } -} - -// normalizeAndStringify 对 map 做确定性序列化(按 key 排序),返回 string -func normalizeAndStringify(v interface{}) (string, error) { - // 先把 v 变成一个 deterministic structure,然后 json.Marshal - norm, err := normalize(v) - if err != nil { - return "", err - } - bs, err := json.Marshal(norm) - if err != nil { - return "", err - } - return string(bs), nil -} - -// normalize 将 map/array 中的键按字母序排序并递归处理 -func normalize(v interface{}) (interface{}, error) { - switch val := v.(type) { - case map[string]interface{}: - keys := make([]string, 0, len(val)) - for k := range val { - keys = append(keys, k) - } - sort.Strings(keys) - //out := make([]interface{}, 0, len(keys)) - // 为了保证 JSON 有键名,我们重建为 map 并按顺序添加 - newMap := make(map[string]interface{}, len(keys)) - for _, k := range keys { - nv, err := normalize(val[k]) - if err != nil { - return nil, err - } - newMap[k] = nv - } - // 返回按 key 排序的 map(Marshal 时 map 的顺序并不保证,但我们已按 key 插入;若你需要绝对保证,请把结果改为 []kv 的形式) - return newMap, nil - case map[interface{}]interface{}: - // unlikely in JSON-decoded, 但处理一下 - keys := make([]string, 0, len(val)) - for k := range val { - keys = append(keys, fmt.Sprint(k)) - } - sort.Strings(keys) - newMap := make(map[string]interface{}, len(keys)) - for _, k := range keys { - newMap[k] = val[k] - } - return normalize(newMap) - case []interface{}: - out := make([]interface{}, 0, len(val)) - for _, it := range val { - nv, err := normalize(it) - if err != nil { - return nil, err - } - out = append(out, nv) - } - return out, nil - default: - // 基本类型直接返回 - return val, nil - } -} - -// cloneInterface 做浅拷贝(仅用于顶层 params) -func cloneInterface(v interface{}) interface{} { - // 通过 json marshal/unmarshal 做深拷贝(简单可靠) - bs, err := json.Marshal(v) - if err != nil { - return v - } - var out interface{} - _ = json.Unmarshal(bs, &out) - return out -} - -func genNonce() uint64 { - micro := time.Now().UnixMicro() - return uint64(micro) -} From bdcc080d26778bdf0b76c5b97a67bb027e0df4e9 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Tue, 17 Mar 2026 10:25:58 +0700 Subject: [PATCH 055/131] add hidden in v3 --- aster-finance-futures-api-testnet.md | 4 +++- aster-finance-futures-api-v3.md | 4 +++- aster-finance-futures-api-v3_CN.md | 4 +++- aster-finance-spot-api-testnet.md | 3 ++- aster-finance-spot-api-v3.md | 3 ++- aster-finance-spot-api.md | 3 ++- aster-finance-spot-api_CN-v3.md | 3 ++- aster-finance-spot-api_CN.md | 4 +++- 8 files changed, 20 insertions(+), 8 deletions(-) diff --git a/aster-finance-futures-api-testnet.md b/aster-finance-futures-api-testnet.md index 7291754..8d9b6c7 100644 --- a/aster-finance-futures-api-testnet.md +++ b/aster-finance-futures-api-testnet.md @@ -451,6 +451,7 @@ if __name__ == '__main__': * IOC - Immediate or Cancel * FOK - Fill or Kill * GTX - Good Till Crossing (Post Only) +* HIDDEN - HIDDEN This type of order is not visible in the order book **Working Type (workingType)** @@ -832,7 +833,8 @@ NONE "GTC", "IOC", "FOK", - "GTX" + "GTX", + "HIDDEN" ], "liquidationFee": "0.010000", // liquidation fee rate "marketTakeBound": "0.30", // the max price difference rate( from mark price) a market order can make diff --git a/aster-finance-futures-api-v3.md b/aster-finance-futures-api-v3.md index 5563130..6bfd9d6 100644 --- a/aster-finance-futures-api-v3.md +++ b/aster-finance-futures-api-v3.md @@ -412,6 +412,7 @@ if __name__ == '__main__': * IOC - Immediate or Cancel * FOK - Fill or Kill * GTX - Good Till Crossing (Post Only) +* HIDDEN - HIDDEN This type of order is not visible in the order book **Working Type (workingType)** @@ -893,7 +894,8 @@ NONE "GTC", "IOC", "FOK", - "GTX" + "GTX", + "HIDDEN" ], "liquidationFee": "0.010000", // liquidation fee rate "marketTakeBound": "0.30", // the max price difference rate( from mark price) a market order can make diff --git a/aster-finance-futures-api-v3_CN.md b/aster-finance-futures-api-v3_CN.md index 4bcf35f..e5f735f 100644 --- a/aster-finance-futures-api-v3_CN.md +++ b/aster-finance-futures-api-v3_CN.md @@ -394,6 +394,7 @@ if __name__ == '__main__': * IOC - Immediate or Cancel 无法立即成交(吃单)的部分就撤销 * FOK - Fill or Kill 无法全部立即成交就撤销 * GTX - Good Till Crossing 无法成为挂单方就撤销 +* HIDDEN - HIDDEN 该类型订单在订单薄里不可见 **条件价格触发类型 (workingType)** @@ -875,7 +876,8 @@ NONE "GTC", // 成交为止, 一直有效 "IOC", // 无法立即成交(吃单)的部分就撤销 "FOK", // 无法全部立即成交就撤销 - "GTX" // 无法成为挂单方就撤销 + "GTX", // 无法成为挂单方就撤销 + "HIDDEN" ], "liquidationFee": "0.010000", // 强平费率 "marketTakeBound": "0.30", // 市价吃单(相对于标记价格)允许可造成的最大价格偏离比例 diff --git a/aster-finance-spot-api-testnet.md b/aster-finance-spot-api-testnet.md index 7bf498d..7d740c8 100644 --- a/aster-finance-spot-api-testnet.md +++ b/aster-finance-spot-api-testnet.md @@ -666,7 +666,8 @@ Test if the REST API can be reached and retrieve the server time. "GTC", "IOC", "FOK", - "GTX" + "GTX", + "HIDDEN" ], "symbol": "BNBUSDT", "ocoAllowed": false diff --git a/aster-finance-spot-api-v3.md b/aster-finance-spot-api-v3.md index 97f0e32..89487a8 100644 --- a/aster-finance-spot-api-v3.md +++ b/aster-finance-spot-api-v3.md @@ -622,7 +622,8 @@ Test if the REST API can be reached and retrieve the server time. "GTC", "IOC", "FOK", - "GTX" + "GTX", + "HIDDEN" ], "symbol": "BNBUSDT", "ocoAllowed": false diff --git a/aster-finance-spot-api.md b/aster-finance-spot-api.md index b905393..b3df69c 100644 --- a/aster-finance-spot-api.md +++ b/aster-finance-spot-api.md @@ -554,7 +554,8 @@ Test if the REST API can be reached and retrieve the server time. "GTC", "IOC", "FOK", - "GTX" + "GTX", + "HIDDEN" ], "symbol": "BNBUSDT", "ocoAllowed": false diff --git a/aster-finance-spot-api_CN-v3.md b/aster-finance-spot-api_CN-v3.md index b05162d..e0011d0 100644 --- a/aster-finance-spot-api_CN-v3.md +++ b/aster-finance-spot-api_CN-v3.md @@ -620,7 +620,8 @@ NONE "GTC", "IOC", "FOK", - "GTX" + "GTX", + "HIDDEN" ], "symbol": "BNBUSDT", "ocoAllowed": false diff --git a/aster-finance-spot-api_CN.md b/aster-finance-spot-api_CN.md index ffaefd4..299326c 100644 --- a/aster-finance-spot-api_CN.md +++ b/aster-finance-spot-api_CN.md @@ -258,6 +258,7 @@ Status | Description `IOC` | 无法立即成交的部分就撤销
订单在失效前会尽量多的成交。 `FOK` | 无法全部立即成交就撤销
如果无法全部成交,订单会失效。 `GTX` | 直到挂单成交
限价只挂单。 +`HIDDEN` | 该类型订单在订单薄里不可见 **K线间隔:** @@ -576,7 +577,8 @@ NONE "GTC", "IOC", "FOK", - "GTX" + "GTX", + "HIDDEN" ], "symbol": "BNBUSDT", "ocoAllowed": false From 2bea734395e66b722f223330b992a7a5a89efdbe Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Tue, 17 Mar 2026 11:09:19 +0700 Subject: [PATCH 056/131] remove timestamp --- aster-finance-futures-api-v3.md | 57 ------------------------------ aster-finance-futures-api-v3_CN.md | 57 ------------------------------ aster-finance-spot-api-v3.md | 29 --------------- aster-finance-spot-api_CN-v3.md | 34 ------------------ 4 files changed, 177 deletions(-) diff --git a/aster-finance-futures-api-v3.md b/aster-finance-futures-api-v3.md index 6bfd9d6..3e1bfe0 100644 --- a/aster-finance-futures-api-v3.md +++ b/aster-finance-futures-api-v3.md @@ -116,7 +116,6 @@ * The base endpoint is: **https://fapi.asterdex.com** * All endpoints return either a JSON object or array. * Data is returned in **ascending** order. Oldest first, newest last. -* All time and timestamp related fields are in milliseconds. * All data types adopt definition in JAVA. ### HTTP Return Codes @@ -2202,8 +2201,6 @@ Change user's Multi-Assets mode (Multi-Assets Mode or Single-Asset Mode) on ***E | Name | Type | Mandatory | Description | | ----------------- | ------ | --------- | ----------------------------------------------------- | | multiAssetsMargin | STRING | YES | "true": Multi-Assets Mode; "false": Single-Asset Mode | -| recvWindow | LONG | NO | | -| timestamp | LONG | YES | | ## Get Current Multi-Assets Mode (USER_DATA) @@ -2226,8 +2223,6 @@ Get user's Multi-Assets mode (Multi-Assets Mode or Single-Asset Mode) on ***Ever | Name | Type | Mandatory | Description | | ---------- | ---- | --------- | ----------- | -| recvWindow | LONG | NO | | -| timestamp | LONG | YES | | ## New Order (TRADE) @@ -2288,8 +2283,6 @@ Send in a new order. | workingType | ENUM | NO | stopPrice triggered by: "MARK_PRICE", "CONTRACT_PRICE". Default "CONTRACT_PRICE" | | priceProtect | STRING | NO | "TRUE" or "FALSE", default "FALSE". Used with`STOP/STOP_MARKET` or `TAKE_PROFIT/TAKE_PROFIT_MARKET` orders. | | newOrderRespType | ENUM | NO | "ACK", "RESULT", default "ACK" | -| recvWindow | LONG | NO | | -| timestamp | LONG | YES | | Additional mandatory parameters based on `type`: @@ -2384,8 +2377,6 @@ Additional mandatory parameters based on `type`: | Name | Type | Mandatory | Description | | ----------- | ---------- | --------- | ------------------------ | | batchOrders | LIST | YES | order list. Max 5 orders | -| recvWindow | LONG | NO | | -| timestamp | LONG | YES | | **Where ``batchOrders`` is the list of order parameters in JSON** @@ -2438,7 +2429,6 @@ amount | DECIMAL | YES | amount asset | STRING | YES | asset clientTranId | STRING | YES | transaction id kindType | STRING | YES | kindType -timestamp | LONG | YES | timestamp Notes: @@ -2498,8 +2488,6 @@ Check an order's status. | symbol | STRING | YES | | | orderId | LONG | NO | | | origClientOrderId | STRING | NO | | -| recvWindow | LONG | NO | | -| timestamp | LONG | YES | | Notes: @@ -2550,8 +2538,6 @@ Cancel an active order. | symbol | STRING | YES | | | orderId | LONG | NO | | | origClientOrderId | STRING | NO | | -| recvWindow | LONG | NO | | -| timestamp | LONG | YES | | Either `orderId` or `origClientOrderId` must be sent. @@ -2576,8 +2562,6 @@ Either `orderId` or `origClientOrderId` must be sent. | Name | Type | Mandatory | Description | | ---------- | ------ | --------- | ----------- | | symbol | STRING | YES | | -| recvWindow | LONG | NO | | -| timestamp | LONG | YES | | ## Cancel Multiple Orders (TRADE) @@ -2628,8 +2612,6 @@ Either `orderId` or `origClientOrderId` must be sent. | symbol | STRING | YES | | | orderIdList | LIST\ | NO | max length 10 e.g. [1234567,2345678] | | origClientOrderIdList | LIST\ | NO | max length 10 e.g. ["my_id_1","my_id_2"], encode the double quotes. No space after comma. | -| recvWindow | LONG | NO | | -| timestamp | LONG | YES | | Either `orderIdList` or `origClientOrderIdList ` must be sent. @@ -2657,8 +2639,6 @@ Cancel all open orders of the specified symbol at the end of the specified count | ------------- | ------ | --------- | -------------------------------------------------------- | | symbol | STRING | YES | | | countdownTime | LONG | YES | countdown time, 1000 for 1 second. 0 to cancel the timer | -| recvWindow | LONG | NO | | -| timestamp | LONG | YES | | * The endpoint should be called repeatedly as heartbeats so that the existing countdown time can be canceled and replaced by a new one. * Example usage: @@ -2710,8 +2690,6 @@ Cancel all open orders of the specified symbol at the end of the specified count | symbol | STRING | YES | | | orderId | LONG | NO | | | origClientOrderId | STRING | NO | | -| recvWindow | LONG | NO | | -| timestamp | LONG | YES | | * Either`orderId` or `origClientOrderId` must be sent * If the queried order has been filled or cancelled, the error message "Order does not exist" will be returned. @@ -2762,8 +2740,6 @@ Get all open orders on a symbol. **Careful** when accessing this with no symbol. | Name | Type | Mandatory | Description | | ---------- | ------ | --------- | ----------- | | symbol | STRING | NO | | -| recvWindow | LONG | NO | | -| timestamp | LONG | YES | | * If the symbol is not sent, orders for all symbols will be returned in an array. @@ -2822,8 +2798,6 @@ Get all account orders; active, canceled, or filled. | startTime | LONG | NO | | | endTime | LONG | NO | | | limit | INT | NO | Default 500; max 1000. | -| recvWindow | LONG | NO | | -| timestamp | LONG | YES | | **Notes:** @@ -2859,8 +2833,6 @@ Get all account orders; active, canceled, or filled. | Name | Type | Mandatory | Description | | ---------- | ---- | --------- | ----------- | -| recvWindow | LONG | NO | | -| timestamp | LONG | YES | | ## Account Information v3 (USER_DATA) @@ -2951,8 +2923,6 @@ Get current account information. | Name | Type | Mandatory | Description | | ---------- | ---- | --------- | ----------- | -| recvWindow | LONG | NO | | -| timestamp | LONG | YES | | ## Change Initial Leverage (TRADE) @@ -2979,8 +2949,6 @@ Change user's initial leverage of specific symbol market. | ---------- | ------ | --------- | ------------------------------------------ | | symbol | STRING | YES | | | leverage | INT | YES | target initial leverage: int from 1 to 125 | -| recvWindow | LONG | NO | | -| timestamp | LONG | YES | | ## Change Margin Type (TRADE) @@ -3004,8 +2972,6 @@ Change user's initial leverage of specific symbol market. | ---------- | ------ | --------- | ----------------- | | symbol | STRING | YES | | | marginType | ENUM | YES | ISOLATED, CROSSED | -| recvWindow | LONG | NO | | -| timestamp | LONG | YES | | ## Modify Isolated Position Margin (TRADE) @@ -3033,8 +2999,6 @@ Change user's initial leverage of specific symbol market. | positionSide | ENUM | NO | Default`BOTH` for One-way Mode ; `LONG` or `SHORT` for Hedge Mode. It must be sent with Hedge Mode. | | amount | DECIMAL | YES | | | type | INT | YES | 1: Add position margin,2: Reduce position margin | -| recvWindow | LONG | NO | | -| timestamp | LONG | YES | | * Only for isolated symbol @@ -3077,8 +3041,6 @@ Change user's initial leverage of specific symbol market. | startTime | LONG | NO | | | endTime | LONG | NO | | | limit | INT | NO | Default: 500 | -| recvWindow | LONG | NO | | -| timestamp | LONG | YES | | ## Position Information v3 (USER_DATA) @@ -3155,8 +3117,6 @@ Get current position information. | Name | Type | Mandatory | Description | | ---------- | ------ | --------- | ----------- | | symbol | STRING | NO | | -| recvWindow | LONG | NO | | -| timestamp | LONG | YES | | **Note** Please use with user data stream `ACCOUNT_UPDATE` to meet your timeliness and accuracy needs. @@ -3202,8 +3162,6 @@ Get trades for a specific account and symbol. | endTime | LONG | NO | | | fromId | LONG | NO | Trade id to fetch from. Default gets most recent trades. | | limit | INT | NO | Default 500; max 1000. | -| recvWindow | LONG | NO | | -| timestamp | LONG | YES | | * 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. @@ -3252,8 +3210,6 @@ Get trades for a specific account and symbol. | startTime | LONG | NO | Timestamp in ms to get funding from INCLUSIVE. | | endTime | LONG | NO | Timestamp in ms to get funding until INCLUSIVE. | | limit | INT | NO | Default 100; max 1000 | -| recvWindow | LONG | NO | | -| timestamp | LONG | YES | | * If neither `startTime` nor `endTime` is sent, the recent 7-day data will be returned. * If `incomeType ` is not sent, all kinds of flow will be returned @@ -3309,8 +3265,6 @@ Get trades for a specific account and symbol. | Name | Type | Mandatory | Description | | ---------- | ------ | --------- | ----------- | | symbol | STRING | NO | | -| recvWindow | LONG | NO | | -| timestamp | LONG | YES | | ## Position ADL Quantile Estimation (USER_DATA) @@ -3350,8 +3304,6 @@ Get trades for a specific account and symbol. | Name | Type | Mandatory | Description | | ---------- | ------ | --------- | ----------- | | symbol | STRING | NO | | -| recvWindow | LONG | NO | | -| timestamp | LONG | YES | | * Values update every 30s. * Values 0, 1, 2, 3, 4 shows the queue position and possibility of ADL from low to high. @@ -3427,8 +3379,6 @@ Get trades for a specific account and symbol. | startTime | LONG | NO | | | endTime | LONG | NO | | | limit | INT | NO | Default 50; max 100. | -| recvWindow | LONG | NO | | -| timestamp | LONG | YES | | * If "autoCloseType" is not sent, orders with both of the types will be returned * If "startTime" is not sent, data within 7 days before "endTime" can be queried @@ -3455,8 +3405,6 @@ Get trades for a specific account and symbol. | Name | Type | Mandatory | Description | | ---------- | ------ | --------- | ----------- | | symbol | STRING | YES | | -| recvWindow | LONG | NO | | -| timestamp | LONG | YES | | # User Data Streams @@ -3881,11 +3829,6 @@ Codes are universal,but messages can vary. * This operation is not supported. -> -1021 INVALID_TIMESTAMP - -* Timestamp for this request is outside of the recvWindow. -* Timestamp for this request was 1000ms ahead of the server's time. - > -1022 INVALID_SIGNATURE * Signature for this request is not valid. diff --git a/aster-finance-futures-api-v3_CN.md b/aster-finance-futures-api-v3_CN.md index e5f735f..3df28ea 100644 --- a/aster-finance-futures-api-v3_CN.md +++ b/aster-finance-futures-api-v3_CN.md @@ -2236,8 +2236,6 @@ POST /fapi/v3/multiAssetsMargin (HMAC SHA256) 名称 | 类型 | 是否必需 | 描述 ---------- | ------ | -------- | ----------------- multiAssetsMargin | STRING | YES | "true": 联合保证金模式开启;"false": 联合保证金模式关闭 -recvWindow | LONG | NO | -timestamp | LONG | YES | @@ -2264,8 +2262,6 @@ GET /fapi/v3/multiAssetsMargin (HMAC SHA256) 名称 | 类型 | 是否必需 | 描述 ---------- | ------ | -------- | ----------------- -recvWindow | LONG | NO | -timestamp | LONG | YES | ## 下单 (TRADE) @@ -2328,8 +2324,6 @@ timeInForce | ENUM | NO | 有效方法 workingType | ENUM | NO | stopPrice 触发类型: `MARK_PRICE`(标记价格), `CONTRACT_PRICE`(合约最新价). 默认 `CONTRACT_PRICE` priceProtect | STRING | NO | 条件单触发保护:"TRUE","FALSE", 默认"FALSE". 仅 `STOP`, `STOP_MARKET`, `TAKE_PROFIT`, `TAKE_PROFIT_MARKET` 需要此参数 newOrderRespType | ENUM | NO | "ACK", "RESULT", 默认 "ACK" -recvWindow | LONG | NO | -timestamp | LONG | YES | 根据 order `type`的不同,某些参数强制要求,具体如下: @@ -2454,8 +2448,6 @@ POST /fapi/v3/batchOrders (HMAC SHA256) 名称 | 类型 | 是否必需 | 描述 ---------------- | ------- | -------- | ---- batchOrders | list | YES | 订单列表,最多支持5个订单 -recvWindow | LONG | NO -timestamp | LONG | YES **其中``batchOrders``应以list of JSON格式填写订单参数** @@ -2511,7 +2503,6 @@ amount | DECIMAL | YES | 数量 asset | STRING | YES | 资产 clientTranId | STRING | YES | 交易id kindType | STRING | YES | 交易类型 -timestamp | LONG | YES | 时间戳 * kindType 取值为FUTURE_SPOT(期货转现货),SPOT_FUTURE(现货转期货) @@ -2570,8 +2561,6 @@ GET /fapi/v3/order (HMAC SHA256) symbol | STRING | YES | 交易对 orderId | LONG | NO | 系统订单号 origClientOrderId | STRING | NO | 用户自定义的订单号 -recvWindow | LONG | NO | -timestamp | LONG | YES | 注意: @@ -2623,8 +2612,6 @@ DELETE /fapi/v3/order (HMAC SHA256) symbol | STRING | YES | 交易对 orderId | LONG | NO | 系统订单号 origClientOrderId | STRING | NO | 用户自定义的订单号 -recvWindow | LONG | NO | -timestamp | LONG | YES | `orderId` 与 `origClientOrderId` 必须至少发送一个 @@ -2652,8 +2639,6 @@ DELETE /fapi/v3/allOpenOrders (HMAC SHA256) 名称 | 类型 | 是否必需 | 描述 ---------- | ------ | -------- | ------ symbol | STRING | YES | 交易对 -recvWindow | LONG | NO | -timestamp | LONG | YES | ## 批量撤销订单 (TRADE) @@ -2707,8 +2692,6 @@ DELETE /fapi/v3/batchOrders (HMAC SHA256) symbol | STRING | YES | 交易对 orderIdList | LIST\ | NO | 系统订单号, 最多支持10个订单
比如`[1234567,2345678]` origClientOrderIdList | LIST\ | NO | 用户自定义的订单号, 最多支持10个订单
比如`["my_id_1","my_id_2"]` 需要encode双引号。逗号后面没有空格。 -recvWindow | LONG | NO | -timestamp | LONG | YES | `orderIdList` 与 `origClientOrderIdList` 必须至少发送一个,不可同时发送 @@ -2738,8 +2721,6 @@ POST /fapi/v3/countdownCancelAll (HMAC SHA256) --------------------- | -------------- | -------- | ---------------- symbol | STRING | YES | countdownTime | LONG | YES | 倒计时。 1000 表示 1 秒; 0 表示取消倒计时撤单功能。 -recvWindow | LONG | NO | -timestamp | LONG | YES | * 该接口可以被用于确保在倒计时结束时撤销指定symbol上的所有挂单。 在使用这个功能时,接口应像心跳一样在倒计时内被反复调用,以便可以取消既有的倒计时并开始新的倒数计时设置。 @@ -2804,8 +2785,6 @@ GET /fapi/v3/openOrder (HMAC SHA256) symbol | STRING | YES | 交易对 orderId | LONG | NO | 系统订单号 origClientOrderId | STRING | NO | 用户自定义的订单号 -recvWindow | LONG | NO | -timestamp | LONG | YES | * `orderId` 与 `origClientOrderId` 中的一个为必填参数 * 查询的订单如果已经成交或取消,将返回报错 "Order does not exist." @@ -2860,8 +2839,6 @@ GET /fapi/v3/openOrders (HMAC SHA256) 名称 | 类型 | 是否必需 | 描述 ---------- | ------ | -------- | ------ symbol | STRING | NO | 交易对 -recvWindow | LONG | NO | -timestamp | LONG | YES | * 不带symbol参数,会返回所有交易对的挂单 @@ -2923,8 +2900,6 @@ orderId | LONG | NO | 只返回此orderID及之后的订单,缺省 startTime | LONG | NO | 起始时间 endTime | LONG | NO | 结束时间 limit | INT | NO | 返回的结果集数量 默认值:500 最大值:1000 -recvWindow | LONG | NO | -timestamp | LONG | YES | * 查询时间范围最大不得超过7天 * 默认查询最近7天内的数据 @@ -2962,8 +2937,6 @@ GET /fapi/v3/balance (HMAC SHA256) 名称 | 类型 | 是否必需 | 描述 ------------ | ------------ | ------------ | ------------ -recvWindow | LONG | NO | -timestamp | LONG | YES @@ -3058,8 +3031,6 @@ GET /fapi/v3/account (HMAC SHA256) 名称 | 类型 | 是否必需 | 描述 ------------ | ------------ | ------------ | ------------ -recvWindow | LONG | NO | -timestamp | LONG | YES | @@ -3091,8 +3062,6 @@ POST /fapi/v3/leverage (HMAC SHA256) ---------- | ------ | -------- | --------------------------- symbol | STRING | YES | 交易对 leverage | INT | YES | 目标杠杆倍数:1 到 125 整数 -recvWindow | LONG | NO | -timestamp | LONG | YES | ## 变换逐全仓模式 (TRADE) @@ -3121,8 +3090,6 @@ POST /fapi/v3/marginType (HMAC SHA256) ---------- | ------ | -------- | ----------------- symbol | STRING | YES | 交易对 marginType | ENUM | YES | 保证金模式 ISOLATED(逐仓), CROSSED(全仓) -recvWindow | LONG | NO | -timestamp | LONG | YES | ## 调整逐仓保证金 (TRADE) @@ -3155,8 +3122,6 @@ symbol | STRING | YES | 交易对 positionSide| ENUM | NO | 持仓方向,单向持仓模式下非必填,默认且仅可填`BOTH`;在双向持仓模式下必填,且仅可选择 `LONG` 或 `SHORT` amount | DECIMAL | YES | 保证金资金 type | INT | YES | 调整方向 1: 增加逐仓保证金,2: 减少逐仓保证金 -recvWindow | LONG | NO | -timestamp | LONG | YES | * 只针对逐仓symbol 与 positionSide(如有) @@ -3204,8 +3169,6 @@ type | INT | NO | 调整方向 1: 增加逐仓保证金,2: 减 startTime | LONG | NO | 起始时间 endTime | LONG | NO | 结束时间 limit | INT | NO | 返回的结果集数量 默认值: 500 -recvWindow | LONG | NO | -timestamp | LONG | YES | @@ -3285,8 +3248,6 @@ GET /fapi/v3/positionRisk (HMAC SHA256) 名称 | 类型 | 是否必需 | 描述 ---------- | ---- | -------- | ---- symbol | STRING | NO | -recvWindow | LONG | NO | -timestamp | LONG | YES | **注意** @@ -3339,8 +3300,6 @@ startTime | LONG | NO | 起始时间 endTime | LONG | NO | 结束时间 fromId | LONG | NO | 返回该fromId及之后的成交,缺省返回最近的成交 limit | INT | NO | 返回的结果集数量 默认值:500 最大值:1000. -recvWindow | LONG | NO | -timestamp | LONG | YES | * 如果`startTime` 和 `endTime` 均未发送, 只会返回最近7天的数据。 * startTime 和 endTime 的最大间隔为7天 @@ -3391,8 +3350,6 @@ incomeType | STRING | NO | 收益类型 "TRANSFER","WELCOME_BONUS", "REA startTime | LONG | NO | 起始时间 endTime | LONG | NO | 结束时间 limit | INT | NO | 返回的结果集数量 默认值:100 最大值:1000 -recvWindow | LONG | NO | -timestamp | LONG | YES | * 如果`startTime` 和 `endTime` 均未发送, 只会返回最近7天的数据。 * 如果`incomeType`没有发送,返回所有类型账户损益资金流水。 @@ -3454,8 +3411,6 @@ GET /fapi/v3/leverageBracket 名称 | 类型 | 是否必需 | 描述 ------ | ------ | -------- | ------ symbol | STRING | NO -recvWindow | LONG | NO | -timestamp | LONG | YES | @@ -3501,8 +3456,6 @@ GET /fapi/v3/adlQuantile 名称 | 类型 | 是否必需 | 描述 ------ | ------ | -------- | ------ symbol | STRING | NO -recvWindow|LONG|NO| -timestamp|LONG|YES| * 每30秒更新数据 @@ -3584,8 +3537,6 @@ autoCloseType | ENUM | NO | "LIQUIDATION": 强平单, "ADL": ADL减仓 startTime | LONG | NO | endTime | LONG | NO | limit | INT | NO | Default 50; max 100. -recvWindow | LONG | NO | -timestamp | LONG | YES | * 如果没有传 "autoCloseType", 强平单和ADL减仓单都会被返回 * 如果没有传"startTime", 只会返回"endTime"之前7天内的数据 @@ -3617,8 +3568,6 @@ GET /fapi/v3/commissionRate (HMAC SHA256) 名称 | 类型 | 是否必需 | 描述 ------------ | ------------ | ------------ | ------------ symbol | STRING | YES -recvWindow | LONG | NO -timestamp | LONG | YES @@ -4065,12 +4014,6 @@ None * This operation is not supported. * 不支持此操作。 -> -1021 INVALID_TIMESTAMP - * Timestamp for this request is outside of the recvWindow. - * 此请求的时间戳在recvWindow之外。 - * Timestamp for this request was 1000ms ahead of the server's time. - * 此请求的时间戳比服务器时间提前1000毫秒。 - > -1022 INVALID_SIGNATURE * Signature for this request is not valid. * 此请求的签名无效。 diff --git a/aster-finance-spot-api-v3.md b/aster-finance-spot-api-v3.md index 89487a8..951ed4a 100644 --- a/aster-finance-spot-api-v3.md +++ b/aster-finance-spot-api-v3.md @@ -2,7 +2,6 @@ * This document lists the base URL for the API endpoints: [**https://sapi.asterdex.com**](https://sapi.asterdex.com) * All API responses are in JSON format. -* All times and timestamps are in UNIX time, in **milliseconds**. ## API Key settings @@ -970,8 +969,6 @@ Get symbol fees | Name | Type | Is it required? | Description | | :---- | :---- | :---- | :---- | | symbol | STRING | YES | | -| recvWindow | LONG | NO | The assigned value cannot be greater than 60000 | -| timestamp | LONG | YES | | # Spot account and trading API @@ -1019,8 +1016,6 @@ Send order | price | DECIMAL | NO | | | newClientOrderId | STRING | NO | Client-customized unique order ID. If not provided, one will be generated automatically. | | stopPrice | DECIMAL | NO | Only STOP, STOP\_MARKET, TAKE\_PROFIT, TAKE\_PROFIT\_MARKET require this parameter | -| recvWindow | LONG | NO | The value cannot be greater than 60000 | -| timestamp | LONG | YES | | Depending on the order `type`, certain parameters are mandatory: @@ -1077,8 +1072,6 @@ Cancel active orders | symbol | STRING | YES | | | orderId | LONG | NO | | | origClientOrderId | STRING | NO | | -| recvWindow | LONG | NO | | -| timestamp | LONG | YES | | At least one of `orderId` or `origClientOrderId` must be sent. @@ -1125,8 +1118,6 @@ Query order status | symbol | STRING | YES | | | orderId | LONG | NO | | | origClientOrderId | STRING | NO | | -| recvWindow | LONG | NO | | -| timestamp | LONG | YES | | Note: @@ -1173,8 +1164,6 @@ Retrieve all current open orders for trading pairs. Use calls without a trading | Name | Type | Is it required? | Description | | :---- | :---- | :---- | :---- | | symbol | STRING | NO | | -| recvWindow | LONG | NO | | -| timestamp | LONG | YES | | * If the symbol parameter is not provided, it will return the order books for all trading pairs. @@ -1203,8 +1192,6 @@ Name | Type | Mandatory | Description symbol | STRING | YES | orderIdList | STRING | NO | orderid array string origClientOrderIdList | STRING | NO | clientOrderId array string -recvWindow | LONG | NO | -timestamp | LONG | YES | ## Query all orders (USER\_DATA) @@ -1252,8 +1239,6 @@ Retrieve all account orders; active, canceled, or completed. | startTime | LONG | NO | | | endTime | LONG | NO | | | limit | INT | NO | Default 500; maximum 1000 | -| recvWindow | LONG | NO | | -| timestamp | LONG | YES | | * The maximum query time range must not exceed 7 days. * By default, query data is from the last 7 days. @@ -1282,7 +1267,6 @@ Retrieve all account orders; active, canceled, or completed. | asset | STRING | YES | Asset | | clientTranId | STRING | YES | Transaction ID | | kindType | STRING | YES | Transaction type | -| timestamp | LONG | YES | Timestamp | * kindType FUTURE_SPOT(future to spot)/SPOT_FUTURE(spot to future) @@ -1341,8 +1325,6 @@ fee | STRING | YES | receiver | STRING | YES | The address of the current account nonce | STRING | YES | The current time in microseconds userSignature | STRING | YES | -recvWindow | LONG | NO | -timestamp | LONG | YES | **Note:** @@ -1443,8 +1425,6 @@ network | STRING | NO | userSignature | STRING | YES | apikeyIP | STRING | NO | desc | STRING | YES | -recvWindow | LONG | NO | -timestamp | LONG | YES | **Note:** * userOperationType: CREATE_API_KEY @@ -1497,8 +1477,6 @@ Retrieve current account information | Name | Type | Is it required? | Description | | :---- | :---- | :---- | :---- | -| recvWindow | LONG | NO | | -| timestamp | LONG | YES | | ## Account trade history (USER\_DATA) @@ -1541,8 +1519,6 @@ Retrieve the trade history for a specified trading pair of an account | endTime | LONG | NO | | | fromId | LONG | NO | Starting trade ID. Defaults to fetching the most recent trade. | | limit | INT | NO | Default 500; maximum 1000 | -| recvWindow | LONG | NO | | -| timestamp | LONG | YES | | * If both `startTime` and `endTime` are not sent, only data from the last 7 days will be returned. * The maximum interval between startTime and endTime is 7 days. @@ -2178,11 +2154,6 @@ Errors consist of two parts: an error code and a message. The code is standardiz * This operation is not supported. -### \-1021 INVALID\_TIMESTAMP - -* Timestamp for this request is outside of the recvWindow. -* The timestamp for this request was 1000ms ahead of the server's time. - ### \-1022 INVALID\_SIGNATURE * The signature for this request is invalid. diff --git a/aster-finance-spot-api_CN-v3.md b/aster-finance-spot-api_CN-v3.md index e0011d0..84a5862 100644 --- a/aster-finance-spot-api_CN-v3.md +++ b/aster-finance-spot-api_CN-v3.md @@ -994,8 +994,6 @@ GET /api/v3/commissionRate 名称 | 类型 | 是否必需 | 描述 ------------ | ------------ | ------------ | ------------ symbol | STRING | YES | -recvWindow | LONG | NO |赋值不能大于 ```60000``` -timestamp | LONG | YES | @@ -1051,8 +1049,6 @@ quoteOrderQty|DECIMAL|NO| price | DECIMAL | NO | newClientOrderId | STRING | NO | 客户自定义的唯一订单ID。 如果未发送,则自动生成 stopPrice | DECIMAL | NO | 仅 `STOP`, `STOP_MARKET` , `TAKE_PROFIT`,`TAKE_PROFIT_MARKET` 需要此参数。 -recvWindow | LONG | NO |赋值不能大于 ```60000``` -timestamp | LONG | YES | 基于订单 `type`不同,强制要求某些参数: @@ -1115,8 +1111,6 @@ DELETE /api/v3/order (HMAC SHA256) symbol | STRING | YES | orderId | LONG | NO | origClientOrderId | STRING | NO | -recvWindow | LONG | NO | -timestamp | LONG | YES | `orderId` 或 `origClientOrderId` 必须至少发送一个 @@ -1165,8 +1159,6 @@ GET /api/v3/order (HMAC SHA256) symbol | STRING | YES | orderId | LONG | NO | origClientOrderId | STRING | NO | -recvWindow | LONG | NO | -timestamp | LONG | YES | 注意: @@ -1213,8 +1205,6 @@ GET /api/v3/openOrder (HMAC SHA256) symbol | STRING | YES | orderId | LONG | NO | origClientOrderId | STRING | NO | -recvWindow | LONG | NO | -timestamp | LONG | YES | 注意: @@ -1263,8 +1253,6 @@ GET /api/v3/openOrders (HMAC SHA256) 名称 | 类型 | 是否必需 | 描述 ------------ | ------------ | ------------ | ------------ symbol | STRING | NO | -recvWindow | LONG | NO | -timestamp | LONG | YES | * 不带symbol参数,会返回所有交易对的挂单 @@ -1295,8 +1283,6 @@ DEL /api/v3/allOpenOrders (HMAC SHA256) symbol | STRING | YES | orderIdList | STRING | NO | id数组字符串 origClientOrderIdList | STRING | NO | clientOrderId数组字符串 -recvWindow | LONG | NO | -timestamp | LONG | YES | ## 查询所有订单 (USER_DATA) @@ -1345,8 +1331,6 @@ orderId | LONG | NO | startTime | LONG | NO | endTime | LONG | NO | limit | INT | NO | 默认 500; 最大 1000. -recvWindow | LONG | NO | -timestamp | LONG | YES |   * 查询时间范围最大不得超过7天 * 默认查询最近7天内的数据 @@ -1387,8 +1371,6 @@ type | STRING | NO | 类别 startTime | LONG | NO | 开始时间 endTime | LONG | NO | 结束时间 limit | LONG | NO | 返回的结果集数量 默认值:100 最大值:1000 -recvWindow | LONG | NO | -timestamp | LONG | YES | 注意: @@ -1422,8 +1404,6 @@ amount | DECIMAL | YES | 数量 asset | STRING | YES | 资产 clientTranId | STRING | YES | 交易id kindType | STRING | YES | 交易类型 -recvWindow | LONG | NO | -timestamp | LONG | YES | 时间戳 注意: * kindType 取值为FUTURE_SPOT(期货转现货),SPOT_FUTURE(现货转期货) @@ -1483,8 +1463,6 @@ fee | STRING | YES | receiver | STRING | YES | nonce | STRING | YES | 当前时间的微秒值 userSignature | STRING | YES | -recvWindow | LONG | NO | -timestamp | LONG | YES | 注意: * chainId: 1(ETH),56(BSC),42161(Arbi) @@ -1584,8 +1562,6 @@ network | STRING | NO | userSignature | STRING | YES | apikeyIP | STRING | NO | desc | STRING | YES | -recvWindow | LONG | NO | -timestamp | LONG | YES | 注意: * userOperationType 仅可取值: CREATE_API_KEY @@ -1642,8 +1618,6 @@ GET /api/v3/account (HMAC SHA256) 名称 | 类型 | 是否必需| 描述 ------------ | ------------ | ------------ | ------------ -recvWindow | LONG | NO | -timestamp | LONG | YES | ## 账户成交历史 (USER_DATA) @@ -1688,8 +1662,6 @@ startTime | LONG | NO | endTime | LONG | NO | fromId | LONG | NO | 起始Trade id。 默认获取最新交易。 limit | INT | NO | 默认 500; 最大 1000. -recvWindow | LONG | NO | -timestamp | LONG | YES | * 如果`startTime` 和 `endTime` 均未发送, 只会返回最近7天的数据。 * startTime 和 endTime 的最大间隔为7天 @@ -2384,12 +2356,6 @@ listenKey | STRING | YES * This operation is not supported. * 不支持此操作。 -### -1021 INVALID_TIMESTAMP - * Timestamp for this request is outside of the recvWindow. - * 此请求的时间戳在recvWindow之外。 - * Timestamp for this request was 1000ms ahead of the server's time. - * 此请求的时间戳比服务器时间提前1000毫秒。 - ### -1022 INVALID_SIGNATURE * Signature for this request is not valid. * 此请求的签名无效。 From e69f66432b82f47d8e819a627723a999e870d1bf Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Tue, 17 Mar 2026 11:16:29 +0700 Subject: [PATCH 057/131] remove tx demo --- v3-demo/requirements.txt | 4 -- v3-demo/tx.py | 104 --------------------------------------- 2 files changed, 108 deletions(-) delete mode 100644 v3-demo/requirements.txt delete mode 100644 v3-demo/tx.py diff --git a/v3-demo/requirements.txt b/v3-demo/requirements.txt deleted file mode 100644 index dd7d83a..0000000 --- a/v3-demo/requirements.txt +++ /dev/null @@ -1,4 +0,0 @@ -eth-account~=0.13.7 -eth-abi~=5.2.0 -web3~=7.11.0 -requests~=2.32.3 diff --git a/v3-demo/tx.py b/v3-demo/tx.py deleted file mode 100644 index ce386cd..0000000 --- a/v3-demo/tx.py +++ /dev/null @@ -1,104 +0,0 @@ - -#Python 3.9.6 -# eth-account~=0.13.7 -# eth-abi~=5.2.0 -# web3~=7.11.0 -# requests~=2.32.3 -# pip install -r requirements.txt - -import json -import math -import time -import requests - -from eth_abi import encode -from eth_account import Account -from eth_account.messages import encode_defunct -from web3 import Web3 - -#your main wallet address (eoa) -#你的登陆钱包地址(erc20) -user = '0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e' - -#please get these parameters from https://www.asterdex.com/en/api-wallet -#下面这些参数在这里生成配置 https://www.asterdex.com/zh-CN/api-wallet -signer='0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0' -priKey = "0x4fd0a42218f3eae43a6ce26d22544e986139a01e5b34a62db53757ffca81bae1" - -host = 'https://fapi.asterdex.com' - -placeOrder = {'url': '/fapi/v3/order', 'method': 'POST', - 'params':{'symbol': 'SANDUSDT', 'positionSide': 'BOTH', 'type': 'LIMIT', 'side': 'BUY', - 'timeInForce': 'GTC', 'quantity': "30", 'price': 0.325,'reduceOnly': True}} -getOrder = {'url':'/fapi/v3/order','method':'GET','params':{'symbol':'SANDUSDT','side':"BUY","type":'LIMIT','orderId':2194215}} - -def call(api): - nonce = math.trunc(time.time() * 1000000) - my_dict = api['params'] - send(api['url'],api['method'],sign(my_dict,nonce)) - -def sign(my_dict,nonce): - my_dict = {key: value for key, value in my_dict.items() if value is not None} - my_dict['recvWindow'] = 50000 - my_dict['timestamp'] = int(round(time.time()*1000)) - msg = trim_param(my_dict,nonce) - signable_msg = encode_defunct(hexstr=msg) - signed_message = Account.sign_message(signable_message=signable_msg, private_key=priKey) - my_dict['nonce'] = nonce - my_dict['user'] = user - my_dict['signer'] = signer - my_dict['signature'] = '0x'+signed_message.signature.hex() - - print(my_dict['signature']) - return my_dict - -def trim_param(my_dict,nonce) -> str: - _trim_dict(my_dict) - json_str = json.dumps(my_dict, sort_keys=True).replace(' ', '').replace('\'','\"') - print(json_str) - encoded = encode(['string', 'address', 'address', 'uint256'], [json_str, user, signer, nonce]) - print(encoded.hex()) - keccak_hex =Web3.keccak(encoded).hex() - print(keccak_hex) - return keccak_hex - -def _trim_dict(my_dict) : - for key in my_dict: - value = my_dict[key] - if isinstance(value, list): - new_value = [] - for item in value: - if isinstance(item, dict): - new_value.append(json.dumps(_trim_dict(item))) - else: - new_value.append(str(item)) - my_dict[key] = json.dumps(new_value) - continue - if isinstance(value, dict): - my_dict[key] = json.dumps(_trim_dict(value)) - continue - my_dict[key] = str(value) - - return my_dict - -def send(url, method, my_dict): - url = host + url - print(url) - print(my_dict) - if method == 'POST': - headers = { - 'Content-Type': 'application/x-www-form-urlencoded', - 'User-Agent': 'PythonApp/1.0' - } - res = requests.post(url, data=my_dict, headers=headers) - print(res.text) - if method == 'GET': - res = requests.get(url, params=my_dict) - print(res.text) - if method == 'DELETE': - res = requests.delete(url, data=my_dict) - print(res.text) - -if __name__ == '__main__': - # call(placeOrder) - call(getOrder) From 097d3bc588d9a70fe0ba441f3a1046c895d65d2d Mon Sep 17 00:00:00 2001 From: Vanessa Date: Tue, 17 Mar 2026 20:41:11 +0800 Subject: [PATCH 058/131] asterchain doc --- README.md | 4 + aster-chain-rpc.md | 312 ++++++++++++++++++++++++++++++++++++++++++ aster-chain-rpc_CN.md | 312 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 628 insertions(+) create mode 100644 aster-chain-rpc.md create mode 100644 aster-chain-rpc_CN.md diff --git a/README.md b/README.md index e1849c3..eb08047 100644 --- a/README.md +++ b/README.md @@ -53,3 +53,7 @@ # Aster 充值提现 [Aster Deposit and Withdrawal](./aster-deposit-withdrawal.md) + +# Aster Chain RPC + +[Aster Chain RPC](./aster-chain-rpc.md) diff --git a/aster-chain-rpc.md b/aster-chain-rpc.md new file mode 100644 index 0000000..9600b81 --- /dev/null +++ b/aster-chain-rpc.md @@ -0,0 +1,312 @@ +- [General Info](#general-info) + - [General API Information](#general-api-information) +- [Chain RPC Endpoints](#chain-rpc-endpoints) + - [Get Balance](#get-balance) + - [Get Open Orders](#get-open-orders) + - [Get User Fills](#get-user-fills) + +# General Info + +## General API Information + +* All endpoints use JSON-RPC 2.0 protocol via HTTP POST. +* The base endpoint is: **https://tapi.asterdex.com/info** +* All requests must set `Content-Type: application/json`. +* The `blockTag` parameter accepts `"latest"` to query the most recent state. +* All time-related fields are in milliseconds. + +> **Note:** The following endpoints only return data when the user has **privacy mode disabled**. If privacy mode is enabled, no data will be returned. + +--- + +# Chain RPC Endpoints + +## Get Balance + +`` +POST /info +`` + +Query the account balance and position information for a given address. + +**Method:** `aster_getBalance` + +**Weight:** +1 + +**Parameters (params array):** + +Index | Name | Type | Mandatory | Description +----- | ---- | ---- | --------- | ----------- +0 | address | STRING | YES | The wallet address to query +1 | blockTag | STRING | YES | Block tag, use `"latest"` for the most recent state + +> **Request Example:** + +```shell +curl -X POST "https://tapi.asterdex.com/info" \ + -H "accept: */*" \ + -H "Content-Type: application/json" \ + -d '{ + "id": {}, + "jsonrpc": "2.0", + "method": "aster_getBalance", + "params": [ + "0x690931c*********", + "latest" + ] + }' +``` + +> **Response:** + +```javascript +{ + "result": { + "address": "0x690931c*********", + "accountPrivy": "disabled", + "perpAssets": [ + { + "asset": "USD1", + "walletBalance": 200.00000000 + }, + { + "asset": "USDT", + "walletBalance": 9049204461.84438644 + } + ], + "positions": [ + { + "tradingProduct": "perps", + "positions": [ + { + "id": "98000000000389_BTCUSDT_BOTH", + "symbol": "BTCUSDT", + "collateral": "USDT", + "positionAmount": "1.340", + "entryPrice": "84490.74932115", + "unrealizedProfit": "-13990.31797537", + "askNotional": "0", + "bidNotional": "60", + "notionalValue": "99227.28611496", + "markPrice": "74050.21351863", + "leverage": 1, + "isolated": false, + "isolatedWallet": "0", + "adl": 1, + "positionSide": "BOTH", + "marginValue": "99227.28611496" + } + ] + } + ] + }, + "id": {}, + "jsonrpc": "2.0" +} +``` + +**Response Fields:** + +Name | Type | Description +---- | ---- | ----------- +address | STRING | Wallet address +accountPrivy | STRING | Privacy mode status: `"disabled"` or `"enabled"` +perpAssets | ARRAY | List of perpetual assets and balances +perpAssets[].asset | STRING | Asset name +perpAssets[].walletBalance | DECIMAL | Wallet balance +positions | ARRAY | List of position groups by trading product +positions[].tradingProduct | STRING | Trading product type (e.g. `"perps"`) +positions[].positions[].id | STRING | Position ID +positions[].positions[].symbol | STRING | Trading pair symbol +positions[].positions[].collateral | STRING | Collateral asset +positions[].positions[].positionAmount | STRING | Position size +positions[].positions[].entryPrice | STRING | Average entry price +positions[].positions[].unrealizedProfit | STRING | Unrealized profit/loss +positions[].positions[].notionalValue | STRING | Position notional value +positions[].positions[].markPrice | STRING | Current mark price +positions[].positions[].leverage | INT | Leverage +positions[].positions[].isolated | BOOLEAN | Whether isolated margin mode +positions[].positions[].isolatedWallet | STRING | Isolated wallet balance +positions[].positions[].adl | INT | ADL quantile +positions[].positions[].positionSide | STRING | Position side: `BOTH`, `LONG`, or `SHORT` +positions[].positions[].marginValue | STRING | Margin value + + +## Get Open Orders + +`` +POST /info +`` + +Query all open orders for a given address. + +**Method:** `aster_openOrders` + +**Weight:** +1 + +**Parameters (params array):** + +Index | Name | Type | Mandatory | Description +----- | ---- | ---- | --------- | ----------- +0 | address | STRING | YES | The wallet address to query +1 | symbol | STRING | NO | Trading pair symbol (e.g. `"BTCUSDT"`); pass `""` to query all symbols +2 | blockTag | STRING | YES | Block tag, use `"latest"` for the most recent state + +> **Request Example:** + +```shell +curl -X POST "https://tapi.asterdex.com/info" \ + -H "accept: */*" \ + -H "Content-Type: application/json" \ + -d '{ + "id": {}, + "jsonrpc": "2.0", + "method": "aster_openOrders", + "params": [ + "0x690931c*********", + "", + "latest" + ] + }' +``` + +> **Response:** + +```javascript +{ + "result": { + "address": "0x690931c*********", + "accountPrivy": "disabled", + "openOrders": [ + { + "orderId": "web_AD_7jz2xjo0ma4nblniq_98", + "symbol": "TRUMPUSDT", + "side": "SELL", + "type": "LIMIT", + "origQty": "4.44000000", + "status": "NEW" + }, + { + "orderId": "web_AD_4u1emfjslzt4hqnc5_98", + "symbol": "BTCUSDT", + "side": "BUY", + "type": "LIMIT", + "origQty": "0.00100000", + "status": "NEW" + } + ] + }, + "id": {}, + "jsonrpc": "2.0" +} +``` + +**Response Fields:** + +Name | Type | Description +---- | ---- | ----------- +address | STRING | Wallet address +accountPrivy | STRING | Privacy mode status: `"disabled"` or `"enabled"` +openOrders | ARRAY | List of open orders +openOrders[].orderId | STRING | Order ID +openOrders[].symbol | STRING | Trading pair symbol +openOrders[].side | STRING | Order side: `BUY` or `SELL` +openOrders[].type | STRING | Order type: e.g. `LIMIT`, `MARKET` +openOrders[].origQty | STRING | Original order quantity +openOrders[].status | STRING | Order status: e.g. `NEW` + + +## Get User Fills + +`` +POST /info +`` + +Query the trade fill history for a given address within a specified time range. + +**Method:** `aster_userFills` + +**Weight:** +1 + +**Parameters (params array):** + +Index | Name | Type | Mandatory | Description +----- | ---- | ---- | --------- | ----------- +0 | address | STRING | YES | The wallet address to query +1 | symbol | STRING | YES | Trading pair symbol (e.g. `"BTCUSDT"`) +2 | from | LONG | YES | Start time in milliseconds +3 | to | LONG | YES | End time in milliseconds +4 | limit | INT | YES | Number of records per page; max `1000` per request +5 | page | INT | YES | Page number, starting from `1` +6 | blockTag | STRING | YES | Block tag, use `"latest"` for the most recent state + +> **Request Example:** + +```shell +curl -X POST "https://tapi.asterdex.com/info" \ + -H "accept: */*" \ + -H "Content-Type: application/json" \ + -d '{ + "id": {}, + "jsonrpc": "2.0", + "method": "aster_userFills", + "params": [ + "0x690931c*********", + "BTCUSDT", + 1772887745000, + 1773146945000, + 2, + 1, + "latest" + ] + }' +``` + +> **Response:** + +```javascript +{ + "result": { + "address": "0x690931c*********", + "accountPrivy": "disabled", + "startTime": 1772887745000, + "endTime": 1783146945000, + "fills": [ + { + "symbol": "BTCUSDT", + "side": "BUY", + "price": "71087.9", + "qty": "0.00100000", + "time": 1773405618000 + }, + { + "symbol": "BTCUSDT", + "side": "BUY", + "price": "71088.1", + "qty": "0.00100000", + "time": 1773401493000 + } + ] + }, + "id": {}, + "jsonrpc": "2.0" +} +``` + +**Response Fields:** + +Name | Type | Description +---- | ---- | ----------- +address | STRING | Wallet address +accountPrivy | STRING | Privacy mode status: `"disabled"` or `"enabled"` +startTime | LONG | Query start time in milliseconds +endTime | LONG | Query end time in milliseconds +fills | ARRAY | List of trade fills +fills[].symbol | STRING | Trading pair symbol +fills[].side | STRING | Trade side: `BUY` or `SELL` +fills[].price | STRING | Fill price +fills[].qty | STRING | Fill quantity +fills[].time | LONG | Fill time in milliseconds \ No newline at end of file diff --git a/aster-chain-rpc_CN.md b/aster-chain-rpc_CN.md new file mode 100644 index 0000000..07b0324 --- /dev/null +++ b/aster-chain-rpc_CN.md @@ -0,0 +1,312 @@ +- [基本信息](#基本信息) + - [接口通用说明](#接口通用说明) +- [链上 RPC 接口](#链上-rpc-接口) + - [查询账户余额](#查询账户余额) + - [查询当前挂单](#查询当前挂单) + - [查询用户成交记录](#查询用户成交记录) + +# 基本信息 + +## 接口通用说明 + +* 所有接口均采用 JSON-RPC 2.0 协议,通过 HTTP POST 方式调用。 +* 接口基础地址:**https://tapi.asterdex.com/info** +* 所有请求需设置请求头 `Content-Type: application/json`。 +* `blockTag` 参数传入 `"latest"` 表示查询最新状态。 +* 所有时间相关字段均为毫秒级时间戳。 + +> **注意:** 以下接口仅在用户**关闭隐私模式**时返回数据。如果用户开启了隐私模式,接口将不返回任何数据。 + +--- + +# 链上 RPC 接口 + +## 查询账户余额 + +`` +POST /info +`` + +查询指定地址的账户余额及持仓信息。 + +**方法名:** `aster_getBalance` + +**权重:** +1 + +**请求参数(params 数组):** + +下标 | 参数名 | 类型 | 是否必填 | 说明 +---- | ------ | ---- | -------- | ---- +0 | address | STRING | 是 | 要查询的钱包地址 +1 | blockTag | STRING | 是 | 区块标签,传入 `"latest"` 表示查询最新状态 + +> **请求示例:** + +```shell +curl -X POST "https://tapi.asterdex.com/info" \ + -H "accept: */*" \ + -H "Content-Type: application/json" \ + -d '{ + "id": {}, + "jsonrpc": "2.0", + "method": "aster_getBalance", + "params": [ + "0x690931c*********", + "latest" + ] + }' +``` + +> **返回结果:** + +```javascript +{ + "result": { + "address": "0x690931c*********", + "accountPrivy": "disabled", + "perpAssets": [ + { + "asset": "USD1", + "walletBalance": 200.00000000 + }, + { + "asset": "USDT", + "walletBalance": 9049204461.84438644 + } + ], + "positions": [ + { + "tradingProduct": "perps", + "positions": [ + { + "id": "98000000000389_BTCUSDT_BOTH", + "symbol": "BTCUSDT", + "collateral": "USDT", + "positionAmount": "1.340", + "entryPrice": "84490.74932115", + "unrealizedProfit": "-13990.31797537", + "askNotional": "0", + "bidNotional": "60", + "notionalValue": "99227.28611496", + "markPrice": "74050.21351863", + "leverage": 1, + "isolated": false, + "isolatedWallet": "0", + "adl": 1, + "positionSide": "BOTH", + "marginValue": "99227.28611496" + } + ] + } + ] + }, + "id": {}, + "jsonrpc": "2.0" +} +``` + +**返回字段说明:** + +字段名 | 类型 | 说明 +------ | ---- | ---- +address | STRING | 钱包地址 +accountPrivy | STRING | 隐私模式状态:`"disabled"` 已关闭 / `"enabled"` 已开启 +perpAssets | ARRAY | 永续合约资产列表 +perpAssets[].asset | STRING | 资产名称 +perpAssets[].walletBalance | DECIMAL | 钱包余额 +positions | ARRAY | 按交易产品分组的持仓列表 +positions[].tradingProduct | STRING | 交易产品类型(如 `"perps"`) +positions[].positions[].id | STRING | 持仓 ID +positions[].positions[].symbol | STRING | 交易对名称 +positions[].positions[].collateral | STRING | 保证金资产 +positions[].positions[].positionAmount | STRING | 持仓数量 +positions[].positions[].entryPrice | STRING | 平均开仓价格 +positions[].positions[].unrealizedProfit | STRING | 未实现盈亏 +positions[].positions[].notionalValue | STRING | 持仓名义价值 +positions[].positions[].markPrice | STRING | 当前标记价格 +positions[].positions[].leverage | INT | 杠杆倍数 +positions[].positions[].isolated | BOOLEAN | 是否逐仓模式 +positions[].positions[].isolatedWallet | STRING | 逐仓钱包余额 +positions[].positions[].adl | INT | ADL 排队等级 +positions[].positions[].positionSide | STRING | 持仓方向:`BOTH`、`LONG` 或 `SHORT` +positions[].positions[].marginValue | STRING | 保证金价值 + + +## 查询当前挂单 + +`` +POST /info +`` + +查询指定地址的所有当前挂单。 + +**方法名:** `aster_openOrders` + +**权重:** +1 + +**请求参数(params 数组):** + +下标 | 参数名 | 类型 | 是否必填 | 说明 +---- | ------ | ---- | -------- | ---- +0 | address | STRING | 是 | 要查询的钱包地址 +1 | symbol | STRING | 否 | 交易对名称(如 `"BTCUSDT"`);传入 `""` 查询所有交易对 +2 | blockTag | STRING | 是 | 区块标签,传入 `"latest"` 表示查询最新状态 + +> **请求示例:** + +```shell +curl -X POST "https://tapi.asterdex.com/info" \ + -H "accept: */*" \ + -H "Content-Type: application/json" \ + -d '{ + "id": {}, + "jsonrpc": "2.0", + "method": "aster_openOrders", + "params": [ + "0x690931c*********", + "", + "latest" + ] + }' +``` + +> **返回结果:** + +```javascript +{ + "result": { + "address": "0x690931c*********", + "accountPrivy": "disabled", + "openOrders": [ + { + "orderId": "web_AD_7jz2xjo0ma4nblniq_98", + "symbol": "TRUMPUSDT", + "side": "SELL", + "type": "LIMIT", + "origQty": "4.44000000", + "status": "NEW" + }, + { + "orderId": "web_AD_4u1emfjslzt4hqnc5_98", + "symbol": "BTCUSDT", + "side": "BUY", + "type": "LIMIT", + "origQty": "0.00100000", + "status": "NEW" + } + ] + }, + "id": {}, + "jsonrpc": "2.0" +} +``` + +**返回字段说明:** + +字段名 | 类型 | 说明 +------ | ---- | ---- +address | STRING | 钱包地址 +accountPrivy | STRING | 隐私模式状态:`"disabled"` 已关闭 / `"enabled"` 已开启 +openOrders | ARRAY | 当前挂单列表 +openOrders[].orderId | STRING | 订单 ID +openOrders[].symbol | STRING | 交易对名称 +openOrders[].side | STRING | 买卖方向:`BUY` 买入 / `SELL` 卖出 +openOrders[].type | STRING | 订单类型:如 `LIMIT` 限价单、`MARKET` 市价单 +openOrders[].origQty | STRING | 原始委托数量 +openOrders[].status | STRING | 订单状态:如 `NEW` 待成交 + + +## 查询用户成交记录 + +`` +POST /info +`` + +查询指定地址在指定时间范围内的历史成交记录。 + +**方法名:** `aster_userFills` + +**权重:** +1 + +**请求参数(params 数组):** + +下标 | 参数名 | 类型 | 是否必填 | 说明 +---- | ------ | ---- | -------- | ---- +0 | address | STRING | 是 | 要查询的钱包地址 +1 | symbol | STRING | 是 | 交易对名称(如 `"BTCUSDT"`) +2 | from | LONG | 是 | 查询起始时间(毫秒时间戳) +3 | to | LONG | 是 | 查询结束时间(毫秒时间戳) +4 | limit | INT | 是 | 每页返回条数,每次最多返回 `1000` 条 +5 | page | INT | 是 | 页码,从 `1` 开始 +6 | blockTag | STRING | 是 | 区块标签,传入 `"latest"` 表示查询最新状态 + +> **请求示例:** + +```shell +curl -X POST "https://tapi.asterdex.com/info" \ + -H "accept: */*" \ + -H "Content-Type: application/json" \ + -d '{ + "id": {}, + "jsonrpc": "2.0", + "method": "aster_userFills", + "params": [ + "0x690931c*********", + "BTCUSDT", + 1772887745000, + 1773146945000, + 2, + 1, + "latest" + ] + }' +``` + +> **返回结果:** + +```javascript +{ + "result": { + "address": "0x690931c*********", + "accountPrivy": "disabled", + "startTime": 1772887745000, + "endTime": 1783146945000, + "fills": [ + { + "symbol": "BTCUSDT", + "side": "BUY", + "price": "71087.9", + "qty": "0.00100000", + "time": 1773405618000 + }, + { + "symbol": "BTCUSDT", + "side": "BUY", + "price": "71088.1", + "qty": "0.00100000", + "time": 1773401493000 + } + ] + }, + "id": {}, + "jsonrpc": "2.0" +} +``` + +**返回字段说明:** + +字段名 | 类型 | 说明 +------ | ---- | ---- +address | STRING | 钱包地址 +accountPrivy | STRING | 隐私模式状态:`"disabled"` 已关闭 / `"enabled"` 已开启 +startTime | LONG | 查询起始时间(毫秒时间戳) +endTime | LONG | 查询结束时间(毫秒时间戳) +fills | ARRAY | 成交记录列表 +fills[].symbol | STRING | 交易对名称 +fills[].side | STRING | 成交方向:`BUY` 买入 / `SELL` 卖出 +fills[].price | STRING | 成交价格 +fills[].qty | STRING | 成交数量 +fills[].time | LONG | 成交时间(毫秒时间戳) \ No newline at end of file From 6a5e185746571ce7598686f3ea2bf0fb13d54164 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Tue, 17 Mar 2026 20:57:58 +0700 Subject: [PATCH 059/131] trade pro and nonce expalin --- aster-finance-futures-api-v3.md | 50 +++++++++++++++++++++++++++ aster-finance-futures-api-v3_CN.md | 55 ++++++++++++++++++++++++++++++ aster-finance-futures-api.md | 44 ++++++++++++++++++++++++ aster-finance-futures-api_CN.md | 43 +++++++++++++++++++++++ aster-finance-spot-api-v3.md | 49 ++++++++++++++++++++++++++ aster-finance-spot-api_CN-v3.md | 53 ++++++++++++++++++++++++++++ 6 files changed, 294 insertions(+) diff --git a/aster-finance-futures-api-v3.md b/aster-finance-futures-api-v3.md index 3e1bfe0..c90cc1b 100644 --- a/aster-finance-futures-api-v3.md +++ b/aster-finance-futures-api-v3.md @@ -4,6 +4,7 @@ - [HTTP Return Codes](#http-return-codes) - [Error Codes and Messages](#error-codes-and-messages) - [General Information on Endpoints](#general-information-on-endpoints) + - [V3 Nonce Mechanism](#v3-nonce-mechanism) - [LIMITS](#limits) - [IP Limits](#ip-limits) - [Order Rate Limits](#order-rate-limits) @@ -101,6 +102,7 @@ - [Event: Balance and Position Update](#event-balance-and-position-update) - [Event: Order Update](#event-order-update) - [Event: Account Configuration Update previous Leverage Update](#event-account-configuration-update-previous-leverage-update) + - [Event: TradePro](#event-tradepro) - [Error Codes](#error-codes) - [10xx - General Server or Network issues](#10xx---general-server-or-network-issues) - [11xx - Request issues](#11xx---request-issues) @@ -152,6 +154,10 @@ * For POST, PUT, and DELETE method APIs, send data in the request body (content type application/x-www-form-urlencoded) * Parameters may be sent in any order. +### V3 Nonce Mechanism + +* A nonce is simply a number used to validate user sends is valid, not repeated, and not outdated. You can think of it like keeping a small list of the user’s most recent actions, each identified by a unique number (called a nonce). When a new action comes in, the system first checks if that number has already been used—if it has, the action is rejected as a duplicate. If it’s new, the system then checks whether it’s too old compared to the recent ones it has already seen. To do this efficiently, it only keeps a limited number of the most recent nonces for each user. If the list is already full and the new number is smaller than the oldest one in the list, it gets rejected because it’s considered outdated. Otherwise, the system removes the oldest number and adds the new one. In simple terms, this mechanism ensures that user actions are processed in a clean and reliable way—preventing repeated requests, ignoring stale ones, and only keeping track of the most relevant recent activity. + ## LIMITS * The `/fapi/v3/exchangeInfo` `rateLimits` array contains objects related to the exchange's `RAW_REQUEST`, `REQUEST_WEIGHT`, and `ORDER` rate limits. These are further defined in the `ENUM definitions` section under `Rate limiters (rateLimitType)`. @@ -3749,6 +3755,50 @@ When the leverage of a trade pair changes, the payload will contain the object ` When the user Multi-Assets margin mode changes the payload will contain the object `ai` representing the user account configuration, where `j` represents the user Multi-Assets margin mode +## Event: TradePro + +> **Topic Subscribe:** + +```javascript +{ + "method": "SUBSCRIBE", + "params": [ + "btcusdt@tradepro" + ], + "id": 3 +} +``` + +> **Payload:** + +```javascript +{ + "stream": "btcusdt@tradepro", + "data": { + "e": "tradepro", + "E": 1773751963081, + "T": 1773751963079, + "s": "BTCUSDT", + "t": 128884613, + "p": "73685.5", + "q": "0.297", + "h": "0X0000000000000000000000000000000000000000000000000000000000000000", + "m": [ + "hidden", + "hidden" + ] + } +} +``` + +* h: Transaction hash of the trade. + +* m: Array containing the participant addresses: + + * m[0]: Taker address + + * m[1]: Maker address + # Error Codes > Here is the error JSON payload: diff --git a/aster-finance-futures-api-v3_CN.md b/aster-finance-futures-api-v3_CN.md index 3df28ea..24597e9 100644 --- a/aster-finance-futures-api-v3_CN.md +++ b/aster-finance-futures-api-v3_CN.md @@ -3,6 +3,7 @@ - [HTTP 返回代码](#http-返回代码) - [接口错误代码](#接口错误代码) - [接口的基本信息](#接口的基本信息) + - [V3 Nonce 机制](#v3-nonce-机制) - [访问限制](#访问限制) - [IP 访问限制](#ip-访问限制) - [下单频率限制](#下单频率限制) @@ -99,6 +100,7 @@ - [Balance和Position更新推送](#balance和position更新推送) - [订单/交易 更新推送](#订单交易-更新推送) - [杠杆倍数等账户配置 更新推送](#杠杆倍数等账户配置-更新推送) + - [Event: TradePro](#event-tradepro) - [错误代码](#错误代码) - [10xx - 常规服务器或网络问题](#10xx---常规服务器或网络问题) - [11xx - Request issues](#11xx---request-issues) @@ -146,6 +148,17 @@ * `POST`, `PUT`, 和 `DELETE` 方法的接口, 在 `request body`中发送(content type `application/x-www-form-urlencoded`) * 对参数的顺序不做要求。 +### V3 Nonce 机制 + +* nonce 本质上是一个用于校验用户请求是否有效、是否重复以及是否过期的数字。你可以把它理解为系统为每个用户维护的一小段“最近操作记录”,每个操作都用一个唯一的数字(即 nonce)来标识。 + +* 当一个新的请求到来时,系统会先检查这个 nonce 是否已经被使用过——如果是,就会将该请求判定为重复请求并拒绝。如果是新的 nonce,系统会进一步判断它是否相对于当前已记录的那些 nonce 来说过旧。 + +* 为了提高效率,系统只会为每个用户保存有限数量的最近 nonce。如果这个列表已经满了,而新的 nonce 又比列表中最旧的那个还小,那么该请求就会被拒绝,因为它被认为是过期的。否则,系统会移除最旧的 nonce,并将新的 nonce 加入列表。 + +* 简单来说,这种机制可以确保用户请求以一种干净、可靠的方式被处理——既能防止重复请求,又能忽略过期请求,同时只保留最相关的近期操作记录。 + + ## 访问限制 * 在 `/fapi/v3/exchangeInfo`接口中`rateLimits`数组里包含有REST接口(不限于本篇的REST接口)的访问限制。包括带权重的访问频次限制、下单速率限制。本篇`枚举定义`章节有限制类型的进一步说明。 * 违反上述任何一个访问限制都会收到HTTP 429,这是一个警告. @@ -3941,7 +3954,49 @@ None 当用户联合保证金状态发生变化时推送消息体会包含对象`ai`表示用户账户配置,其中`j`代表用户联合保证金状态 +## Event: TradePro + +> **Topic Subscribe:** + +```javascript +{ + "method": "SUBSCRIBE", + "params": [ + "btcusdt@tradepro" + ], + "id": 3 +} +``` + +> **Payload:** + +```javascript +{ + "stream": "btcusdt@tradepro", + "data": { + "e": "tradepro", + "E": 1773751963081, + "T": 1773751963079, + "s": "BTCUSDT", + "t": 128884613, + "p": "73685.5", + "q": "0.297", + "h": "0X0000000000000000000000000000000000000000000000000000000000000000", + "m": [ + "hidden", + "hidden" + ] + } +} +``` + +* h: 该笔交易的交易哈希(Transaction hash) + +* m: 包含交易参与方地址的数组: + + * m[0]: Taker 地址(主动成交方) + * m[1]: Maker 地址(挂单方) # 错误代码 diff --git a/aster-finance-futures-api.md b/aster-finance-futures-api.md index 1d11082..6c08fad 100644 --- a/aster-finance-futures-api.md +++ b/aster-finance-futures-api.md @@ -104,6 +104,7 @@ - [Event: Balance and Position Update](#event-balance-and-position-update) - [Event: Order Update](#event-order-update) - [Event: Account Configuration Update previous Leverage Update](#event-account-configuration-update-previous-leverage-update) + - [Event: TradePro](#event-tradepro) - [Error Codes](#error-codes) - [10xx - General Server or Network issues](#10xx---general-server-or-network-issues) - [11xx - Request issues](#11xx---request-issues) @@ -4035,6 +4036,49 @@ When the leverage of a trade pair changes, the payload will contain the object ` When the user Multi-Assets margin mode changes the payload will contain the object `ai` representing the user account configuration, where `j` represents the user Multi-Assets margin mode +## Event: TradePro + +> **Topic Subscribe:** + +```javascript +{ + "method": "SUBSCRIBE", + "params": [ + "btcusdt@tradepro" + ], + "id": 3 +} +``` + +> **Payload:** + +```javascript +{ + "stream": "btcusdt@tradepro", + "data": { + "e": "tradepro", + "E": 1773751963081, + "T": 1773751963079, + "s": "BTCUSDT", + "t": 128884613, + "p": "73685.5", + "q": "0.297", + "h": "0X0000000000000000000000000000000000000000000000000000000000000000", + "m": [ + "hidden", + "hidden" + ] + } +} +``` + +* h: Transaction hash of the trade. + +* m: Array containing the participant addresses: + + * m[0]: Taker address + + * m[1]: Maker address # Error Codes diff --git a/aster-finance-futures-api_CN.md b/aster-finance-futures-api_CN.md index ecc383b..4275449 100644 --- a/aster-finance-futures-api_CN.md +++ b/aster-finance-futures-api_CN.md @@ -104,6 +104,7 @@ - [Balance和Position更新推送](#balance和position更新推送) - [订单/交易 更新推送](#订单交易-更新推送) - [杠杆倍数等账户配置 更新推送](#杠杆倍数等账户配置-更新推送) + - [Event: TradePro](#event-tradepro) - [错误代码](#错误代码) - [10xx - 常规服务器或网络问题](#10xx---常规服务器或网络问题) - [11xx - Request issues](#11xx---request-issues) @@ -3907,7 +3908,49 @@ None 当用户联合保证金状态发生变化时推送消息体会包含对象`ai`表示用户账户配置,其中`j`代表用户联合保证金状态 +## Event: TradePro +> **Topic Subscribe:** + +```javascript +{ + "method": "SUBSCRIBE", + "params": [ + "btcusdt@tradepro" + ], + "id": 3 +} +``` + +> **Payload:** + +```javascript +{ + "stream": "btcusdt@tradepro", + "data": { + "e": "tradepro", + "E": 1773751963081, + "T": 1773751963079, + "s": "BTCUSDT", + "t": 128884613, + "p": "73685.5", + "q": "0.297", + "h": "0X0000000000000000000000000000000000000000000000000000000000000000", + "m": [ + "hidden", + "hidden" + ] + } +} +``` + +* h: 该笔交易的交易哈希(Transaction hash) + +* m: 包含交易参与方地址的数组: + + * m[0]: Taker 地址(主动成交方) + + * m[1]: Maker 地址(挂单方) # 错误代码 diff --git a/aster-finance-spot-api-v3.md b/aster-finance-spot-api-v3.md index 951ed4a..7e61771 100644 --- a/aster-finance-spot-api-v3.md +++ b/aster-finance-spot-api-v3.md @@ -14,6 +14,10 @@ If an API Key is accidentally exposed, immediately delete that Key and generate ### Attention * TESTUSDT or any other symbols starting with TEST are symbols used for Aster’s INTERNAL TESTING ONLY. Please DO NOT trade on these symbols starting with TEST. Aster does not hold any accountability for loss of funds due to trading on these symbols. However, if you run into issues, you may contact support about this any time, we will try to help you recover your funds. +### V3 Nonce Mechanism + +* A nonce is simply a number used to validate user sends is valid, not repeated, and not outdated. You can think of it like keeping a small list of the user’s most recent actions, each identified by a unique number (called a nonce). When a new action comes in, the system first checks if that number has already been used—if it has, the action is rejected as a duplicate. If it’s new, the system then checks whether it’s too old compared to the recent ones it has already seen. To do this efficiently, it only keeps a limited number of the most recent nonces for each user. If the list is already full and the new number is smaller than the oldest one in the list, it gets rejected because it’s considered outdated. Otherwise, the system removes the oldest number and adds the new one. In simple terms, this mechanism ensures that user actions are processed in a clean and reliable way—preventing repeated requests, ignoring stale ones, and only keeping track of the most relevant recent activity. + ### HTTP return codes * HTTP `4XX` status codes are used to indicate errors in the request content, behavior, or format. The problem lies with the requester. @@ -2087,6 +2091,51 @@ Orders are updated via the `executionReport` event * TRADE \- Order had a new fill * EXPIRED \- Order expired (based on the order's Time In Force parameter) +## Event: TradePro + +> **Topic Subscribe:** + +```javascript +{ + "method": "SUBSCRIBE", + "params": [ + "btcusdt@tradepro" + ], + "id": 3 +} +``` + +> **Payload:** + +```javascript +{ + "stream": "btcusdt@tradepro", + "data": { + "e": "tradepro", + "E": 1773751963081, + "T": 1773751963079, + "s": "BTCUSDT", + "t": 128884613, + "p": "73685.5", + "q": "0.297", + "h": "0X0000000000000000000000000000000000000000000000000000000000000000", + "m": [ + "hidden", + "hidden" + ] + } +} +``` + +* h: Transaction hash of the trade. + +* m: Array containing the participant addresses: + + * m[0]: Taker address + + * m[1]: Maker address + + \#错误代码 error JSON payload: diff --git a/aster-finance-spot-api_CN-v3.md b/aster-finance-spot-api_CN-v3.md index 84a5862..5d4fa6b 100644 --- a/aster-finance-spot-api_CN-v3.md +++ b/aster-finance-spot-api_CN-v3.md @@ -40,6 +40,16 @@ * `POST`, `PUT`, 和 `DELETE` 方法的接口,参数可以在内容形式为`application/x-www-form-urlencoded`的 `query string` 中发送,也可以在 `request body` 中发送。 * 对参数的顺序不做要求。 +### V3 Nonce 机制 + +* nonce 本质上是一个用于校验用户请求是否有效、是否重复以及是否过期的数字。你可以把它理解为系统为每个用户维护的一小段“最近操作记录”,每个操作都用一个唯一的数字(即 nonce)来标识。 + +* 当一个新的请求到来时,系统会先检查这个 nonce 是否已经被使用过——如果是,就会将该请求判定为重复请求并拒绝。如果是新的 nonce,系统会进一步判断它是否相对于当前已记录的那些 nonce 来说过旧。 + +* 为了提高效率,系统只会为每个用户保存有限数量的最近 nonce。如果这个列表已经满了,而新的 nonce 又比列表中最旧的那个还小,那么该请求就会被拒绝,因为它被认为是过期的。否则,系统会移除最旧的 nonce,并将新的 nonce 加入列表。 + +* 简单来说,这种机制可以确保用户请求以一种干净、可靠的方式被处理——既能防止重复请求,又能忽略过期请求,同时只保留最相关的近期操作记录。 + --- ## 访问限制 ### 访问限制基本信息 @@ -2282,6 +2292,49 @@ listenKey | STRING | YES +## Event: TradePro + +> **Topic Subscribe:** + +```javascript +{ + "method": "SUBSCRIBE", + "params": [ + "btcusdt@tradepro" + ], + "id": 3 +} +``` + +> **Payload:** + +```javascript +{ + "stream": "btcusdt@tradepro", + "data": { + "e": "tradepro", + "E": 1773751963081, + "T": 1773751963079, + "s": "BTCUSDT", + "t": 128884613, + "p": "73685.5", + "q": "0.297", + "h": "0X0000000000000000000000000000000000000000000000000000000000000000", + "m": [ + "hidden", + "hidden" + ] + } +} +``` + +* h: 该笔交易的交易哈希(Transaction hash) + +* m: 包含交易参与方地址的数组: + + * m[0]: Taker 地址(主动成交方) + + * m[1]: Maker 地址(挂单方) From 22916ed0468c2e704b35cd6641cfef718eae2f01 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Tue, 17 Mar 2026 21:31:31 +0700 Subject: [PATCH 060/131] nonce --- aster-finance-futures-api-v3.md | 8 +++++++- aster-finance-futures-api-v3_CN.md | 3 +-- aster-finance-spot-api-v3.md | 8 +++++++- aster-finance-spot-api_CN-v3.md | 3 +-- 4 files changed, 16 insertions(+), 6 deletions(-) diff --git a/aster-finance-futures-api-v3.md b/aster-finance-futures-api-v3.md index c90cc1b..3b43463 100644 --- a/aster-finance-futures-api-v3.md +++ b/aster-finance-futures-api-v3.md @@ -156,7 +156,13 @@ ### V3 Nonce Mechanism -* A nonce is simply a number used to validate user sends is valid, not repeated, and not outdated. You can think of it like keeping a small list of the user’s most recent actions, each identified by a unique number (called a nonce). When a new action comes in, the system first checks if that number has already been used—if it has, the action is rejected as a duplicate. If it’s new, the system then checks whether it’s too old compared to the recent ones it has already seen. To do this efficiently, it only keeps a limited number of the most recent nonces for each user. If the list is already full and the new number is smaller than the oldest one in the list, it gets rejected because it’s considered outdated. Otherwise, the system removes the oldest number and adds the new one. In simple terms, this mechanism ensures that user actions are processed in a clean and reliable way—preventing repeated requests, ignoring stale ones, and only keeping track of the most relevant recent activity. +* A nonce is essentially a number used to validate that a user request is valid, not duplicated, and not outdated. It is generally recommended to use the current timestamp as the nonce, preferably with microsecond precision, to ensure uniqueness and monotonicity. + +* When a new action comes in, the system first checks if that number has already been used—if it has, the action is rejected as a duplicate. If it’s new, the system then checks whether it’s too old compared to the recent ones it has already seen. + +* To do this efficiently, it only keeps a limited number of the most recent nonces for each user. If the list is already full and the new number is smaller than the oldest one in the list, it gets rejected because it’s considered outdated. Otherwise, the system removes the oldest number and adds the new one. + +* In simple terms, this mechanism ensures that user actions are processed in a clean and reliable way—preventing repeated requests, ignoring stale ones, and only keeping track of the most relevant recent activity. ## LIMITS diff --git a/aster-finance-futures-api-v3_CN.md b/aster-finance-futures-api-v3_CN.md index 24597e9..0a74d6b 100644 --- a/aster-finance-futures-api-v3_CN.md +++ b/aster-finance-futures-api-v3_CN.md @@ -150,8 +150,7 @@ ### V3 Nonce 机制 -* nonce 本质上是一个用于校验用户请求是否有效、是否重复以及是否过期的数字。你可以把它理解为系统为每个用户维护的一小段“最近操作记录”,每个操作都用一个唯一的数字(即 nonce)来标识。 - +* nonce 本质上是一个用于校验用户请求是否有效、是否重复以及是否过期的数字。通常建议用户直接使用当前时间戳(timestamp)作为 nonce,并使用微秒级(microsecond)精度,以确保其唯一性和递增性。 * 当一个新的请求到来时,系统会先检查这个 nonce 是否已经被使用过——如果是,就会将该请求判定为重复请求并拒绝。如果是新的 nonce,系统会进一步判断它是否相对于当前已记录的那些 nonce 来说过旧。 * 为了提高效率,系统只会为每个用户保存有限数量的最近 nonce。如果这个列表已经满了,而新的 nonce 又比列表中最旧的那个还小,那么该请求就会被拒绝,因为它被认为是过期的。否则,系统会移除最旧的 nonce,并将新的 nonce 加入列表。 diff --git a/aster-finance-spot-api-v3.md b/aster-finance-spot-api-v3.md index 7e61771..a5440a9 100644 --- a/aster-finance-spot-api-v3.md +++ b/aster-finance-spot-api-v3.md @@ -16,7 +16,13 @@ If an API Key is accidentally exposed, immediately delete that Key and generate ### V3 Nonce Mechanism -* A nonce is simply a number used to validate user sends is valid, not repeated, and not outdated. You can think of it like keeping a small list of the user’s most recent actions, each identified by a unique number (called a nonce). When a new action comes in, the system first checks if that number has already been used—if it has, the action is rejected as a duplicate. If it’s new, the system then checks whether it’s too old compared to the recent ones it has already seen. To do this efficiently, it only keeps a limited number of the most recent nonces for each user. If the list is already full and the new number is smaller than the oldest one in the list, it gets rejected because it’s considered outdated. Otherwise, the system removes the oldest number and adds the new one. In simple terms, this mechanism ensures that user actions are processed in a clean and reliable way—preventing repeated requests, ignoring stale ones, and only keeping track of the most relevant recent activity. +* A nonce is essentially a number used to validate that a user request is valid, not duplicated, and not outdated. It is generally recommended to use the current timestamp as the nonce, preferably with microsecond precision, to ensure uniqueness and monotonicity. + +* When a new action comes in, the system first checks if that number has already been used—if it has, the action is rejected as a duplicate. If it’s new, the system then checks whether it’s too old compared to the recent ones it has already seen. + +* To do this efficiently, it only keeps a limited number of the most recent nonces for each user. If the list is already full and the new number is smaller than the oldest one in the list, it gets rejected because it’s considered outdated. Otherwise, the system removes the oldest number and adds the new one. + +* In simple terms, this mechanism ensures that user actions are processed in a clean and reliable way—preventing repeated requests, ignoring stale ones, and only keeping track of the most relevant recent activity. ### HTTP return codes diff --git a/aster-finance-spot-api_CN-v3.md b/aster-finance-spot-api_CN-v3.md index 5d4fa6b..b17bf1d 100644 --- a/aster-finance-spot-api_CN-v3.md +++ b/aster-finance-spot-api_CN-v3.md @@ -42,8 +42,7 @@ ### V3 Nonce 机制 -* nonce 本质上是一个用于校验用户请求是否有效、是否重复以及是否过期的数字。你可以把它理解为系统为每个用户维护的一小段“最近操作记录”,每个操作都用一个唯一的数字(即 nonce)来标识。 - +* nonce 本质上是一个用于校验用户请求是否有效、是否重复以及是否过期的数字。通常建议用户直接使用当前时间戳(timestamp)作为 nonce,并使用微秒级(microsecond)精度,以确保其唯一性和递增性。 * 当一个新的请求到来时,系统会先检查这个 nonce 是否已经被使用过——如果是,就会将该请求判定为重复请求并拒绝。如果是新的 nonce,系统会进一步判断它是否相对于当前已记录的那些 nonce 来说过旧。 * 为了提高效率,系统只会为每个用户保存有限数量的最近 nonce。如果这个列表已经满了,而新的 nonce 又比列表中最旧的那个还小,那么该请求就会被拒绝,因为它被认为是过期的。否则,系统会移除最旧的 nonce,并将新的 nonce 加入列表。 From 448ac6541c220cb6840515f494f6e8569e50ffcd Mon Sep 17 00:00:00 2001 From: aodyc Date: Wed, 18 Mar 2026 00:28:26 +0700 Subject: [PATCH 061/131] update deposit withdraw docs --- aster-deposit-withdrawal.md | 642 ++++++++++++++++++++++++++---------- 1 file changed, 476 insertions(+), 166 deletions(-) diff --git a/aster-deposit-withdrawal.md b/aster-deposit-withdrawal.md index 40ad9e4..bf1dca0 100644 --- a/aster-deposit-withdrawal.md +++ b/aster-deposit-withdrawal.md @@ -1,4 +1,30 @@ -# 1. get all deposit assets +## Table of Contents + +- [Query APIs](#query-apis) + - [get all deposit assets](#get-all-deposit-assets) + - [get all withdraw assets](#get-all-withdraw-assets) + - [estimate withdraw fee](#estimate-withdraw-fee) + - [get server time](#get-server-time) +- [Signature](#signature) + - [API-KEY Signature (V1)](#api-key-signature-v1) + - [Pro API-KEY Signature (V3)](#pro-api-key-signature-v3) + - [EVM Withdraw Signature](#evm-withdraw-signature) + - [Solana Withdraw Signature (optional)](#solana-withdraw-signature-optional) +- [Withdrawal APIs](#withdrawal-apis) + - [withdraw by fapi \[evm\] \[futures\]](#withdraw-by-fapi-evm-futures) + - [withdraw by fapi \[solana\] \[futures\]](#withdraw-by-fapi-solana-futures) + - [withdraw by API \[evm\] \[spot\]](#withdraw-by-api-evm-spot) + - [withdraw by API \[solana\] \[spot\]](#withdraw-by-api-solana-spot) + - [withdraw by fapi\[v3\] \[evm\] \[futures\]](#withdraw-by-fapiv3-evm-futures) + - [withdraw by fapi\[v3\] \[solana\] \[futures\]](#withdraw-by-fapiv3-solana-futures) + - [withdraw by fapi\[v3\] \[evm\] \[spot\]](#withdraw-by-fapiv3-evm-spot) + - [withdraw by fapi\[v3\] \[solana\] \[spot\]](#withdraw-by-fapiv3-solana-spot) + +--- + +# Query APIs + +## get all deposit assets ### request: @@ -7,11 +33,12 @@ curl 'https://www.asterdex.com/bapi/futures/v1/public/future/aster/deposit/asset ``` ### params: -|param | type | required | description | -|-----------|--------|----------|------------------------------------------------------------------------| -| chainIds | string | true | Chain ID, multiple IDs separated by commas | -| networks | string | false | Network type, e.g., EVM, SOLANA, multiple networks separated by commas | -| accountType | string | true | Account type, e.g., spot, perp | + +| param | type | required | description | +|-------------|--------|----------|------------------------------------------------------------------------| +| chainIds | string | true | Chain ID, multiple IDs separated by commas | +| networks | string | false | Network type, e.g., EVM, SOLANA, multiple networks separated by commas | +| accountType | string | true | Account type, e.g., spot, perp | ### response: @@ -49,7 +76,7 @@ curl 'https://www.asterdex.com/bapi/futures/v1/public/future/aster/deposit/asset } ``` -# 2. get all withdraw assets +## get all withdraw assets ### request: @@ -58,50 +85,51 @@ curl 'https://www.asterdex.com/bapi/futures/v1/public/future/aster/withdraw/asse ``` ### params: -|param | type | required | description | -|-----------|--------|----------|------------------------------------------------------------------------| -| chainIds | string | true | Chain ID, multiple IDs separated by commas | -| networks | string | false | Network type, e.g., EVM, SOLANA, multiple networks separated by commas | -| accountType | string | true | Account type, e.g., spot, perp | + +| param | type | required | description | +|-------------|--------|----------|------------------------------------------------------------------------| +| chainIds | string | true | Chain ID, multiple IDs separated by commas | +| networks | string | false | Network type, e.g., EVM, SOLANA, multiple networks separated by commas | +| accountType | string | true | Account type, e.g., spot, perp | ### response: ```json { - "code": "000000", - "message": null, - "messageDetail": null, - "data": [ - { - "name": "ASTER", - "displayName": "ASTER", - "contractAddress": "0x000ae314e2a2172a039b26378814c252734f556a", - "decimals": 18, - "network": "EVM", - "chainId": 56, - "withdrawType": "autoWithdraw", - "rank": 10, - "isNative": false, - "isProfit": true, - "admin": null, - "bank": null, - "tokenVaultAuthority": null, - "tokenVault": null, - "tokenMint": null, - "associatedTokenProgram": null, - "tokenProgram": null, - "systemProgram": null, - "ixSysvar": null, - "priceFeed": null, - "priceFeedProgram": null, - "solVault": null - } - ], - "success": true + "code": "000000", + "message": null, + "messageDetail": null, + "data": [ + { + "name": "ASTER", + "displayName": "ASTER", + "contractAddress": "0x000ae314e2a2172a039b26378814c252734f556a", + "decimals": 18, + "network": "EVM", + "chainId": 56, + "withdrawType": "autoWithdraw", + "rank": 10, + "isNative": false, + "isProfit": true, + "admin": null, + "bank": null, + "tokenVaultAuthority": null, + "tokenVault": null, + "tokenMint": null, + "associatedTokenProgram": null, + "tokenProgram": null, + "systemProgram": null, + "ixSysvar": null, + "priceFeed": null, + "priceFeedProgram": null, + "solVault": null + } + ], + "success": true } ``` -# 3. estimate withdraw fee +## estimate withdraw fee ### request: @@ -111,12 +139,12 @@ curl 'https://www.asterdex.com/bapi/futures/v1/public/future/aster/estimate-with ### params: -|param | type | required | description | -|------------|--------|----------|------------------------------| -| chainId | int | true | Chain ID | -| network | string | true | Network type, e.g., EVM, SOL | -| currency | string | true | Currency name, e.g., ASTER | -| accountType | string | true | Account type, e.g., spot, perp | +| param | type | required | description | +|-------------|--------|----------|--------------------------------| +| chainId | int | true | Chain ID | +| network | string | true | Network type, e.g., EVM, SOL | +| currency | string | true | Currency name, e.g., ASTER | +| accountType | string | true | Account type, e.g., spot, perp | ### response: @@ -137,11 +165,135 @@ curl 'https://www.asterdex.com/bapi/futures/v1/public/future/aster/estimate-with } ``` -- gasCost: Estimated withdrawal fee in token units +| field | desc | +|---------|-----------------------------------------| +| gasCost | Estimated withdrawal fee in token units | + +## get server time + +### request: + +```shell +curl 'https://fapi5.asterdex.com/fapi/v3/time' +``` + +### response: + +```json +{ + "serverTime": 1742198400000 +} +``` + +| field | desc | +|------------|---------------------------------------------| +| serverTime | Current server time in milliseconds (Unix) | + +--- + +# Signature + +## API-KEY Signature (V1) + +With a V1 API key, you generate your own `API_KEY` and `API_SECRET`. Every request must include the following three parameters: + +| parameter | description | +|------------|-------------------------------------------------------------------------------------------------| +| timestamp | Current time in milliseconds (Unix timestamp) | +| recvWindow | Maximum number of milliseconds the request remains valid after `timestamp` (default: `5000`) | +| signature | HMAC SHA256 signature of the full request query string or body, signed with your `API_SECRET` | + +In addition, include your `API_KEY` in the request header: + +``` +X-MBX-APIKEY: +``` + +### How to generate the signature + +Concatenate all query parameters into a single string, then sign it with your `API_SECRET` using HMAC SHA256. Append the result as the `signature` parameter. + +```javascript +const queryString = 'asset=USDT&amount=10×tamp=1742198400000&recvWindow=5000'; +const signature = CryptoJS.HmacSHA256(queryString, API_SECRET).toString(); +const finalUrl = `${baseUrl}?${queryString}&signature=${signature}`; +``` + +> The `signature` parameter must always be the **last** parameter in the query string. + +## Pro API-KEY Signature (V3) + +With a Pro API key (V3), you will be issued a dedicated EOA wallet address and its corresponding private key. Every V3 request must include the following parameters: + +| parameter | description | +|-----------|----------------------------------------------------------------------------------------------------------------------| +| nonce | Nanosecond timestamp, valid within 30 seconds. Use the [get server time](#get-server-time) API to obtain the current server time. | +| user | The user's own wallet address | +| signer | The issued EOA wallet address | +| signature | Signature of all request parameters, signed with the issued EOA wallet private key | + +### How to generate the signature + +The V3 signature is an EIP712 typed data signature. Concatenate all query parameters into a single string as the message payload, then sign it with your issued EOA private key using `signTypedData`. + +**EIP712 Domain** + +```json +{ + "name": "AsterSignTransaction", + "version": "1", + "chainId": "", + "verifyingContract": "0x0000000000000000000000000000000000000000" +} +``` + +**EIP712 Types** + +```json +{ + "Message": [ + { "name": "msg", "type": "string" } + ] +} +``` + +**Value** + +```json +{ + "msg": "" +} +``` + +**Example (JavaScript / ethers.js)** + +```javascript +const domain = { + name: 'AsterSignTransaction', + version: '1', + chainId: 1666, + verifyingContract: ethers.ZeroAddress, +}; + +const types = { + Message: [ + { name: 'msg', type: 'string' }, + ], +}; + +const queryString = 'nonce=1742198400000000000&user=0xYourAddress&signer=0xSignerAddress'; +const value = { msg: queryString }; + +const wallet = new ethers.Wallet(API_PRIVATEKEY); +const signature = await wallet.signTypedData(domain, types, value); +const finalUrl = `${baseUrl}?${queryString}&signature=${signature}`; +``` + +> The `signature` parameter must always be the **last** parameter in the query string. -# 4. withdraw signature +## EVM Withdraw Signature -* when you withdraw, you should supply a EIP712 signature. You can get the signature by signing the following message with your wallet. +* When you withdraw, you should supply an EIP712 signature. You can get the signature by signing the following message with your wallet. ### EIP712 Domain @@ -154,12 +306,12 @@ curl 'https://www.asterdex.com/bapi/futures/v1/public/future/aster/estimate-with } ``` -|field|desc| -|---|---| -|name|fix string 'Aster'| -|version|fix string '1'| -|chainId|the chainId of withdraw chain| -|verifyingContract|fix address: zero address| +| field | desc | +|-------------------|-------------------------------------| +| name | Fixed string: `Aster` | +| version | Fixed string: `1` | +| chainId | The chainId of the withdraw chain | +| verifyingContract | Fixed address: zero address | ### EIP712 Types @@ -178,89 +330,141 @@ curl 'https://www.asterdex.com/bapi/futures/v1/public/future/aster/estimate-with } ``` -|field | desc | -|---------------|-------------------------------------------------------------------------------------------------------| -|type | fix string 'Withdraw' | -|destination | the receipt address, should be user's register address | -|destination Chain | the chain name of receipt address, you can see the defination of chainName below | -|token| the name of the currency user withdraw, e.g. ASTER, you can get the name from withdraw/asset API | -|amount | the amount user withdraw in token unit, eg. '1.23' | -|fee| the fee user will pay in token unit, eg. '0.01' (you can get the fee from withdraw/estimate-withdraw-fee API) | -|nonce| a unique number, use the current timestamp in milliseconds and multiply '1000' | -|aster chain| fix string 'Mainnet' | +| field | desc | +|-------------------|-------------------------------------------------------------------------------------------------------| +| type | Fixed string: `Withdraw` | +| destination | The receipt address; should be the user's registered address | +| destination Chain | The chain name of the receipt address; see chainName definition below | +| token | The name of the currency the user withdraws, e.g., `ASTER`; get the name from the withdraw/asset API | +| amount | The amount the user withdraws in token units, e.g., `1.23` | +| fee | The fee the user will pay in token units, e.g., `0.01`; get the fee from estimate-withdraw-fee API | +| nonce | A unique number; use the current timestamp in milliseconds multiplied by `1000` | +| aster chain | Fixed string: `Mainnet` | ### chainName definition -|chainId| chainName | -|---|-----------| -|56| BSC | -|42161| Arbitrum | -|1| ETH | +| chainId | chainName | +|---------|-----------| +| 1 | ETH | +| 56 | BSC | +| 42161 | Arbitrum | -# 5. withdraw +## Solana Withdraw Signature (optional) + +When submitting a Solana withdrawal, you may optionally provide a valid signature. While the signature is not currently required, it will be enforced in a future release. It is strongly recommended to include one — only withdrawal requests carrying a valid signature will be recorded on the L1 chain. + +### How to generate the signature + +The Solana withdrawal signature is an **Ed25519 signature** over a structured message string, encoded in **Base58**. + +**Message format** + +Construct the message by joining the following fields with commas, in this exact order: + +``` +PrimaryType=Withdraw,AsterChain=Mainnet,Destination={destination},DestinationChain={destinationChain},Token={token},Amount={amount},Fee={fee},Nonce={nonce} +``` + +| field | description | +|------------------|---------------------------------------------------------------------| +| Destination | The recipient's Solana wallet address | +| DestinationChain | Fixed string: `Solana` | +| Token | Currency name, e.g., `USDT` | +| Amount | Withdraw amount with trailing zeros stripped, e.g., `1.2` not `1.20` | +| Fee | Fee amount with trailing zeros stripped, e.g., `0.1` not `0.10` | +| Nonce | Nanosecond timestamp, e.g., `1773741793787000` | + +**Example message** + +``` +PrimaryType=Withdraw,AsterChain=Mainnet,Destination=H7LqU4p4f8LDddADXDH9oFeoh3r7vhfJFf3XCEot8pkd,DestinationChain=Solana,Token=USDT,Amount=1.2,Fee=0.1,Nonce=1773741793787000 +``` + +**Example (Node.js)** + +```javascript +import { Keypair } from '@solana/web3.js'; +import nacl from 'tweetnacl'; +import bs58 from 'bs58'; + +const destination = 'H7LqU4p4f8LDddADXDH9oFeoh3r7vhfJFf3XCEot8pkd'; +const destinationChain = 'Solana'; +const token = 'USDT'; +const amount = '1.2'; +const fee = '0.1'; +const nonce = Date.now() * 1000; // nanosecond-level timestamp + +const message = `PrimaryType=Withdraw,AsterChain=Mainnet,Destination=${destination},DestinationChain=${destinationChain},Token=${token},Amount=${amount},Fee=${fee},Nonce=${nonce}`; + +const messageBytes = Buffer.from(message, 'utf8'); +const keypair = Keypair.fromSecretKey(bs58.decode(YOUR_PRIVATE_KEY)); +const signatureBytes = nacl.sign.detached(messageBytes, keypair.secretKey); +const userSignature = bs58.encode(signatureBytes); +``` + +> Trailing zeros in `Amount` and `Fee` must be stripped (e.g., `1.20` → `1.2`). A mismatch will cause signature verification to fail. + +# Withdrawal APIs + +## withdraw by fapi \[evm\] \[futures\] + +* Note: Follow the [API-KEY Signature (V1)](#api-key-signature-v1) instructions to generate the required request signature. The example below includes only the parameters specific to this endpoint. ### request: ```shell -curl -X POST "https://www.asterdex.com/bapi/futures/v1/private/future/aster/user-withdraw" -H "accept: */*" -H "x-gray-env: normal" -H "x-trace-id: fa2a5961b4a346e083f2bb0bffe39e2f" -H "Content-Type: application/json" \ --d "{ \"accountType\": \"spot\", \"amount\": \"10.2\", \"chainId\": 97, \"currency\": \"USDT\", \"fee\": \"0.01\", \"nonce\": \"1761029928213000\", \"receiver\": \"0x4C5EdB66CC7626a1C92d5178c3E5c45409BcE6D7\", \"userSignature\": \"0xc0299efe235ec194d070163b1f92ebf5d01bd820c1c08fa9730929c7a36172a9001b99203b2f9997aa7d41b7658348704e0515f4c40e76f1892f7a5b0af31daa1c\"}" +curl --location --request POST 'https://fapi.asterdex.com/fapi/aster/user-withdraw?chainId=56&asset=USDT&amount=31&fee=0.3&receiver=0x000ae314e2a2172a039b26378814c252734f556a&nonce=1761210000000000&userSignature=0xde4ca529eef20db136eed1daf1d072083431d5279e6d6e219600cf57161c5e6d1232af3c8a8ef37ba8b5963f439ef9cc2b475fe18dcc3732dda9fb93c94a3abd1c' \ + --header 'Content-Type: application/json' \ + --header 'X-MBX-APIKEY: Your API KEY' ``` ### params: -|param | type | required | description | -|--------------|--------|----------|-----------------------------------------------------------| -| accountType | string | true | Account type, e.g., spot, perp | -| amount | string | true | Withdraw amount in token unit | -| chainId | int | true | Chain ID | -| currency | string | true | Currency name, e.g., ASTER | -| fee | string | true | Withdraw fee in token unit | -| nonce | string | true | Unique number, should be the save in signature | -| receiver | string | true | Withdraw receipt address, should be the save in signature | -| userSignature | string | true | EIP712 signature | + +| param | type | required | description | +|---------------|--------|----------|---------------------------------------------------------------------| +| amount | string | true | Withdraw amount in token units | +| chainId | int | true | Chain ID | +| asset | string | true | Currency name, e.g., ASTER | +| fee | string | true | Withdraw fee in token units | +| nonce | string | true | Unique number; should be the same value used in signature | +| receiver | string | true | Withdraw receipt address; should be the same as in signature | +| userSignature | string | true | EIP712 signature | ### response: ```json { - "code": "200", - "message": "success", - "messageDetail": null, - "data": { "withdrawId": "1234567", "hash": "0x9a40f0119b670fb6b155744b51981f91c4c4c8a20c333441a63853fe7d055c90" - }, - "success": true } ``` -|field | desc | -|-----------|--------------------------------------| -|withdrawId | the withdraw request id, a unique id | -|hash | the digest of user's signature | +| field | desc | +|------------|--------------------------------------| +| withdrawId | The withdraw request ID, a unique ID | +| hash | The digest of the user's signature | -# 6. withdraw by API [evm] [futures] +## withdraw by API \[evm\] \[spot\] ### request: ```shell -curl --location --request POST 'https://fapi.asterdex.com/fapi/aster/user-withdraw?chainId=56&asset=USDT&amount=31&fee=0.3&receiver=0x000ae314e2a2172a039b26378814c252734f556a&nonce=1761210000000000&userSignature=0xde4ca529eef20db136eed1daf1d072083431d5279e6d6e219600cf57161c5e6d1232af3c8a8ef37ba8b5963f439ef9cc2b475fe18dcc3732dda9fb93c94a3abd1c&recvWindow=60000×tamp=1761230958410&signature=f5fd60da19be213d58914dd6f46bc400ada610fb916998dfc01dd346bfdad512' \ ---header 'Content-Type: application/json' \ ---header 'X-MBX-APIKEY: Your API KEY' +curl --location --request POST 'https://sapi.asterdex.com/api/v1/aster/user-withdraw?chainId=56&asset=ASTER&amount=1&fee=0.095&receiver=0x000ae314e2a2172a039b26378814c252734f556a&nonce=1761222960000000&userSignature=0x39051cc68de0fefb8e823259d3f7014fc787a8008b65d2a89d70defc48c3f91b35a4a819718c22ffcaeb143c8e1735621a0768d7c69e45ad8fbcf9bd315988423b' \ + --header 'Content-Type: application/json' \ + --header 'X-MBX-APIKEY: Your API KEY' ``` ### params: -| param | type | required | description | -|---------------|--------|----------|-----------------------------------------------------------| -| amount | string | true | Withdraw amount in token unit | -| chainId | int | true | Chain ID | -| asset | string | true | Currency name, e.g., ASTER | -| fee | string | true | Withdraw fee in token unit | -| nonce | string | true | Unique number, should be the save in signature | -| receiver | string | true | Withdraw receipt address, should be the save in signature | -| userSignature | string | true | EIP712 signature | -|timestamp|int| true| Current timestamp in milliseconds| -|recvWindow|int| false| The number of milliseconds after timestamp the request is valid for| -|signature|string| true| HMAC SHA256 signature of the request| + +| param | type | required | description | +|---------------|--------|----------|---------------------------------------------------------------------| +| amount | string | true | Withdraw amount in token units | +| chainId | int | true | Chain ID | +| asset | string | true | Currency name, e.g., ASTER | +| fee | string | true | Withdraw fee in token units | +| nonce | string | true | Unique number; should be the same value used in signature | +| receiver | string | true | Withdraw receipt address; should be the same as in signature | +| userSignature | string | true | EIP712 signature | ### response: @@ -271,34 +475,32 @@ curl --location --request POST 'https://fapi.asterdex.com/fapi/aster/user-withdr } ``` -|field | desc | -|-----------|--------------------------------------| -|withdrawId | the withdraw request id, a unique id | -|hash | the digest of user's signature | +| field | desc | +|------------|--------------------------------------| +| withdrawId | The withdraw request ID, a unique ID | +| hash | The digest of the user's signature | -# 7. withdraw by API [evm] [spot] +## withdraw by fapi \[solana\] \[futures\] ### request: ```shell -curl --location --request POST 'https://sapi.asterdex.com/api/v1/aster/user-withdraw?chainId=56&asset=ASTER&amount=1&fee=0.095&receiver=0x000ae314e2a2172a039b26378814c252734f556a&nonce=1761222960000000&userSignature=0x39051cc68de0fefb8e823259d3f7014fc787a8008b65d2a89d70defc48c3f91b35a4a819718c22ffcaeb143c8e1735621a0768d7c69e45ad8fbcf9bd315988423b&recvWindow=60000×tamp=1761230958410&signature=f5fd60da19be213d58914dd6f46bc400ada610fb916998dfc01dd346bfdad51' \ ---header 'Content-Type: application/json' \ ---header 'X-MBX-APIKEY: Your API KEY' +curl --location --request POST 'https://fapi.asterdex.com/fapi/aster/user-solana-withdraw?chainId=101&asset=USDT&amount=3&fee=0.6&receiver=4wTV1YmiEkRvAtNtsSGPtUrqRYQMe5SKy2uB4Jjaxnjf&userNonce=1773741793787000&userSignature=51pM5A46n5NzHYTtuzB7gh8FFfbkh4Aij1fceCZV2NtkiVvE7DADMnSvXFiUJvauKawdWaCfPhzCTVfXYcf1iteQ' \ + --header 'Content-Type: application/json' \ + --header 'X-MBX-APIKEY: Your API KEY' ``` ### params: -| param | type | required | description | -|---------------|--------|----------|-----------------------------------------------------------| -| amount | string | true | Withdraw amount in token unit | -| chainId | int | true | Chain ID | -| asset | string | true | Currency name, e.g., ASTER | -| fee | string | true | Withdraw fee in token unit | -| nonce | string | true | Unique number, should be the save in signature | -| receiver | string | true | Withdraw receipt address, should be the save in signature | -| userSignature | string | true | EIP712 signature | -|timestamp|int| true| Current timestamp in milliseconds| -|recvWindow|int| false| The number of milliseconds after timestamp the request is valid for| -|signature|string| true| HMAC SHA256 signature of the request| + +| param | type | required | description | +|---------------|--------|----------|---------------------------------------------------------------------| +| amount | string | true | Withdraw amount in token units | +| chainId | int | true | Fixed value: `101` | +| asset | string | true | Currency name, e.g., USDT | +| fee | string | true | Withdraw fee in token units | +| receiver | string | true | Withdraw receipt address | +| userNonce | string | false | Nanosecond timestamp; should be the same value used in signature. Not currently required but strongly recommended | +| userSignature | string | false | Ed25519 withdraw signature encoded in Base58. Not currently required but strongly recommended | ### response: @@ -309,32 +511,29 @@ curl --location --request POST 'https://sapi.asterdex.com/api/v1/aster/user-with } ``` -|field | desc | -|-----------|--------------------------------------| -|withdrawId | the withdraw request id, a unique id | -|hash | the digest of user's signature | +> Note: `hash` is not the transaction hash; it is just a unique identifier. -# 8. withdraw by API [solana] [futures] +## withdraw by API \[solana\] \[spot\] ### request: ```shell -curl --location --request POST 'https://fapi.asterdex.com/fapi/aster/user-solana-withdraw?chainId=101&asset=USDT&amount=3&fee=0.6&receiver=4wTV1YmiEkRvAtNtsSGPtUrqRYQMe5SKy2uB4Jjaxnjf&recvWindow=60000×tamp=1762440135477&signature=a773a7e83c2fe4581eb2dc0500000faa3138173ba6262316c0d83b3498dea319' \ ---header 'Content-Type: application/json' \ ---header 'X-MBX-APIKEY: Your API KEY' +curl --location --request POST 'https://sapi.asterdex.com/api/v1/aster/user-solana-withdraw?chainId=101&asset=USDT&amount=0.97&fee=0.5&receiver=BzsJhmtg2UtQWNw6764DkK5Y4GPjc1XMzRqAGqSziymK&userNonce=1773741793787000&userSignature=51pM5A46n5NzHYTtuzB7gh8FFfbkh4Aij1fceCZV2NtkiVvE7DADMnSvXFiUJvauKawdWaCfPhzCTVfXYcf1iteQ' \ + --header 'Content-Type: application/json' \ + --header 'X-MBX-APIKEY: Your API KEY' ``` ### params: -| param | type | required | description | -|---------------|--------|----------|-----------------------------------------------------------| -| amount | string | true | Withdraw amount in token unit | -| chainId | int | true | fix value 101 | -| asset | string | true | Currency name, e.g., USDT | -| fee | string | true | Withdraw fee in token unit | -| receiver | string | true | Withdraw receipt address, should be the save in signature | -|timestamp|int| true| Current timestamp in milliseconds| -|recvWindow|int| false| The number of milliseconds after timestamp the request is valid for| -|signature|string| true| HMAC SHA256 signature of the request| + +| param | type | required | description | +|---------------|--------|----------|-------------------------------------------------------------------------------------------------------------------| +| amount | string | true | Withdraw amount in token units | +| chainId | int | true | Fixed value: `101` | +| asset | string | true | Currency name, e.g., USDT | +| fee | string | true | Withdraw fee in token units | +| receiver | string | true | Withdraw receipt address | +| userNonce | string | false | Nanosecond timestamp; should be the same value used in signature. Not currently required but strongly recommended | +| userSignature | string | false | Ed25519 withdraw signature encoded in Base58. Not currently required but strongly recommended | ### response: @@ -344,29 +543,31 @@ curl --location --request POST 'https://fapi.asterdex.com/fapi/aster/user-solana "hash": "0x9a40f0119b670fb6b155744b51981f91c4c4c8a20c333441a63853fe7d055c90" } ``` -- hash is not the transaction hash, just a unique value -# 9. withdraw by API [solana] [spot] +> Note: `hash` is not the transaction hash; it is just a unique identifier. + +## withdraw by fapi\[v3\] \[evm\] \[futures\] + +* Note: Follow the [Pro API-KEY Signature (V3)](#pro-api-key-signature-v3) instructions to generate the required request signature. The example below includes only the parameters specific to this endpoint. ### request: ```shell -curl --location --request POST 'https://sapi.asterdex.com/api/v1/aster/user-solana-withdraw?chainId=101&asset=USDT&amount=0.97&fee=0.5&receiver=BzsJhmtg2UtQWNw6764DkK5Y4GPjc1XMzRqAGqSziymK&recvWindow=60000×tamp=1764663883270&signature=d2fbaef40388208b47e0326fafc50798206f5b198762110ce1bf8879b5d9da22' \ ---header 'Content-Type: application/json' \ ---header 'X-MBX-APIKEY: Your API KEY' +curl --location --request POST 'https://fapi.asterdex.com/fapi/v3/aster/user-withdraw?chainId=56&asset=USDT&amount=31&fee=0.3&receiver=0x000ae314e2a2172a039b26378814c252734f556a&userNonce=1761210000000000&userSignature=0xde4ca529eef20db136eed1daf1d072083431d5279e6d6e219600cf57161c5e6d1232af3c8a8ef37ba8b5963f439ef9cc2b475fe18dcc3732dda9fb93c94a3abd1c' \ + --header 'Content-Type: application/json' ``` ### params: -| param | type | required | description | -|---------------|--------|----------|-----------------------------------------------------------| -| amount | string | true | Withdraw amount in token unit | -| chainId | int | true | fix value 101 | -| asset | string | true | Currency name, e.g., USDT | -| fee | string | true | Withdraw fee in token unit | -| receiver | string | true | Withdraw receipt address, should be the save in signature | -|timestamp|int| true| Current timestamp in milliseconds| -|recvWindow|int| false| The number of milliseconds after timestamp the request is valid for| -|signature|string| true| HMAC SHA256 signature of the request| + +| param | type | required | description | +|---------------|--------|----------|--------------------------------------------------------------------------------------------------------------------| +| amount | string | true | Withdraw amount in token units | +| chainId | int | true | Chain ID | +| asset | string | true | Currency name, e.g., ASTER | +| fee | string | true | Withdraw fee in token units | +| userNonce | string | true | Nanosecond timestamp for the EVM withdraw signature; separate from V3 API `nonce`, may differ by up to 1 hour | +| receiver | string | true | Withdraw receipt address; should be the same as in signature | +| userSignature | string | true | EIP712 withdraw signature | ### response: @@ -376,4 +577,113 @@ curl --location --request POST 'https://sapi.asterdex.com/api/v1/aster/user-sola "hash": "0x9a40f0119b670fb6b155744b51981f91c4c4c8a20c333441a63853fe7d055c90" } ``` -- hash is not the transaction hash, just a unique value \ No newline at end of file + +| field | desc | +|------------|--------------------------------------| +| withdrawId | The withdraw request ID, a unique ID | +| hash | The digest of the user's signature | + +## withdraw by fapi\[v3\] \[solana\] \[futures\] + +* Note: Follow the [Pro API-KEY Signature (V3)](#pro-api-key-signature-v3) instructions to generate the required request signature. The example below includes only the parameters specific to this endpoint. + +### request: + +```shell +curl --location --request POST 'https://fapi.asterdex.com/fapi/v3/aster/user-solana-withdraw?chainId=101&asset=USDT&amount=3&fee=0.6&receiver=4wTV1YmiEkRvAtNtsSGPtUrqRYQMe5SKy2uB4Jjaxnjf&userNonce=1773741793787000&userSignature=51pM5A46n5NzHYTtuzB7gh8FFfbkh4Aij1fceCZV2NtkiVvE7DADMnSvXFiUJvauKawdWaCfPhzCTVfXYcf1iteQ' \ + --header 'Content-Type: application/json' +``` + +### params: + +| param | type | required | description | +|---------------|--------|----------|---------------------------------------------------------------------------------------------------------------------------------------| +| amount | string | true | Withdraw amount in token units | +| chainId | int | true | Fixed value: `101` | +| asset | string | true | Currency name, e.g., USDT | +| fee | string | true | Withdraw fee in token units | +| receiver | string | true | Withdraw receipt address | +| userNonce | string | false | Nanosecond timestamp for the Solana withdraw signature; separate from V3 API `nonce`. Not currently required but strongly recommended | +| userSignature | string | false | Ed25519 withdraw signature encoded in Base58. Not currently required but strongly recommended | + +### response: + +```json +{ + "withdrawId": "1234567", + "hash": "0x9a40f0119b670fb6b155744b51981f91c4c4c8a20c333441a63853fe7d055c90" +} +``` + +> Note: `hash` is not the transaction hash; it is just a unique identifier. + +## withdraw by fapi\[v3\] \[evm\] \[spot\] + +* Note: Follow the [Pro API-KEY Signature (V3)](#pro-api-key-signature-v3) instructions to generate the required request signature. The example below includes only the parameters specific to this endpoint. + +### request: + +```shell +curl --location --request POST 'https://sapi.asterdex.com/api/v3/aster/user-withdraw?chainId=56&asset=USDT&amount=31&fee=0.3&receiver=0x000ae314e2a2172a039b26378814c252734f556a&userNonce=1761210000000000&userSignature=0xde4ca529eef20db136eed1daf1d072083431d5279e6d6e219600cf57161c5e6d1232af3c8a8ef37ba8b5963f439ef9cc2b475fe18dcc3732dda9fb93c94a3abd1c' \ + --header 'Content-Type: application/json' +``` + +### params: + +| param | type | required | description | +|---------------|--------|----------|--------------------------------------------------------------------------------------------------------------------| +| amount | string | true | Withdraw amount in token units | +| chainId | int | true | Chain ID | +| asset | string | true | Currency name, e.g., ASTER | +| fee | string | true | Withdraw fee in token units | +| userNonce | string | true | Nanosecond timestamp for the EVM withdraw signature; separate from V3 API `nonce`, may differ by up to 1 hour | +| receiver | string | true | Withdraw receipt address; should be the same as in signature | +| userSignature | string | true | EIP712 withdraw signature | + +### response: + +```json +{ + "withdrawId": "1234567", + "hash": "0x9a40f0119b670fb6b155744b51981f91c4c4c8a20c333441a63853fe7d055c90" +} +``` + +| field | desc | +|------------|--------------------------------------| +| withdrawId | The withdraw request ID, a unique ID | +| hash | The digest of the user's signature | + +## withdraw by fapi\[v3\] \[solana\] \[spot\] + +* Note: Follow the [Pro API-KEY Signature (V3)](#pro-api-key-signature-v3) instructions to generate the required request signature. The example below includes only the parameters specific to this endpoint. + +### request: + +```shell +curl --location --request POST 'https://sapi.asterdex.com/api/v3/aster/user-solana-withdraw?chainId=101&asset=USDT&amount=0.97&fee=0.5&receiver=BzsJhmtg2UtQWNw6764DkK5Y4GPjc1XMzRqAGqSziymK&userNonce=1773741793787000&userSignature=51pM5A46n5NzHYTtuzB7gh8FFfbkh4Aij1fceCZV2NtkiVvE7DADMnSvXFiUJvauKawdWaCfPhzCTVfXYcf1iteQ' \ + --header 'Content-Type: application/json' +``` + +### params: + +| param | type | required | description | +|---------------|--------|----------|---------------------------------------------------------------------------------------------------------------------------------------| +| amount | string | true | Withdraw amount in token units | +| chainId | int | true | Fixed value: `101` | +| asset | string | true | Currency name, e.g., USDT | +| fee | string | true | Withdraw fee in token units | +| receiver | string | true | Withdraw receipt address | +| userNonce | string | false | Nanosecond timestamp for the Solana withdraw signature; separate from V3 API `nonce`. Not currently required but strongly recommended | +| userSignature | string | false | Ed25519 withdraw signature encoded in Base58. Not currently required but strongly recommended | + +### response: + +```json +{ + "withdrawId": "1234567", + "hash": "0x9a40f0119b670fb6b155744b51981f91c4c4c8a20c333441a63853fe7d055c90" +} +``` + +> Note: `hash` is not the transaction hash; it is just a unique identifier. \ No newline at end of file From d10d7c271a7cb34e94302d3d43c5e49534011c76 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Wed, 18 Mar 2026 11:11:11 +0700 Subject: [PATCH 062/131] remove HMAC SHA256 from all v3 API docs Co-Authored-By: Claude Sonnet 4.6 --- aster-finance-futures-api-v3.md | 48 +++++++++---------- aster-finance-futures-api-v3_CN.md | 75 ++++++++++-------------------- aster-finance-spot-api-v3.md | 6 +-- aster-finance-spot-api_CN-v3.md | 36 +++++--------- 4 files changed, 63 insertions(+), 102 deletions(-) diff --git a/aster-finance-futures-api-v3.md b/aster-finance-futures-api-v3.md index 3b43463..4046b12 100644 --- a/aster-finance-futures-api-v3.md +++ b/aster-finance-futures-api-v3.md @@ -2155,7 +2155,7 @@ Considering the possible data latency from RESTful endpoints during an extremely } ``` -``POST /fapi/v3/positionSide/dual (HMAC SHA256)`` +``POST /fapi/v3/positionSide/dual`` Change user's position mode (Hedge Mode or One-way Mode ) on ***EVERY symbol*** @@ -2178,7 +2178,7 @@ Change user's position mode (Hedge Mode or One-way Mode ) on ***EVERY symbol*** } ``` -``GET /fapi/v3/positionSide/dual (HMAC SHA256)`` +``GET /fapi/v3/positionSide/dual`` Get user's position mode (Hedge Mode or One-way Mode ) on ***EVERY symbol*** @@ -2201,7 +2201,7 @@ Get user's position mode (Hedge Mode or One-way Mode ) on ***EVERY symbol*** } ``` -``POST /fapi/v3/multiAssetsMargin (HMAC SHA256)`` +``POST /fapi/v3/multiAssetsMargin`` Change user's Multi-Assets mode (Multi-Assets Mode or Single-Asset Mode) on ***Every symbol*** @@ -2224,7 +2224,7 @@ Change user's Multi-Assets mode (Multi-Assets Mode or Single-Asset Mode) on ***E } ``` -``GET /fapi/v3/multiAssetsMargin (HMAC SHA256)`` +``GET /fapi/v3/multiAssetsMargin`` Get user's Multi-Assets mode (Multi-Assets Mode or Single-Asset Mode) on ***Every symbol*** @@ -2268,7 +2268,7 @@ Get user's Multi-Assets mode (Multi-Assets Mode or Single-Asset Mode) on ***Ever } ``` -``POST /fapi/v3/order (HMAC SHA256)`` +``POST /fapi/v3/order `` Send in a new order. @@ -2379,7 +2379,7 @@ Additional mandatory parameters based on `type`: ] ``` -``POST /fapi/v3/batchOrders (HMAC SHA256)`` +``POST /fapi/v3/batchOrders `` **Weight:** 5 @@ -2481,7 +2481,7 @@ Notes: } ``` -``GET /fapi/v3/order (HMAC SHA256)`` +``GET /fapi/v3/order`` Check an order's status. @@ -2536,7 +2536,7 @@ Notes: } ``` -``DELETE /fapi/v3/order (HMAC SHA256)`` +``DELETE /fapi/v3/order `` Cancel an active order. @@ -2564,7 +2564,7 @@ Either `orderId` or `origClientOrderId` must be sent. } ``` -``DELETE /fapi/v3/allOpenOrders (HMAC SHA256)`` +``DELETE /fapi/v3/allOpenOrders `` **Weight:** 1 @@ -2612,7 +2612,7 @@ Either `orderId` or `origClientOrderId` must be sent. ] ``` -``DELETE /fapi/v3/batchOrders (HMAC SHA256)`` +``DELETE /fapi/v3/batchOrders `` **Weight:** 1 @@ -2640,7 +2640,7 @@ Either `orderIdList` or `origClientOrderIdList ` must be sent. Cancel all open orders of the specified symbol at the end of the specified countdown. -``POST /fapi/v3/countdownCancelAll (HMAC SHA256)`` +``POST /fapi/v3/countdownCancelAll `` **Weight:** 10 @@ -2691,7 +2691,7 @@ Cancel all open orders of the specified symbol at the end of the specified count } ``` -``GET /fapi/v3/openOrder (HMAC SHA256)`` +``GET /fapi/v3/openOrder `` **Weight:** 1 @@ -2740,7 +2740,7 @@ Cancel all open orders of the specified symbol at the end of the specified count ] ``` -``GET /fapi/v3/openOrders (HMAC SHA256)`` +``GET /fapi/v3/openOrders `` Get all open orders on a symbol. **Careful** when accessing this with no symbol. @@ -2789,7 +2789,7 @@ Get all open orders on a symbol. **Careful** when accessing this with no symbol. ] ``` -``GET /fapi/v3/allOrders (HMAC SHA256)`` +``GET /fapi/v3/allOrders`` Get all account orders; active, canceled, or filled. @@ -2836,7 +2836,7 @@ Get all account orders; active, canceled, or filled. ] ``` -``GET /fapi/v3/balance (HMAC SHA256)`` +``GET /fapi/v3/balance`` **Weight:** 5 @@ -2924,7 +2924,7 @@ Get all account orders; active, canceled, or filled. } ``` -``GET /fapi/v3/account (HMAC SHA256)`` +``GET /fapi/v3/account`` Get current account information. @@ -2948,7 +2948,7 @@ Get current account information. } ``` -``POST /fapi/v3/leverage (HMAC SHA256)`` +``POST /fapi/v3/leverage`` Change user's initial leverage of specific symbol market. @@ -2973,7 +2973,7 @@ Change user's initial leverage of specific symbol market. } ``` -``POST /fapi/v3/marginType (HMAC SHA256)`` +``POST /fapi/v3/marginType`` **Weight:** 1 @@ -2998,7 +2998,7 @@ Change user's initial leverage of specific symbol market. } ``` -``POST /fapi/v3/positionMargin (HMAC SHA256)`` +``POST /fapi/v3/positionMargin`` **Weight:** 1 @@ -3039,7 +3039,7 @@ Change user's initial leverage of specific symbol market. ] ``` -``GET /fapi/v3/positionMargin/history (HMAC SHA256)`` +``GET /fapi/v3/positionMargin/history`` **Weight:** 1 @@ -3117,7 +3117,7 @@ Change user's initial leverage of specific symbol market. ] ``` -``GET /fapi/v3/positionRisk (HMAC SHA256)`` +``GET /fapi/v3/positionRisk`` Get current position information. @@ -3158,7 +3158,7 @@ Please use with user data stream `ACCOUNT_UPDATE` to meet your timeliness and ac ] ``` -``GET /fapi/v3/userTrades (HMAC SHA256)`` +``GET /fapi/v3/userTrades `` Get trades for a specific account and symbol. @@ -3208,7 +3208,7 @@ Get trades for a specific account and symbol. ] ``` -``GET /fapi/v3/income (HMAC SHA256)`` +``GET /fapi/v3/income`` **Weight:** 30 @@ -3407,7 +3407,7 @@ Get trades for a specific account and symbol. } ``` -``GET /fapi/v3/commissionRate (HMAC SHA256)`` +``GET /fapi/v3/commissionRate`` **Weight:** 20 diff --git a/aster-finance-futures-api-v3_CN.md b/aster-finance-futures-api-v3_CN.md index 0a74d6b..e5a1368 100644 --- a/aster-finance-futures-api-v3_CN.md +++ b/aster-finance-futures-api-v3_CN.md @@ -2188,8 +2188,7 @@ orderbook的变化部分,推送间隔250毫秒,500毫秒,100毫秒(如有刷 ``` `` -POST /fapi/v3/positionSide/dual (HMAC SHA256) -`` +POST /fapi/v3/positionSide/dual`` 变换用户在 ***所有symbol*** 合约上的持仓模式:双向持仓或单向持仓。 @@ -2215,8 +2214,7 @@ dualSidePosition | STRING | YES | "true": 双向持仓模式;"false": ``` `` -GET /fapi/v3/positionSide/dual (HMAC SHA256) -`` +GET /fapi/v3/positionSide/dual`` 查询用户目前在 ***所有symbol*** 合约上的持仓模式:双向持仓或单向持仓。 @@ -2235,8 +2233,7 @@ GET /fapi/v3/positionSide/dual (HMAC SHA256) ``` `` -POST /fapi/v3/multiAssetsMargin (HMAC SHA256) -`` +POST /fapi/v3/multiAssetsMargin`` 变换用户在 ***所有symbol*** 合约上的联合保证金模式:开启或关闭联合保证金模式。 @@ -2262,8 +2259,7 @@ multiAssetsMargin | STRING | YES | "true": 联合保证金模式开启; ``` `` -GET /fapi/v3/multiAssetsMargin (HMAC SHA256) -`` +GET /fapi/v3/multiAssetsMargin`` 查询用户目前在 ***所有symbol*** 合约上的联合保证金模式。 @@ -2310,8 +2306,7 @@ GET /fapi/v3/multiAssetsMargin (HMAC SHA256) ``` `` -POST /fapi/v3/order (HMAC SHA256) -`` +POST /fapi/v3/order `` **权重:** 1 @@ -2394,8 +2389,7 @@ Type | 强制要求的参数 `` -POST /fapi/v3/order/test (HMAC SHA256) -`` +POST /fapi/v3/order/test`` 用于测试订单请求,但不会提交到撮合引擎 @@ -2448,8 +2442,7 @@ POST /fapi/v3/order/test (HMAC SHA256) ``` `` -POST /fapi/v3/batchOrders (HMAC SHA256) -`` +POST /fapi/v3/batchOrders `` **权重:** 5 @@ -2553,8 +2546,7 @@ kindType | STRING | YES | 交易类型 ``` `` -GET /fapi/v3/order (HMAC SHA256) -`` +GET /fapi/v3/order`` 查询订单状态 @@ -2611,8 +2603,7 @@ origClientOrderId | STRING | NO | 用户自定义的订单号 ``` `` -DELETE /fapi/v3/order (HMAC SHA256) -`` +DELETE /fapi/v3/order `` **权重:** 1 @@ -2640,8 +2631,7 @@ origClientOrderId | STRING | NO | 用户自定义的订单号 ``` `` -DELETE /fapi/v3/allOpenOrders (HMAC SHA256) -`` +DELETE /fapi/v3/allOpenOrders `` **权重:** 1 @@ -2691,8 +2681,7 @@ symbol | STRING | YES | 交易对 ``` `` -DELETE /fapi/v3/batchOrders (HMAC SHA256) -`` +DELETE /fapi/v3/batchOrders `` **权重:** 1 @@ -2721,8 +2710,7 @@ origClientOrderIdList | LIST\ | NO | 用户自定义的订单号, `` -POST /fapi/v3/countdownCancelAll (HMAC SHA256) -`` +POST /fapi/v3/countdownCancelAll `` **权重:** 10 @@ -2782,8 +2770,7 @@ countdownTime | LONG | YES | 倒计时。 1000 表示 1 秒; 0 表示取消倒 ``` `` -GET /fapi/v3/openOrder (HMAC SHA256) -`` +GET /fapi/v3/openOrder `` 请小心使用不带symbol参数的调用 @@ -2837,8 +2824,7 @@ origClientOrderId | STRING | NO | 用户自定义的订单号 ``` `` -GET /fapi/v3/openOrders (HMAC SHA256) -`` +GET /fapi/v3/openOrders `` 请小心使用不带symbol参数的调用 @@ -2892,8 +2878,7 @@ symbol | STRING | NO | 交易对 ``` `` -GET /fapi/v3/allOrders (HMAC SHA256) -`` +GET /fapi/v3/allOrders`` * 请注意,如果订单满足如下条件,不会被查询到: * 订单的最终状态为 `CANCELED` 或者 `EXPIRED`, **并且** @@ -2939,8 +2924,7 @@ limit | INT | NO | 返回的结果集数量 默认值:500 最大 ``` `` -GET /fapi/v3/balance (HMAC SHA256) -`` +GET /fapi/v3/balance`` **Weight:** 5 @@ -3033,8 +3017,7 @@ GET /fapi/v3/balance (HMAC SHA256) `` -GET /fapi/v3/account (HMAC SHA256) -`` +GET /fapi/v3/account`` **权重:** 5 @@ -3060,8 +3043,7 @@ GET /fapi/v3/account (HMAC SHA256) ``` `` -POST /fapi/v3/leverage (HMAC SHA256) -`` +POST /fapi/v3/leverage`` 调整用户在指定symbol合约的开仓杠杆。 @@ -3088,8 +3070,7 @@ leverage | INT | YES | 目标杠杆倍数:1 到 125 整数 ``` `` -POST /fapi/v3/marginType (HMAC SHA256) -`` +POST /fapi/v3/marginType`` 变换用户在指定symbol合约上的保证金模式:逐仓或全仓。 @@ -3118,8 +3099,7 @@ marginType | ENUM | YES | 保证金模式 ISOLATED(逐仓), CROSSED(全 ``` `` -POST /fapi/v3/positionMargin (HMAC SHA256) -`` +POST /fapi/v3/positionMargin`` 针对逐仓模式下的仓位,调整其逐仓保证金资金。 @@ -3164,8 +3144,7 @@ type | INT | YES | 调整方向 1: 增加逐仓保证金,2: 减 ``` `` -GET /fapi/v3/positionMargin/history (HMAC SHA256) -`` +GET /fapi/v3/positionMargin/history`` @@ -3249,8 +3228,7 @@ limit | INT | NO | 返回的结果集数量 默认值: 500 ``` `` -GET /fapi/v3/positionRisk (HMAC SHA256) -`` +GET /fapi/v3/positionRisk`` **权重:** 5 @@ -3295,8 +3273,7 @@ symbol | STRING | NO | ``` `` -GET /fapi/v3/userTrades (HMAC SHA256) -`` +GET /fapi/v3/userTrades `` 获取某交易对的成交历史 @@ -3347,8 +3324,7 @@ limit | INT | NO | 返回的结果集数量 默认值:500 最大 ``` `` -GET /fapi/v3/income (HMAC SHA256) -`` +GET /fapi/v3/income`` **权重:** 30 @@ -3568,8 +3544,7 @@ limit | INT | NO | Default 50; max 100. ``` `` -GET /fapi/v3/commissionRate (HMAC SHA256) -`` +GET /fapi/v3/commissionRate`` **权重:** 20 diff --git a/aster-finance-spot-api-v3.md b/aster-finance-spot-api-v3.md index a5440a9..52b80dc 100644 --- a/aster-finance-spot-api-v3.md +++ b/aster-finance-spot-api-v3.md @@ -1189,8 +1189,7 @@ Retrieve all current open orders for trading pairs. Use calls without a trading ``` `` -DEL /api/v3/allOpenOrders (HMAC SHA256) -`` +DEL /api/v3/allOpenOrders `` **Weight:** - ***1*** @@ -1318,8 +1317,7 @@ asset | STRING | YES | ``` `` -POST /api/v3/aster/user-withdraw (HMAC SHA256) -`` +POST /api/v3/aster/user-withdraw`` **Weight:** 1 diff --git a/aster-finance-spot-api_CN-v3.md b/aster-finance-spot-api_CN-v3.md index b17bf1d..4767066 100644 --- a/aster-finance-spot-api_CN-v3.md +++ b/aster-finance-spot-api_CN-v3.md @@ -1037,8 +1037,7 @@ symbol | STRING | YES | ``` `` -POST /api/v3/order (HMAC SHA256) -`` +POST /api/v3/order `` 发送下单。 @@ -1105,8 +1104,7 @@ stopPrice | DECIMAL | NO | 仅 `STOP`, `STOP_MARKET` , `TAKE_PROFIT`,`TAKE_PROFI ``` `` -DELETE /api/v3/order (HMAC SHA256) -`` +DELETE /api/v3/order `` 取消有效订单。 @@ -1148,8 +1146,7 @@ origClientOrderId | STRING | NO | ``` `` -GET /api/v3/order (HMAC SHA256) -`` +GET /api/v3/order`` 查询订单状态。 @@ -1199,8 +1196,7 @@ origClientOrderId | STRING | NO | ``` `` -GET /api/v3/openOrder (HMAC SHA256) -`` +GET /api/v3/openOrder`` 查询订单状态。 @@ -1248,8 +1244,7 @@ origClientOrderId | STRING | NO | ``` `` -GET /api/v3/openOrders (HMAC SHA256) -`` +GET /api/v3/openOrders `` 获取交易对的所有当前挂单, 请小心使用不带交易对参数的调用。 @@ -1279,8 +1274,7 @@ symbol | STRING | NO | ``` `` -DEL /api/v3/allOpenOrders (HMAC SHA256) -`` +DEL /api/v3/allOpenOrders `` **权重:** - ***1*** @@ -1320,8 +1314,7 @@ origClientOrderIdList | STRING | NO | clientOrderId数组字符串 ``` `` -GET /api/v3/allOrders (HMAC SHA256) -`` +GET /api/v3/allOrders`` 获取所有帐户订单; 有效,已取消或已完成。 @@ -1347,8 +1340,7 @@ limit | INT | NO | 默认 500; 最大 1000. `` -GET /api/v3/transactionHistory (HMAC SHA256) -`` +GET /api/v3/transactionHistory`` > **响应** ```javascript @@ -1398,8 +1390,7 @@ limit | LONG | NO | 返回的结果集数量 默认值:100 最大值:1000 ``` `` -POST /api/v3/asset/wallet/transfer (HMAC SHA256) -`` +POST /api/v3/asset/wallet/transfer `` **权重:** 5 @@ -1455,8 +1446,7 @@ asset | STRING | YES | ``` `` -POST /api/v3/aster/user-withdraw (HMAC SHA256) -`` +POST /api/v3/aster/user-withdraw`` **权重:** 5 @@ -1615,8 +1605,7 @@ const signature = await signer.signMessage(message); ``` `` -GET /api/v3/account (HMAC SHA256) -`` +GET /api/v3/account`` 获取当前账户信息。 @@ -1653,8 +1642,7 @@ GET /api/v3/account (HMAC SHA256) ``` `` -GET /api/v3/userTrades (HMAC SHA256) -`` +GET /api/v3/userTrades `` 获取账户指定交易对的成交历史 From 77994f3ddce65f3bf482538b37fbee93f7340821 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Thu, 19 Mar 2026 11:31:01 +0700 Subject: [PATCH 063/131] testnetpy --- .claude/settings.local.json | 9 ++ aster-finance-futures-api-testnet.md | 152 ++++++++++++++------------- 2 files changed, 90 insertions(+), 71 deletions(-) create mode 100644 .claude/settings.local.json diff --git a/.claude/settings.local.json b/.claude/settings.local.json new file mode 100644 index 0000000..1552e97 --- /dev/null +++ b/.claude/settings.local.json @@ -0,0 +1,9 @@ +{ + "permissions": { + "allow": [ + "Bash(git add:*)", + "Bash(git commit:*)", + "Bash(git push:*)" + ] + } +} diff --git a/aster-finance-futures-api-testnet.md b/aster-finance-futures-api-testnet.md index 8d9b6c7..c46805b 100644 --- a/aster-finance-futures-api-testnet.md +++ b/aster-finance-futures-api-testnet.md @@ -283,113 +283,123 @@ typed_data = { > **Step 1: As a query string** ```python -import random import time +import urllib import requests -from eth_account.messages import encode_typed_data +from eth_account.messages import encode_structured_data from eth_account import Account -from eip712 import typed_data +typed_data = { + "types": { + "EIP712Domain": [ + {"name": "name", "type": "string"}, + {"name": "version", "type": "string"}, + {"name": "chainId", "type": "uint256"}, + {"name": "verifyingContract", "type": "address"} + ], + "Message": [ + { "name": "msg", "type": "string" } + ] + }, + "primaryType": "Message", + "domain": { + "name": "AsterSignTransaction", + "version": "1", + "chainId": 714, + "verifyingContract": "0x0000000000000000000000000000000000000000" + }, + "message": { + "msg": "$msg" + } +} +headers = { + 'Content-Type': 'application/x-www-form-urlencoded', + 'User-Agent': 'PythonApp/1.0' +} -def get_url(my_dict) -> str: - return '&'.join(f'{key}={str(value)}'for key, value in my_dict.items()) +# config your user and agent info here +user = '*' +signer = '*' +private_key = "*" -def send_by_url() : - import random - import time +host = 'https://fapi.asterdex-testnet.com' - import requests - from eth_account.messages import encode_typed_data - from eth_account import Account +place_order = {"url":"/fapi/v3/order","method":"POST","params":{"symbol": "ASTERUSDT", "type": "LIMIT", "side": "BUY", + "timeInForce": "GTC", "quantity": "20", "price": "0.5"}} +batch_orders = {"url":"/fapi/v3/batchOrders","method":"POST","params":{ + "batchOrders":"[{'symbol':'ASTERUSDT','type':'LIMIT','side':'BUY','timeInForce':'GTC','quantity':'20','price':'0.5'},{'symbol':'ASTERUSDT','type':'LIMIT','side':'BUY','timeInForce':'GTC','quantity':'20','price':'0.5'}]" }} +listenKey = {"url":"/fapi/v3/listenKey","method":"POST","params":{}} - test_net_end_point = 'https://fapi.asterdex-testnet.com/fapi/v3/order' - param = 'symbol=BTCUSDT&side=BUY&type=LIMIT&quantity=1&price=9000&timeInForce=GTC' +_last_ms = 0 +_i = 0 - nonce = int(time.time()) * 1_000_000 + random.randint(0, 999999) - param += '&nonce=' + str(nonce) - param += '&user=' + '0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e' - param += '&signer=' + '0xbEf084ad26b44F002C3b55DB3bf7241003dABdab' +def get_nonce(): + global _last_ms, _i + now_ms = int(time.time()) - typed_data['message']['msg'] = param + if now_ms == _last_ms: + _i += 1 + else: + _last_ms = now_ms + _i = 0 - message = encode_typed_data(full_message=typed_data) + return now_ms * 1_000_000 + _i - private_key = "*" - signed = Account.sign_message(message, private_key=private_key) - print(signed.signature.hex()) +def send_by_url(api) : + my_dict = api['params'] + url = host + api['url'] - url = test_net_end_point + '?' + param + '&signature=' + signed.signature.hex() + my_dict['nonce'] = str(get_nonce()) + my_dict['user'] = user + my_dict['signer'] = signer - headers = { - 'Content-Type': 'application/x-www-form-urlencoded', - 'User-Agent': 'PythonApp/1.0' - } + param = urllib.parse.urlencode(my_dict) + + print(param) + typed_data['message']['msg'] = param + message = encode_structured_data(typed_data) + signed = Account.sign_message(message, private_key=private_key) + + url = url + '?' + param + '&signature=' + signed.signature.hex() print(url) res = requests.post(url, headers=headers) print(res.text) -if __name__ == '__main__': - send_by_url() - - -``` - -> **Step 1: As a body** - -```python -import random -import time - -import requests -from eth_account.messages import encode_typed_data -from eth_account import Account - -from eip712 import typed_data - - -def get_url(my_dict) -> str: - return '&'.join(f'{key}={str(value)}'for key, value in my_dict.items()) - -def send_by_body() : - my_dict = {"symbol": "BTCUSDT", "positionSide": "BOTH", "type": "LIMIT", "side": "BUY", - "timeInForce": "GTC", "quantity": "0.01", "price": "81000"} +def send_by_body(api) : + my_dict = api['params'] + url = host +api['url'] + my_dict['nonce'] = str(get_nonce()) + my_dict['user'] = user + my_dict['signer'] = signer - test_net_end_point = 'https://fapi.asterdex-testnet.com/fapi/v3/order' + param = urllib.parse.urlencode(my_dict) + typed_data['message']['msg'] = param + message = encode_structured_data(typed_data) - nonce = int(time.time()) * 1_000_000 + random.randint(0, 999999) - my_dict['nonce'] = str(nonce) - my_dict['user'] = '0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e' - my_dict['signer'] = '0xbEf084ad26b44F002C3b55DB3bf7241003dABdab' - - content = get_url(my_dict) - - typed_data['message']['msg'] = content - - message = encode_typed_data(full_message=typed_data) - - private_key = "*" signed = Account.sign_message(message, private_key=private_key) print(signed.signature.hex()) my_dict['signature'] = signed.signature.hex() - headers = { - 'Content-Type': 'application/x-www-form-urlencoded', - 'User-Agent': 'PythonApp/1.0' - } print(my_dict) - res = requests.post(test_net_end_point, data=my_dict, headers=headers) + res = requests.post(url, data=my_dict, headers=headers) print(res.text) if __name__ == '__main__': - send_by_body() + send_by_url(place_order) + # send_by_url(batch_orders) + # send_by_body(place_order) + # send_by_body(batch_orders) + # send_by_body(listenKey) + ``` + ## Public Endpoints Info ### Terminology From 78162a6d058c33119687ec6d6957293d5e71bc53 Mon Sep 17 00:00:00 2001 From: aodyc Date: Thu, 19 Mar 2026 17:22:20 +0700 Subject: [PATCH 064/131] docs: add user-withdraw-info and deposit-withdraw-history API endpoints Add documentation for two new authenticated query APIs under Query APIs section: - GET /fapi/aster/user-withdraw-info: returns user withdrawal limits and per-asset/per-chain balance info - GET /fapi/aster/deposit-withdraw-history: returns user deposit and withdrawal history records Both endpoints require API-KEY (V1) signature authentication. --- aster-deposit-withdrawal.md | 108 ++++++++++++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) diff --git a/aster-deposit-withdrawal.md b/aster-deposit-withdrawal.md index bf1dca0..37d1bdd 100644 --- a/aster-deposit-withdrawal.md +++ b/aster-deposit-withdrawal.md @@ -5,6 +5,8 @@ - [get all withdraw assets](#get-all-withdraw-assets) - [estimate withdraw fee](#estimate-withdraw-fee) - [get server time](#get-server-time) + - [get user withdraw info](#get-user-withdraw-info) + - [get deposit and withdraw history](#get-deposit-and-withdraw-history) - [Signature](#signature) - [API-KEY Signature (V1)](#api-key-signature-v1) - [Pro API-KEY Signature (V3)](#pro-api-key-signature-v3) @@ -189,6 +191,112 @@ curl 'https://fapi5.asterdex.com/fapi/v3/time' |------------|---------------------------------------------| | serverTime | Current server time in milliseconds (Unix) | +## get user withdraw info + +* Note: Follow the [API-KEY Signature (V1)](#api-key-signature-v1) instructions to generate the required request signature. + +### request: + +```shell +curl --location 'https://fapi.asterdex.com/fapi/aster/user-withdraw-info?timestamp=1742198400000&recvWindow=5000&signature=' \ + --header 'X-MBX-APIKEY: Your API KEY' +``` + +### params: + +No additional parameters required beyond the standard V1 signature parameters (`timestamp`, `recvWindow`, `signature`). + +### response: + +```json +{ + "userDailyLimit": "10000", + "userRemainingDailyLimit": "9000", + "totalDailyLimit": "1000000", + "totalRemainingDailyLimit": "980000", + "balances": { + "USDT": { + "currency": "USDT", + "spotTotalWithdrawAmount": "500", + "perpTotalWithdrawAmount": "300", + "dailyLimit": "9000", + "chainBalances": { + "56": { + "chainId": 56, + "spotMaxWithdrawAmount": "500", + "perpMaxWithdrawAmount": "300", + "chainLimit": "800", + "withdrawFee": "0.5" + } + } + } + } +} +``` + +| field | desc | +|--------------------------|-------------------------------------------------------------------| +| userDailyLimit | User's daily withdrawal limit, denominated in USD | +| userRemainingDailyLimit | User's remaining daily withdrawal limit, denominated in USD | +| totalDailyLimit | Global daily withdrawal limit, denominated in USD | +| totalRemainingDailyLimit | Global remaining daily withdrawal limit, denominated in USD | +| balances | Map of non-zero asset balances, keyed by asset name | +| balances.currency | Asset name | +| balances.spotTotalWithdrawAmount | Total spot balance available for withdrawal | +| balances.perpTotalWithdrawAmount | Total futures balance available for withdrawal | +| balances.dailyLimit | Remaining daily withdrawal limit for this asset, denominated in USD | +| balances.chainBalances | Per-chain balance info, keyed by chain ID | +| balances.chainBalances.chainId | Chain ID | +| balances.chainBalances.spotMaxWithdrawAmount | Max withdrawable spot amount on this chain | +| balances.chainBalances.perpMaxWithdrawAmount | Max withdrawable futures amount on this chain | +| balances.chainBalances.chainLimit | Max withdrawable amount on this chain | +| balances.chainBalances.withdrawFee | Withdrawal fee on this chain | + +## get deposit and withdraw history + +* Note: Follow the [API-KEY Signature (V1)](#api-key-signature-v1) instructions to generate the required request signature. + +### request: + +```shell +curl --location 'https://fapi.asterdex.com/fapi/aster/deposit-withdraw-history?timestamp=1742198400000&recvWindow=5000&signature=' \ + --header 'X-MBX-APIKEY: Your API KEY' +``` + +### params: + +No additional parameters required beyond the standard V1 signature parameters (`timestamp`, `recvWindow`, `signature`). + +### response: + +```json +[ + { + "id": "1234567", + "type": "DEPOSIT", + "asset": "USDT", + "amount": "100", + "state": "SUCCESS", + "txHash": "0x9a40f0119b670fb6b155744b51981f91c4c4c8a20c333441a63853fe7d055c90", + "time": 1742198400000, + "chainId": 56, + "accountType": "spot" + } +] +``` + +| field | desc | +|-------------|----------------------------------------------------------------------| +| id | Record ID | +| type | Record type: `DEPOSIT` or `WITHDRAW` | +| asset | Asset name, e.g., USDT | +| amount | Amount | +| state | Status: `PROCESSING`, `SUCCESS`, or `FAILED` | +| txHash | On-chain transaction hash | +| time | Record time in milliseconds (Unix) | +| chainId | Chain ID | +| accountType | Account type: `spot` or `perp` | + --- # Signature From 6b94cf48f228b3de77d5a5763d85ed3f930c54c5 Mon Sep 17 00:00:00 2001 From: aodyc Date: Thu, 19 Mar 2026 20:47:24 +0700 Subject: [PATCH 065/131] fix: update user-withdraw-info and deposit-withdraw-history to POST --- aster-deposit-withdrawal.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/aster-deposit-withdrawal.md b/aster-deposit-withdrawal.md index 37d1bdd..2211540 100644 --- a/aster-deposit-withdrawal.md +++ b/aster-deposit-withdrawal.md @@ -198,7 +198,7 @@ curl 'https://fapi5.asterdex.com/fapi/v3/time' ### request: ```shell -curl --location 'https://fapi.asterdex.com/fapi/aster/user-withdraw-info?timestamp=1742198400000&recvWindow=5000&signature=' \ +curl --location --request POST 'https://fapi.asterdex.com/fapi/aster/user-withdraw-info?timestamp=1742198400000&recvWindow=5000&signature=' \ --header 'X-MBX-APIKEY: Your API KEY' ``` @@ -259,7 +259,7 @@ No additional parameters required beyond the standard V1 signature parameters (` ### request: ```shell -curl --location 'https://fapi.asterdex.com/fapi/aster/deposit-withdraw-history?timestamp=1742198400000&recvWindow=5000&signature=' \ +curl --location --request POST 'https://fapi.asterdex.com/fapi/aster/deposit-withdraw-history?timestamp=1742198400000&recvWindow=5000&signature=' \ --header 'X-MBX-APIKEY: Your API KEY' ``` From f27bd0d1f39e0d3a948e6a18b8fb10440526594f Mon Sep 17 00:00:00 2001 From: Vanessa Date: Sat, 21 Mar 2026 15:31:03 +0800 Subject: [PATCH 066/131] add index weight references --- aster-finance-futures-api-v3.md | 87 ++++++++++++++++++++++++++++++ aster-finance-futures-api-v3_CN.md | 86 +++++++++++++++++++++++++++++ 2 files changed, 173 insertions(+) diff --git a/aster-finance-futures-api-v3.md b/aster-finance-futures-api-v3.md index 4046b12..a9a5a82 100644 --- a/aster-finance-futures-api-v3.md +++ b/aster-finance-futures-api-v3.md @@ -41,6 +41,7 @@ - [24hr Ticker Price Change Statistics](#24hr-ticker-price-change-statistics) - [Symbol Price Ticker](#symbol-price-ticker) - [Symbol Order Book Ticker](#symbol-order-book-ticker) + - [Index Price References](#index-price-references) - [Websocket Market Streams](#websocket-market-streams) - [Live Subscribing/Unsubscribing to streams](#live-subscribingunsubscribing-to-streams) - [Subscribe to a stream](#subscribe-to-a-stream) @@ -1508,6 +1509,92 @@ Best price/qty on the order book for a symbol or symbols. * If the symbol is not sent, bookTickers for all symbols will be returned in an array. + +## Index Price References + +> **Response:** + +```javascript +{ + "symbol": "BTCUSDT", // Trading pair + "time": 1774077572319, // Data timestamp + "references": [ + { + "exchange": "binance", // Source exchange + "symbol": "BTCUSDT", // Symbol on source exchange + "weight": "0.41441441" // Weight + }, + { + "exchange": "okex", + "symbol": "BTC-USDT", + "weight": "0.13513513" + }, + { + "exchange": "coinbase", + "symbol": "BTC-USDT", + "weight": "0.13513513" + }, + { + "exchange": "gateio", + "symbol": "BTC_USDT", + "weight": "0.04504504" + }, + { + "exchange": "kucoin", + "symbol": "BTC-USDT", + "weight": "0.06756756" + }, + { + "exchange": "mxc", + "symbol": "BTCUSDT", + "weight": "0.06756756" + }, + { + "exchange": "bybit", + "symbol": "BTCUSDT", + "weight": "0.06756756" + }, + { + "exchange": "bitget", + "symbol": "BTCUSDT", + "weight": "0.06756756" + } + ] +} +``` + +> **Error response (missing symbol):** + +```javascript +{ + "code": -1102, + "msg": "Mandatory parameter 'symbol' was not sent, was empty/null, or malformed." +} +``` + +> **Error response (invalid symbol):** + +```javascript +{ + "code": -1000, + "msg": "Invalid symbol." +} +``` + +``GET /fapi/v3/indexreferences`` + +Get the component exchanges and their weights for the index price of a symbol. + +**Weight:** +1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ------ | ------ | --------- | ------------ | +| symbol | STRING | YES | Trading pair | + + # Websocket Market Streams * The baseurl for websocket is **wss://fstream.asterdex.com** diff --git a/aster-finance-futures-api-v3_CN.md b/aster-finance-futures-api-v3_CN.md index e5a1368..eb0b96d 100644 --- a/aster-finance-futures-api-v3_CN.md +++ b/aster-finance-futures-api-v3_CN.md @@ -40,6 +40,7 @@ - [24hr价格变动情况](#24hr价格变动情况) - [最新价格](#最新价格) - [当前最优挂单](#当前最优挂单) + - [获取指数价格成分](#获取指数价格成分) - [Websocket 行情推送](#websocket-行情推送) - [实时订阅/取消数据流](#实时订阅取消数据流) - [订阅一个信息流](#订阅一个信息流) @@ -1515,6 +1516,91 @@ symbol | STRING | NO | 交易对 * 不发送交易对参数,则会返回所有交易对信息 +## 获取指数价格成分 + +> **响应:** + +```javascript +{ + "symbol": "BTCUSDT", // 交易对 + "time": 1774077572319, // 数据时间 + "references": [ + { + "exchange": "binance", // 来源交易所 + "symbol": "BTCUSDT", // 来源交易所交易对 + "weight": "0.41441441" // 权重 + }, + { + "exchange": "okex", + "symbol": "BTC-USDT", + "weight": "0.13513513" + }, + { + "exchange": "coinbase", + "symbol": "BTC-USDT", + "weight": "0.13513513" + }, + { + "exchange": "gateio", + "symbol": "BTC_USDT", + "weight": "0.04504504" + }, + { + "exchange": "kucoin", + "symbol": "BTC-USDT", + "weight": "0.06756756" + }, + { + "exchange": "mxc", + "symbol": "BTCUSDT", + "weight": "0.06756756" + }, + { + "exchange": "bybit", + "symbol": "BTCUSDT", + "weight": "0.06756756" + }, + { + "exchange": "bitget", + "symbol": "BTCUSDT", + "weight": "0.06756756" + } + ] +} +``` + +> **错误响应(未传 symbol):** + +```javascript +{ + "code": -1102, + "msg": "Mandatory parameter 'symbol' was not sent, was empty/null, or malformed." +} +``` + +> **错误响应(无效交易对):** + +```javascript +{ + "code": -1000, + "msg": "Invalid symbol." +} +``` + +`` +GET /fapi/v3/indexreferences +`` + +查询指数价格的成分交易所及各交易所的权重 + +**权重:** +1 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +------ | ------ | -------- | ------ +symbol | STRING | YES | 交易对 # Websocket 行情推送 From 6501038c5c417c82c684b633f301d387b39e1aaa Mon Sep 17 00:00:00 2001 From: Vanessa Date: Sat, 21 Mar 2026 15:36:11 +0800 Subject: [PATCH 067/131] modify index weight references --- aster-finance-futures-api-v3.md | 9 --------- aster-finance-futures-api-v3_CN.md | 9 --------- 2 files changed, 18 deletions(-) diff --git a/aster-finance-futures-api-v3.md b/aster-finance-futures-api-v3.md index a9a5a82..e5b83da 100644 --- a/aster-finance-futures-api-v3.md +++ b/aster-finance-futures-api-v3.md @@ -1563,15 +1563,6 @@ Best price/qty on the order book for a symbol or symbols. } ``` -> **Error response (missing symbol):** - -```javascript -{ - "code": -1102, - "msg": "Mandatory parameter 'symbol' was not sent, was empty/null, or malformed." -} -``` - > **Error response (invalid symbol):** ```javascript diff --git a/aster-finance-futures-api-v3_CN.md b/aster-finance-futures-api-v3_CN.md index eb0b96d..bbb74d5 100644 --- a/aster-finance-futures-api-v3_CN.md +++ b/aster-finance-futures-api-v3_CN.md @@ -1569,15 +1569,6 @@ symbol | STRING | NO | 交易对 } ``` -> **错误响应(未传 symbol):** - -```javascript -{ - "code": -1102, - "msg": "Mandatory parameter 'symbol' was not sent, was empty/null, or malformed." -} -``` - > **错误响应(无效交易对):** ```javascript From f2f0b11bade377d3a35f693520c94b38d2d35b45 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Tue, 24 Mar 2026 17:48:45 +0700 Subject: [PATCH 068/131] remove_abi --- aster-finance-futures-api-testnet.md | 4 ---- aster-finance-futures-api-v3.md | 4 ---- aster-finance-spot-api-testnet.md | 4 ---- aster-finance-spot-api-v3.md | 5 +---- 4 files changed, 1 insertion(+), 16 deletions(-) diff --git a/aster-finance-futures-api-testnet.md b/aster-finance-futures-api-testnet.md index c46805b..bd444f9 100644 --- a/aster-finance-futures-api-testnet.md +++ b/aster-finance-futures-api-testnet.md @@ -218,10 +218,6 @@ It is recommended to use a small recvWindow of 5000 or less! ## Endpoints requiring signature * Security Type: TRADE, USER_DATA, USER_STREAM, MARKET_DATA -* After converting the API parameters to strings, sort them by their key values in ASCII order to generate the final string. Note: All parameter values must be treated as strings during the signing process. -* After generating the string, combine it with the authentication signature parameters user, signer, and nonce, then use Web3’s ABI parameter encoding to generate the bytecode. -* After generating the bytecode, use the Keccak algorithm to generate the hash. -* Use the private key of **API wallet address** to sign the hash using web3’s ECDSA signature algorithm, generating the final signature. ## Example of POST /fapi/v3/order diff --git a/aster-finance-futures-api-v3.md b/aster-finance-futures-api-v3.md index e5b83da..702872e 100644 --- a/aster-finance-futures-api-v3.md +++ b/aster-finance-futures-api-v3.md @@ -217,10 +217,6 @@ It is strongly recommended to use websocket stream for getting data as much as p ## Endpoints requiring signature * Security Type: TRADE, USER_DATA, USER_STREAM -* After generating the string, combine it with the authentication signature parameters user, signer, and nonce, then use Web3’s ABI parameter encoding to generate the bytecode. -* After generating the bytecode, use the Keccak algorithm to generate the hash. -* Use the private key of **API wallet address** to sign the hash using web3’s ECDSA signature algorithm, generating the final signature. - ## Example of POST /fapi/v3/order diff --git a/aster-finance-spot-api-testnet.md b/aster-finance-spot-api-testnet.md index 7d740c8..562bf1b 100644 --- a/aster-finance-spot-api-testnet.md +++ b/aster-finance-spot-api-testnet.md @@ -101,10 +101,6 @@ You are advised to use WebSocket messages to obtain the corresponding data as mu ## Endpoints requiring signature * Security Type: TRADE, USER_DATA, USER_STREAM, MARKET_DATA -* After converting the API parameters to strings, sort them by their key values in ASCII order to generate the final string. Note: All parameter values must be treated as strings during the signing process. -* After generating the string, combine it with the authentication signature parameters user, signer, and nonce, then use Web3’s ABI parameter encoding to generate the bytecode. -* After generating the bytecode, use the Keccak algorithm to generate the hash. -* Use the private key of **API wallet address** to sign the hash using web3’s ECDSA signature algorithm, generating the final signature. ## Example of POST /api/v3/order diff --git a/aster-finance-spot-api-v3.md b/aster-finance-spot-api-v3.md index 52b80dc..cf759b9 100644 --- a/aster-finance-spot-api-v3.md +++ b/aster-finance-spot-api-v3.md @@ -106,10 +106,7 @@ You are advised to use WebSocket messages to obtain the corresponding data as mu --- ## SIGNED (TRADE AND USER\_DATA) Endpoint security - -* After generating the string, combine it with the authentication signature parameters user, signer, and nonce, then use Web3’s ABI parameter encoding to generate the bytecode. -* After generating the bytecode, use the Keccak algorithm to generate the hash. -* Use the private key of **API wallet address** to sign the hash using web3’s ECDSA signature algorithm, generating the final signature. +* Security Type: SPOT_TRADE, USER_DATA, USER_STREAM ## Example of POST /api/v3/order From cc008080e69dcc740f409e9c91dae87c6f041ee4 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Wed, 25 Mar 2026 09:54:06 +0700 Subject: [PATCH 069/131] testnet py script --- aster-finance-futures-api-testnet.md | 49 ++------- aster-finance-spot-api-testnet.md | 155 +++++++++++---------------- 2 files changed, 72 insertions(+), 132 deletions(-) diff --git a/aster-finance-futures-api-testnet.md b/aster-finance-futures-api-testnet.md index bd444f9..8017243 100644 --- a/aster-finance-futures-api-testnet.md +++ b/aster-finance-futures-api-testnet.md @@ -205,7 +205,7 @@ It is recommended to use a small recvWindow of 5000 or less! | TRADE | A valid signer and signature are required | | USER_DATA | A valid signer and signature are required | | USER_STREAM | A valid signer and signature are required | -| MARKET_DATA | A valid signer and signature are required | +| MARKET_DATA | API that does not require authentication | ## Authentication signature payload @@ -217,7 +217,7 @@ It is recommended to use a small recvWindow of 5000 or less! | signature | Signature | ## Endpoints requiring signature -* Security Type: TRADE, USER_DATA, USER_STREAM, MARKET_DATA +* Security Type: TRADE, USER_DATA, USER_STREAM ## Example of POST /fapi/v3/order @@ -248,37 +248,7 @@ long microsecond = now.getEpochSecond() * 1000000 + now.getNano() / 1000; #### Example: The following parameters are business request parameters. ```python - -typed_data = { - "types": { - "EIP712Domain": [ - {"name": "name", "type": "string"}, - {"name": "version", "type": "string"}, - {"name": "chainId", "type": "uint256"}, - {"name": "verifyingContract", "type": "address"} - ], - "Message": [ - { "name": "msg", "type": "string" } - ] - }, - "primaryType": "Message", - "domain": { - "name": "AsterSignTransaction", - "version": "1", - "chainId": 714, - "verifyingContract": "0x0000000000000000000000000000000000000000" - }, - "message": { - "msg": "$msg" - } -} -``` - -#### Example: As a query string (using Python as an example). - -> **Step 1: As a query string** - -```python +import json import time import urllib @@ -314,20 +284,18 @@ headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'PythonApp/1.0' } +host = 'https://fapi.asterdex-testnet.com' # config your user and agent info here user = '*' signer = '*' -private_key = "*" - -host = 'https://fapi.asterdex-testnet.com' +private_key = '*' place_order = {"url":"/fapi/v3/order","method":"POST","params":{"symbol": "ASTERUSDT", "type": "LIMIT", "side": "BUY", "timeInForce": "GTC", "quantity": "20", "price": "0.5"}} batch_orders = {"url":"/fapi/v3/batchOrders","method":"POST","params":{ "batchOrders":"[{'symbol':'ASTERUSDT','type':'LIMIT','side':'BUY','timeInForce':'GTC','quantity':'20','price':'0.5'},{'symbol':'ASTERUSDT','type':'LIMIT','side':'BUY','timeInForce':'GTC','quantity':'20','price':'0.5'}]" }} -listenKey = {"url":"/fapi/v3/listenKey","method":"POST","params":{}} - +listen_key = {"url":"/fapi/v3/listenKey","method":"POST","params":{}} _last_ms = 0 _i = 0 @@ -361,7 +329,6 @@ def send_by_url(api) : url = url + '?' + param + '&signature=' + signed.signature.hex() print(url) res = requests.post(url, headers=headers) - print(res.text) def send_by_body(api) : @@ -382,15 +349,15 @@ def send_by_body(api) : print(my_dict) res = requests.post(url, data=my_dict, headers=headers) - + # print(res.headers) print(res.text) if __name__ == '__main__': send_by_url(place_order) + # send_by_url(listen_key) # send_by_url(batch_orders) # send_by_body(place_order) # send_by_body(batch_orders) - # send_by_body(listenKey) ``` diff --git a/aster-finance-spot-api-testnet.md b/aster-finance-spot-api-testnet.md index 562bf1b..91e191e 100644 --- a/aster-finance-spot-api-testnet.md +++ b/aster-finance-spot-api-testnet.md @@ -83,7 +83,7 @@ You are advised to use WebSocket messages to obtain the corresponding data as mu | TRADE | A valid signer and signature are required | | USER_DATA | A valid signer and signature are required | | USER_STREAM | A valid signer and signature are required | -| MARKET_DATA | A valid signer and signature are required | +| MARKET_DATA | API that does not require authentication | --- @@ -100,7 +100,7 @@ You are advised to use WebSocket messages to obtain the corresponding data as mu | signature | Signature | ## Endpoints requiring signature -* Security Type: TRADE, USER_DATA, USER_STREAM, MARKET_DATA +* Security Type: SPOT_TRADE, USER_DATA, USER_STREAM ## Example of POST /api/v3/order @@ -131,6 +131,12 @@ long microsecond = now.getEpochSecond() * 1000000 + now.getNano() / 1000; #### Example: The following parameters are business request parameters. ```python +import time +import urllib + +import requests +from eth_account.messages import encode_structured_data +from eth_account import Account typed_data = { "types": { @@ -154,118 +160,85 @@ typed_data = { "message": { "msg": "$msg" } -} -``` +} -#### Example: As a query string (using Python as an example). +headers = { + 'Content-Type': 'application/x-www-form-urlencoded', + 'User-Agent': 'PythonApp/1.0' +} +host = 'https://sapi.asterdex-testnet.com' -> **Step 1: As a query string** +# config your user and agent info here +user = '*' +signer = '*' +private_key = '*' -```python -import random -import time +place_order = {"url":"/api/v3/order","method":"POST","params":{"symbol": "ASTERUSDT", "type": "LIMIT", "side": "BUY", + "timeInForce": "GTC", "quantity": "20", "price": "0.5"}} +batch_orders = {"url":"/api/v3/batchOrders","method":"POST","params":{ + "batchOrders":"[{'symbol':'ASTERUSDT','type':'LIMIT','side':'BUY','timeInForce':'GTC','quantity':'20','price':'0.5'},{'symbol':'ASTERUSDT','type':'LIMIT','side':'BUY','timeInForce':'GTC','quantity':'20','price':'0.5'}]" }} +listen_key = {"url":"/api/v3/listenKey","method":"POST","params":{}} +_last_ms = 0 +_i = 0 -import requests -from eth_account.messages import encode_typed_data -from eth_account import Account +def get_nonce(): + global _last_ms, _i + now_ms = int(time.time()) -from eip712 import typed_data + if now_ms == _last_ms: + _i += 1 + else: + _last_ms = now_ms + _i = 0 + return now_ms * 1_000_000 + _i -def get_url(my_dict) -> str: - return '&'.join(f'{key}={str(value)}'for key, value in my_dict.items()) +def send_by_url(api) : + my_dict = api['params'] + url = host + api['url'] -def send_by_body() : - my_dict = {"symbol": "ASTERUSDT", "type": "LIMIT", "side": "BUY", - "timeInForce": "GTC", "quantity": "10", "price": "0.6"} + my_dict['nonce'] = str(get_nonce()) + my_dict['user'] = user + my_dict['signer'] = signer - test_net_end_point = 'https://sapi.asterdex-testnet.com/api/v3/order' + param = urllib.parse.urlencode(my_dict) - nonce = int(time.time()) * 1_000_000 + random.randint(0, 999999) - my_dict['nonce'] = str(nonce) - my_dict['user'] = '0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e' - my_dict['signer'] = '0xF1A3E9330a348Df202D29E5a065089f6EbA01b26' + print(param) + typed_data['message']['msg'] = param + message = encode_structured_data(typed_data) + signed = Account.sign_message(message, private_key=private_key) - content = get_url(my_dict) + url = url + '?' + param + '&signature=' + signed.signature.hex() + print(url) + res = requests.post(url, headers=headers) + print(res.text) - typed_data['message']['msg'] = content +def send_by_body(api) : + my_dict = api['params'] + url = host +api['url'] + my_dict['nonce'] = str(get_nonce()) + my_dict['user'] = user + my_dict['signer'] = signer - message = encode_typed_data(full_message=typed_data) + param = urllib.parse.urlencode(my_dict) + typed_data['message']['msg'] = param + message = encode_structured_data(typed_data) - private_key = "*" signed = Account.sign_message(message, private_key=private_key) print(signed.signature.hex()) my_dict['signature'] = signed.signature.hex() - headers = { - 'Content-Type': 'application/x-www-form-urlencoded', - 'User-Agent': 'PythonApp/1.0' - } print(my_dict) - res = requests.post(test_net_end_point, data=my_dict, headers=headers) - + res = requests.post(url, data=my_dict, headers=headers) print(res.text) if __name__ == '__main__': - send_by_body() - - -``` - -> **Step 1: As a body** - -```python -import random -import time - -import requests -from eth_account.messages import encode_typed_data -from eth_account import Account - -from eip712 import typed_data - - -def get_url(my_dict) -> str: - return '&'.join(f'{key}={str(value)}'for key, value in my_dict.items()) - -def send_by_url() : - import random - import time - - import requests - from eth_account.messages import encode_typed_data - from eth_account import Account - - test_net_end_point = 'https://sapi.asterdex-testnet.com/api/v3/order' - param = 'symbol=ASTERUSDT&side=BUY&type=LIMIT&quantity=10&price=0.6&timeInForce=GTC' - - nonce = int(time.time()) * 1_000_000 + random.randint(0, 999999) - param += '&nonce=' + str(nonce) - param += '&user=' + '0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e' - param += '&signer=' + '0xF1A3E9330a348Df202D29E5a065089f6EbA01b26' - - typed_data['message']['msg'] = param - - message = encode_typed_data(full_message=typed_data) - - private_key = "*" - signed = Account.sign_message(message, private_key=private_key) - print(signed.signature.hex()) - - url = test_net_end_point + '?' + param + '&signature=' + signed.signature.hex() - - headers = { - 'Content-Type': 'application/x-www-form-urlencoded', - 'User-Agent': 'PythonApp/1.0' - } - print(url) - res = requests.post(url, headers=headers) - - print(res.text) - -if __name__ == '__main__': - send_by_url() + send_by_url(place_order) + # send_by_url(listen_key) + # send_by_url(batch_orders) + # send_by_body(place_order) + # send_by_body(batch_orders) ``` From 61a040aaf2f925a87f209da903a863bb939342a8 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Wed, 25 Mar 2026 19:32:56 +0700 Subject: [PATCH 070/131] batchdeletedemo --- aster-finance-futures-api-v3.md | 3 +++ aster-finance-futures-api-v3_CN.md | 3 +++ 2 files changed, 6 insertions(+) diff --git a/aster-finance-futures-api-v3.md b/aster-finance-futures-api-v3.md index 702872e..847e2e9 100644 --- a/aster-finance-futures-api-v3.md +++ b/aster-finance-futures-api-v3.md @@ -294,6 +294,8 @@ place_order = {"url":"/fapi/v3/order","method":"POST","params":{"symbol": "ASTER "timeInForce": "GTC", "quantity": "20", "price": "0.5"}} batch_orders = {"url":"/fapi/v3/batchOrders","method":"POST","params":{ "batchOrders":"[{'symbol':'ASTERUSDT','type':'LIMIT','side':'BUY','timeInForce':'GTC','quantity':'20','price':'0.5'},{'symbol':'ASTERUSDT','type':'LIMIT','side':'BUY','timeInForce':'GTC','quantity':'20','price':'0.5'}]" }} +batch_orders_delete = {"url": "/fapi/v3/batchOrders", "method": "DELETE", + "params": {"symbol": "BTCUSDT", "origClientOrderIdList": "[123,111,123]"}} _last_ms = 0 _i = 0 @@ -357,6 +359,7 @@ if __name__ == '__main__': # send_by_url(batch_orders) # send_by_body(place_order) # send_by_body(batch_orders) + #send_by_url(batch_orders_delete) ``` ## Public Endpoints Info diff --git a/aster-finance-futures-api-v3_CN.md b/aster-finance-futures-api-v3_CN.md index bbb74d5..092a889 100644 --- a/aster-finance-futures-api-v3_CN.md +++ b/aster-finance-futures-api-v3_CN.md @@ -280,6 +280,8 @@ place_order = {"url":"/fapi/v3/order","method":"POST","params":{"symbol": "ASTER "timeInForce": "GTC", "quantity": "20", "price": "0.5"}} batch_orders = {"url":"/fapi/v3/batchOrders","method":"POST","params":{ "batchOrders":"[{'symbol':'ASTERUSDT','type':'LIMIT','side':'BUY','timeInForce':'GTC','quantity':'20','price':'0.5'},{'symbol':'ASTERUSDT','type':'LIMIT','side':'BUY','timeInForce':'GTC','quantity':'20','price':'0.5'}]" }} +batch_orders_delete = {"url": "/fapi/v3/batchOrders", "method": "DELETE", + "params": {"symbol": "BTCUSDT", "origClientOrderIdList": "[123,111,123]"}} _last_ms = 0 _i = 0 @@ -343,6 +345,7 @@ if __name__ == '__main__': # send_by_url(batch_orders) # send_by_body(place_order) # send_by_body(batch_orders) + #send_by_url(batch_orders_delete) ``` ## 公开API参数 From dbb6e3b2ce94f8ff812459eae658e6e2138b3cb6 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Wed, 25 Mar 2026 19:43:14 +0700 Subject: [PATCH 071/131] batchdeletedemo --- aster-finance-futures-api-v3.md | 28 ++++++++++++++++++++-------- aster-finance-futures-api-v3_CN.md | 28 ++++++++++++++++++++-------- 2 files changed, 40 insertions(+), 16 deletions(-) diff --git a/aster-finance-futures-api-v3.md b/aster-finance-futures-api-v3.md index 847e2e9..cd2d5c6 100644 --- a/aster-finance-futures-api-v3.md +++ b/aster-finance-futures-api-v3.md @@ -288,12 +288,13 @@ host = 'https://fapi3.asterdex.com' # config your user and agent info here user = '*' signer = '*' -private_key = "*" +private_key = '*' place_order = {"url":"/fapi/v3/order","method":"POST","params":{"symbol": "ASTERUSDT", "type": "LIMIT", "side": "BUY", "timeInForce": "GTC", "quantity": "20", "price": "0.5"}} batch_orders = {"url":"/fapi/v3/batchOrders","method":"POST","params":{ "batchOrders":"[{'symbol':'ASTERUSDT','type':'LIMIT','side':'BUY','timeInForce':'GTC','quantity':'20','price':'0.5'},{'symbol':'ASTERUSDT','type':'LIMIT','side':'BUY','timeInForce':'GTC','quantity':'20','price':'0.5'}]" }} + batch_orders_delete = {"url": "/fapi/v3/batchOrders", "method": "DELETE", "params": {"symbol": "BTCUSDT", "origClientOrderIdList": "[123,111,123]"}} @@ -315,6 +316,7 @@ def get_nonce(): def send_by_url(api) : my_dict = api['params'] url = host + api['url'] + method = api['method'] my_dict['nonce'] = str(get_nonce()) my_dict['user'] = user @@ -329,13 +331,19 @@ def send_by_url(api) : url = url + '?' + param + '&signature=' + signed.signature.hex() print(url) - res = requests.post(url, headers=headers) - print(res.text) + if method == 'DELETE': + res = requests.delete(url, headers=headers) + print(res.text) + if method == 'POST': + res = requests.post(url, headers=headers) + print(res.text) def send_by_body(api) : my_dict = api['params'] url = host +api['url'] + method = api['method'] + my_dict['nonce'] = str(get_nonce()) my_dict['user'] = user my_dict['signer'] = signer @@ -350,16 +358,20 @@ def send_by_body(api) : my_dict['signature'] = signed.signature.hex() print(my_dict) - res = requests.post(url, data=my_dict, headers=headers) - - print(res.text) + if method == 'DELETE': + res = requests.delete(url, data=my_dict, headers=headers) + print(res.text) + if method == 'POST': + res = requests.post(url, data=my_dict, headers=headers) + print(res.text) if __name__ == '__main__': send_by_url(place_order) - # send_by_url(batch_orders) # send_by_body(place_order) # send_by_body(batch_orders) - #send_by_url(batch_orders_delete) + # send_by_url(batch_orders_delete) + # send_by_body(batch_orders_delete) + ``` ## Public Endpoints Info diff --git a/aster-finance-futures-api-v3_CN.md b/aster-finance-futures-api-v3_CN.md index 092a889..eee331b 100644 --- a/aster-finance-futures-api-v3_CN.md +++ b/aster-finance-futures-api-v3_CN.md @@ -274,12 +274,13 @@ host = 'https://fapi3.asterdex.com' # config your user and agent info here user = '*' signer = '*' -private_key = "*" +private_key = '*' place_order = {"url":"/fapi/v3/order","method":"POST","params":{"symbol": "ASTERUSDT", "type": "LIMIT", "side": "BUY", "timeInForce": "GTC", "quantity": "20", "price": "0.5"}} batch_orders = {"url":"/fapi/v3/batchOrders","method":"POST","params":{ "batchOrders":"[{'symbol':'ASTERUSDT','type':'LIMIT','side':'BUY','timeInForce':'GTC','quantity':'20','price':'0.5'},{'symbol':'ASTERUSDT','type':'LIMIT','side':'BUY','timeInForce':'GTC','quantity':'20','price':'0.5'}]" }} + batch_orders_delete = {"url": "/fapi/v3/batchOrders", "method": "DELETE", "params": {"symbol": "BTCUSDT", "origClientOrderIdList": "[123,111,123]"}} @@ -301,6 +302,7 @@ def get_nonce(): def send_by_url(api) : my_dict = api['params'] url = host + api['url'] + method = api['method'] my_dict['nonce'] = str(get_nonce()) my_dict['user'] = user @@ -315,13 +317,19 @@ def send_by_url(api) : url = url + '?' + param + '&signature=' + signed.signature.hex() print(url) - res = requests.post(url, headers=headers) - print(res.text) + if method == 'DELETE': + res = requests.delete(url, headers=headers) + print(res.text) + if method == 'POST': + res = requests.post(url, headers=headers) + print(res.text) def send_by_body(api) : my_dict = api['params'] url = host +api['url'] + method = api['method'] + my_dict['nonce'] = str(get_nonce()) my_dict['user'] = user my_dict['signer'] = signer @@ -336,16 +344,20 @@ def send_by_body(api) : my_dict['signature'] = signed.signature.hex() print(my_dict) - res = requests.post(url, data=my_dict, headers=headers) - - print(res.text) + if method == 'DELETE': + res = requests.delete(url, data=my_dict, headers=headers) + print(res.text) + if method == 'POST': + res = requests.post(url, data=my_dict, headers=headers) + print(res.text) if __name__ == '__main__': send_by_url(place_order) - # send_by_url(batch_orders) # send_by_body(place_order) # send_by_body(batch_orders) - #send_by_url(batch_orders_delete) + # send_by_url(batch_orders_delete) + # send_by_body(batch_orders_delete) + ``` ## 公开API参数 From 5e3c89d4a3f80458c43f3acba880dbabe53b1cb1 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Wed, 25 Mar 2026 21:03:14 +0700 Subject: [PATCH 072/131] batchdeletedemo --- aster-finance-futures-api-v3.md | 2 +- aster-finance-futures-api-v3_CN.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/aster-finance-futures-api-v3.md b/aster-finance-futures-api-v3.md index cd2d5c6..e3f9ab6 100644 --- a/aster-finance-futures-api-v3.md +++ b/aster-finance-futures-api-v3.md @@ -296,7 +296,7 @@ batch_orders = {"url":"/fapi/v3/batchOrders","method":"POST","params":{ "batchOrders":"[{'symbol':'ASTERUSDT','type':'LIMIT','side':'BUY','timeInForce':'GTC','quantity':'20','price':'0.5'},{'symbol':'ASTERUSDT','type':'LIMIT','side':'BUY','timeInForce':'GTC','quantity':'20','price':'0.5'}]" }} batch_orders_delete = {"url": "/fapi/v3/batchOrders", "method": "DELETE", - "params": {"symbol": "BTCUSDT", "origClientOrderIdList": "[123,111,123]"}} + "params": {"symbol": "BTCUSDT", "origClientOrderIdList": '["123aaaa","111ccc","321313"]'}} _last_ms = 0 _i = 0 diff --git a/aster-finance-futures-api-v3_CN.md b/aster-finance-futures-api-v3_CN.md index eee331b..07faa86 100644 --- a/aster-finance-futures-api-v3_CN.md +++ b/aster-finance-futures-api-v3_CN.md @@ -282,7 +282,7 @@ batch_orders = {"url":"/fapi/v3/batchOrders","method":"POST","params":{ "batchOrders":"[{'symbol':'ASTERUSDT','type':'LIMIT','side':'BUY','timeInForce':'GTC','quantity':'20','price':'0.5'},{'symbol':'ASTERUSDT','type':'LIMIT','side':'BUY','timeInForce':'GTC','quantity':'20','price':'0.5'}]" }} batch_orders_delete = {"url": "/fapi/v3/batchOrders", "method": "DELETE", - "params": {"symbol": "BTCUSDT", "origClientOrderIdList": "[123,111,123]"}} + "params": {"symbol": "BTCUSDT", "origClientOrderIdList": '["123aaaa","111ccc","321313"]'}} _last_ms = 0 _i = 0 From 9d392db6d9487b536d0fd18c5da04bbbdfe4c9dd Mon Sep 17 00:00:00 2001 From: Vanessa Date: Thu, 26 Mar 2026 21:13:23 +0800 Subject: [PATCH 073/131] aster chain doc update --- aster-chain-rpc.md | 60 +++++++++++++++++++++++++------------------ aster-chain-rpc_CN.md | 60 +++++++++++++++++++++++++------------------ 2 files changed, 70 insertions(+), 50 deletions(-) diff --git a/aster-chain-rpc.md b/aster-chain-rpc.md index 9600b81..fcea88b 100644 --- a/aster-chain-rpc.md +++ b/aster-chain-rpc.md @@ -15,7 +15,7 @@ * The `blockTag` parameter accepts `"latest"` to query the most recent state. * All time-related fields are in milliseconds. -> **Note:** The following endpoints only return data when the user has **privacy mode disabled**. If privacy mode is enabled, no data will be returned. +> **Note:** In the Open Orders and Fills endpoints, account privacy enabled only applies to new orders placed after it is enabled; orders completed when account privacy is disabled remain visible as usual. --- @@ -236,12 +236,10 @@ Query the trade fill history for a given address within a specified time range. Index | Name | Type | Mandatory | Description ----- | ---- | ---- | --------- | ----------- 0 | address | STRING | YES | The wallet address to query -1 | symbol | STRING | YES | Trading pair symbol (e.g. `"BTCUSDT"`) -2 | from | LONG | YES | Start time in milliseconds -3 | to | LONG | YES | End time in milliseconds -4 | limit | INT | YES | Number of records per page; max `1000` per request -5 | page | INT | YES | Page number, starting from `1` -6 | blockTag | STRING | YES | Block tag, use `"latest"` for the most recent state +1 | symbol | STRING | NO | Trading pair symbol (e.g. `"BTCUSDT"`); pass `null` to query all symbols +2 | from | LONG | NO | Start time in milliseconds. If omitted and `to` is provided, defaults to `to - 7 days`. If both are omitted, defaults to 7 days before current time. Must be ≥ `1772678119418` (block 1 genesis); queries before this timestamp return empty results. +3 | to | LONG | NO | End time in milliseconds. If omitted and `from` is provided, defaults to `from + 7 days`. If both are omitted, defaults to current time. The time range between `from` and `to` must not exceed 7 days. +4 | blockTag | STRING | YES | Block tag, use `"latest"` for the most recent state > **Request Example:** @@ -254,12 +252,10 @@ curl -X POST "https://tapi.asterdex.com/info" \ "jsonrpc": "2.0", "method": "aster_userFills", "params": [ - "0x690931c*********", - "BTCUSDT", - 1772887745000, - 1773146945000, - 2, - 1, + "0x87EC27*********************", + null, + null, + null, "latest" ] }' @@ -270,24 +266,38 @@ curl -X POST "https://tapi.asterdex.com/info" \ ```javascript { "result": { - "address": "0x690931c*********", + "address": "0x87EC27*********************", "accountPrivy": "disabled", - "startTime": 1772887745000, - "endTime": 1783146945000, + "startTime": 1773916057398, + "endTime": 1774520857398, "fills": [ { "symbol": "BTCUSDT", "side": "BUY", - "price": "71087.9", - "qty": "0.00100000", - "time": 1773405618000 + "price": "69999", + "qty": "0.001", + "time": 1774233564000 + }, + { + "symbol": "BTCUSDT", + "side": "SELL", + "price": "70658.6", + "qty": "0.001", + "time": 1774084612000 + }, + { + "symbol": "ETHUSDT", + "side": "BUY", + "price": "1971", + "qty": "0.013", + "time": 1774084518000 }, { "symbol": "BTCUSDT", "side": "BUY", - "price": "71088.1", - "qty": "0.00100000", - "time": 1773401493000 + "price": "70676.7", + "qty": "0.001", + "time": 1774084489000 } ] }, @@ -302,9 +312,9 @@ Name | Type | Description ---- | ---- | ----------- address | STRING | Wallet address accountPrivy | STRING | Privacy mode status: `"disabled"` or `"enabled"` -startTime | LONG | Query start time in milliseconds -endTime | LONG | Query end time in milliseconds -fills | ARRAY | List of trade fills +startTime | LONG | Actual query start time in milliseconds +endTime | LONG | Actual query end time in milliseconds +fills | ARRAY | List of trade fills; returns at most `1000` records fills[].symbol | STRING | Trading pair symbol fills[].side | STRING | Trade side: `BUY` or `SELL` fills[].price | STRING | Fill price diff --git a/aster-chain-rpc_CN.md b/aster-chain-rpc_CN.md index 07b0324..268accf 100644 --- a/aster-chain-rpc_CN.md +++ b/aster-chain-rpc_CN.md @@ -15,7 +15,7 @@ * `blockTag` 参数传入 `"latest"` 表示查询最新状态。 * 所有时间相关字段均为毫秒级时间戳。 -> **注意:** 以下接口仅在用户**关闭隐私模式**时返回数据。如果用户开启了隐私模式,接口将不返回任何数据。 +> **注意:** 在 Open Orders 和 Fills 接口中,隐私模式仅影响开启后的新订单;非隐私模式下完成的历史订单仍按正常规则展示。 --- @@ -236,12 +236,10 @@ POST /info 下标 | 参数名 | 类型 | 是否必填 | 说明 ---- | ------ | ---- | -------- | ---- 0 | address | STRING | 是 | 要查询的钱包地址 -1 | symbol | STRING | 是 | 交易对名称(如 `"BTCUSDT"`) -2 | from | LONG | 是 | 查询起始时间(毫秒时间戳) -3 | to | LONG | 是 | 查询结束时间(毫秒时间戳) -4 | limit | INT | 是 | 每页返回条数,每次最多返回 `1000` 条 -5 | page | INT | 是 | 页码,从 `1` 开始 -6 | blockTag | STRING | 是 | 区块标签,传入 `"latest"` 表示查询最新状态 +1 | symbol | STRING | 否 | 交易对名称(如 `"BTCUSDT"`),传 `null` 则查询所有交易对 +2 | from | LONG | 否 | 查询起始时间(毫秒时间戳)。若不填且填了 `to`,则默认为 `to - 7天`;若两者均不填,则默认为当前时间往前 7 天。最小值为 `1772678119418`(block 1 创世时间),早于此时间的查询默认返回空。 +3 | to | LONG | 否 | 查询结束时间(毫秒时间戳)。若不填且填了 `from`,则默认为 `from + 7天`;若两者均不填,则默认为当前时间。`from` 与 `to` 时间间隔不得超过 7 天。 +4 | blockTag | STRING | 是 | 区块标签,传入 `"latest"` 表示查询最新状态 > **请求示例:** @@ -254,12 +252,10 @@ curl -X POST "https://tapi.asterdex.com/info" \ "jsonrpc": "2.0", "method": "aster_userFills", "params": [ - "0x690931c*********", - "BTCUSDT", - 1772887745000, - 1773146945000, - 2, - 1, + "0x1c3C4*************", + null, + null, + null, "latest" ] }' @@ -270,24 +266,38 @@ curl -X POST "https://tapi.asterdex.com/info" \ ```javascript { "result": { - "address": "0x690931c*********", + "address": "0x1c3C4*************", "accountPrivy": "disabled", - "startTime": 1772887745000, - "endTime": 1783146945000, + "startTime": 1773916057398, + "endTime": 1774520857398, "fills": [ { "symbol": "BTCUSDT", "side": "BUY", - "price": "71087.9", - "qty": "0.00100000", - "time": 1773405618000 + "price": "69999", + "qty": "0.001", + "time": 1774233564000 + }, + { + "symbol": "BTCUSDT", + "side": "SELL", + "price": "70658.6", + "qty": "0.001", + "time": 1774084612000 + }, + { + "symbol": "ETHUSDT", + "side": "BUY", + "price": "1971", + "qty": "0.013", + "time": 1774084518000 }, { "symbol": "BTCUSDT", "side": "BUY", - "price": "71088.1", - "qty": "0.00100000", - "time": 1773401493000 + "price": "70676.7", + "qty": "0.001", + "time": 1774084489000 } ] }, @@ -302,9 +312,9 @@ curl -X POST "https://tapi.asterdex.com/info" \ ------ | ---- | ---- address | STRING | 钱包地址 accountPrivy | STRING | 隐私模式状态:`"disabled"` 已关闭 / `"enabled"` 已开启 -startTime | LONG | 查询起始时间(毫秒时间戳) -endTime | LONG | 查询结束时间(毫秒时间戳) -fills | ARRAY | 成交记录列表 +startTime | LONG | 实际查询起始时间(毫秒时间戳) +endTime | LONG | 实际查询结束时间(毫秒时间戳) +fills | ARRAY | 成交记录列表,最多返回 `1000` 条 fills[].symbol | STRING | 交易对名称 fills[].side | STRING | 成交方向:`BUY` 买入 / `SELL` 卖出 fills[].price | STRING | 成交价格 From a1263494c000e94d9735a27f1b349a556c73454d Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Fri, 27 Mar 2026 17:01:02 +0700 Subject: [PATCH 074/131] sol builder demo --- aster-finance-futures-api-testnet.md | 18 +-- aster-finance-futures-api-v3.md | 17 +-- aster-finance-futures-api-v3_CN.md | 17 +-- aster-finance-spot-api-testnet.md | 17 +-- aster-finance-spot-api-v3.md | 17 +-- aster-finance-spot-api_CN-v3.md | 17 +-- demo/sol_agent.py | 159 +++++++++++++++++++++++++++ 7 files changed, 220 insertions(+), 42 deletions(-) create mode 100644 demo/sol_agent.py diff --git a/aster-finance-futures-api-testnet.md b/aster-finance-futures-api-testnet.md index 8017243..8cd32d3 100644 --- a/aster-finance-futures-api-testnet.md +++ b/aster-finance-futures-api-testnet.md @@ -251,6 +251,7 @@ long microsecond = now.getEpochSecond() * 1000000 + now.getNano() / 1000; import json import time import urllib +import threading import requests from eth_account.messages import encode_structured_data @@ -296,20 +297,23 @@ place_order = {"url":"/fapi/v3/order","method":"POST","params":{"symbol": "ASTER batch_orders = {"url":"/fapi/v3/batchOrders","method":"POST","params":{ "batchOrders":"[{'symbol':'ASTERUSDT','type':'LIMIT','side':'BUY','timeInForce':'GTC','quantity':'20','price':'0.5'},{'symbol':'ASTERUSDT','type':'LIMIT','side':'BUY','timeInForce':'GTC','quantity':'20','price':'0.5'}]" }} listen_key = {"url":"/fapi/v3/listenKey","method":"POST","params":{}} + _last_ms = 0 _i = 0 +_nonce_lock = threading.Lock() def get_nonce(): global _last_ms, _i - now_ms = int(time.time()) + with _nonce_lock: + now_ms = int(time.time()) - if now_ms == _last_ms: - _i += 1 - else: - _last_ms = now_ms - _i = 0 + if now_ms == _last_ms: + _i += 1 + else: + _last_ms = now_ms + _i = 0 - return now_ms * 1_000_000 + _i + return now_ms * 1_000_000 + _i def send_by_url(api) : my_dict = api['params'] diff --git a/aster-finance-futures-api-v3.md b/aster-finance-futures-api-v3.md index e3f9ab6..6e325b7 100644 --- a/aster-finance-futures-api-v3.md +++ b/aster-finance-futures-api-v3.md @@ -250,6 +250,7 @@ long microsecond = now.getEpochSecond() * 1000000 + now.getNano() / 1000; ```python import time import urllib +import threading import requests from eth_account.messages import encode_structured_data @@ -300,18 +301,20 @@ batch_orders_delete = {"url": "/fapi/v3/batchOrders", "method": "DELETE", _last_ms = 0 _i = 0 +_nonce_lock = threading.Lock() def get_nonce(): global _last_ms, _i - now_ms = int(time.time()) + with _nonce_lock: + now_ms = int(time.time()) - if now_ms == _last_ms: - _i += 1 - else: - _last_ms = now_ms - _i = 0 + if now_ms == _last_ms: + _i += 1 + else: + _last_ms = now_ms + _i = 0 - return now_ms * 1_000_000 + _i + return now_ms * 1_000_000 + _i def send_by_url(api) : my_dict = api['params'] diff --git a/aster-finance-futures-api-v3_CN.md b/aster-finance-futures-api-v3_CN.md index 07faa86..2beb3bd 100644 --- a/aster-finance-futures-api-v3_CN.md +++ b/aster-finance-futures-api-v3_CN.md @@ -236,6 +236,7 @@ long microsecond = now.getEpochSecond() * 1000000 + now.getNano() / 1000; ```python import time import urllib +import threading import requests from eth_account.messages import encode_structured_data @@ -286,18 +287,20 @@ batch_orders_delete = {"url": "/fapi/v3/batchOrders", "method": "DELETE", _last_ms = 0 _i = 0 +_nonce_lock = threading.Lock() def get_nonce(): global _last_ms, _i - now_ms = int(time.time()) + with _nonce_lock: + now_ms = int(time.time()) - if now_ms == _last_ms: - _i += 1 - else: - _last_ms = now_ms - _i = 0 + if now_ms == _last_ms: + _i += 1 + else: + _last_ms = now_ms + _i = 0 - return now_ms * 1_000_000 + _i + return now_ms * 1_000_000 + _i def send_by_url(api) : my_dict = api['params'] diff --git a/aster-finance-spot-api-testnet.md b/aster-finance-spot-api-testnet.md index 91e191e..2016728 100644 --- a/aster-finance-spot-api-testnet.md +++ b/aster-finance-spot-api-testnet.md @@ -133,6 +133,7 @@ long microsecond = now.getEpochSecond() * 1000000 + now.getNano() / 1000; ```python import time import urllib +import threading import requests from eth_account.messages import encode_structured_data @@ -180,18 +181,20 @@ batch_orders = {"url":"/api/v3/batchOrders","method":"POST","params":{ listen_key = {"url":"/api/v3/listenKey","method":"POST","params":{}} _last_ms = 0 _i = 0 +_nonce_lock = threading.Lock() def get_nonce(): global _last_ms, _i - now_ms = int(time.time()) + with _nonce_lock: + now_ms = int(time.time()) - if now_ms == _last_ms: - _i += 1 - else: - _last_ms = now_ms - _i = 0 + if now_ms == _last_ms: + _i += 1 + else: + _last_ms = now_ms + _i = 0 - return now_ms * 1_000_000 + _i + return now_ms * 1_000_000 + _i def send_by_url(api) : my_dict = api['params'] diff --git a/aster-finance-spot-api-v3.md b/aster-finance-spot-api-v3.md index cf759b9..12fb676 100644 --- a/aster-finance-spot-api-v3.md +++ b/aster-finance-spot-api-v3.md @@ -140,6 +140,7 @@ long microsecond = now.getEpochSecond() * 1000000 + now.getNano() / 1000; ```python import time import urllib +import threading import requests from eth_account.messages import encode_structured_data @@ -184,18 +185,20 @@ place_order = {"url":"/api/v3/order","method":"POST","params":{"symbol": "ASTERU "timeInForce": "GTC", "quantity": "100", "price": "0.4"}} _last_ms = 0 _i = 0 +_nonce_lock = threading.Lock() def get_nonce(): global _last_ms, _i - now_ms = int(time.time()) + with _nonce_lock: + now_ms = int(time.time()) - if now_ms == _last_ms: - _i += 1 - else: - _last_ms = now_ms - _i = 0 + if now_ms == _last_ms: + _i += 1 + else: + _last_ms = now_ms + _i = 0 - return now_ms * 1_000_000 + _i + return now_ms * 1_000_000 + _i def send_by_url(api) : my_dict = api['params'] diff --git a/aster-finance-spot-api_CN-v3.md b/aster-finance-spot-api_CN-v3.md index 4767066..19ace7a 100644 --- a/aster-finance-spot-api_CN-v3.md +++ b/aster-finance-spot-api_CN-v3.md @@ -128,6 +128,7 @@ long microsecond = now.getEpochSecond() * 1000000 + now.getNano() / 1000; ```python import time import urllib +import threading import requests from eth_account.messages import encode_structured_data @@ -172,18 +173,20 @@ place_order = {"url":"/api/v3/order","method":"POST","params":{"symbol": "ASTERU "timeInForce": "GTC", "quantity": "100", "price": "0.4"}} _last_ms = 0 _i = 0 +_nonce_lock = threading.Lock() def get_nonce(): global _last_ms, _i - now_ms = int(time.time()) + with _nonce_lock: + now_ms = int(time.time()) - if now_ms == _last_ms: - _i += 1 - else: - _last_ms = now_ms - _i = 0 + if now_ms == _last_ms: + _i += 1 + else: + _last_ms = now_ms + _i = 0 - return now_ms * 1_000_000 + _i + return now_ms * 1_000_000 + _i def send_by_url(api) : my_dict = api['params'] diff --git a/demo/sol_agent.py b/demo/sol_agent.py new file mode 100644 index 0000000..201db78 --- /dev/null +++ b/demo/sol_agent.py @@ -0,0 +1,159 @@ +import threading +import urllib + +import base58 +from eth_account import Account +from eth_account.messages import encode_structured_data +from nacl.signing import SigningKey +import time +import requests + +user = '6mSp4BuWCNgRSwv8JopQwCma26hmBT8jrcgJNadq23Gt' +base58_private_key = '*' +signer = '0x71949710270163F096A8Bd342b266183Ae742e5E' +signer_pri_key = '*' + +builder = '0x014c85ffb0fF2F2972237AA950B452f92C69Ae1D' +host = 'https://fapi3.asterdex.com' + +headers = { + 'Content-Type': 'application/x-www-form-urlencoded', + 'User-Agent': 'PythonApp/1.0' +} + +typed_data = { + "types": { + "EIP712Domain": [ + {"name": "name", "type": "string"}, + {"name": "version", "type": "string"}, + {"name": "chainId", "type": "uint256"}, + {"name": "verifyingContract", "type": "address"} + ], + "Message": [ + { "name": "msg", "type": "string" } + ] + }, + "primaryType": "Message", + "domain": { + "name": "AsterSignTransaction", + "version": "1", + "chainId": 1666, + "verifyingContract": "0x0000000000000000000000000000000000000000" + }, + "message": { + "msg": "$msg" + } +} + +approveAgent = {'url': '/fapi/v3/approveAgent', 'method': 'POST', + 'params':{'agentName':'acc' ,'agentAddress':signer, + 'ipWhitelist':'', 'expired':1967945395040,'canSpotTrade':True, + 'canPerpTrade':False, 'canWithdraw':False} + ,'main':True,"primary_type":"ApproveAgent"} + +updateAgent = {'url': '/fapi/v3/updateAgent', 'method': 'POST', + 'params':{'agentAddress':signer,'ipWhitelist':'', + 'canSpotTrade':True, 'canPerpTrade':True, 'canWithdraw':False},'main':True,"primary_type":"UpdateAgent"} + +delAgent = {'url': '/fapi/v3/agent', 'method': 'DELETE', + 'params':{'agentAddress':signer},'main':True,"primary_type":"DelAgent"} + +getAgents = {'url': '/fapi/v3/agent', 'method': 'GET', + 'params':{}} + +approveBuilder = {'url': '/fapi/v3/approveBuilder', 'method': 'POST', + 'params': {'builder': builder, + 'maxFeeRate': '0.00001','builderName':'ivan3' }, 'main': True,"primary_type":"ApproveBuilder"} + +updateBuilder = {'url': '/fapi/v3/updateBuilder', 'method': 'POST', + 'params':{'builder': builder,'maxFeeRate': '0.00002'},'main':True,"primary_type":"UpdateBuilder"} + +delBuilder = {'url': '/fapi/v3/builder', 'method': 'DELETE', + 'params':{'builder':builder},'main':True,"primary_type":"DelBuilder"} +getBuilders = {'url': '/fapi/v3/builder', 'method': 'GET', 'params':{}} + +placeOrder = {'url': '/fapi/v3/order', 'method': 'POST', + 'params':{'symbol': 'BTCUSDT', 'type': 'MARKET','builder':builder,'feeRate':0.00001, 'side': 'BUY','quantity': "0.03"}} + +def sign(message, all_bytes=None) : + # 要签名的数据 + # 创建 signing key + if len(all_bytes) == 64: + all_bytes = all_bytes[:32] + + signing_key = SigningKey(all_bytes) + # 签名 + signed = signing_key.sign(message.encode()) + # signature + signature = signed.signature + + print("message:", message) + print("signature base58:", base58.b58encode(signature).decode()) + print("signature hex:", signature.hex()) + return base58.b58encode(signature).decode() + +_last_ms = 0 +_i = 0 +_nonce_lock = threading.Lock() + +def get_nonce(): + global _last_ms, _i + with _nonce_lock: + now_ms = int(time.time()) + + if now_ms == _last_ms: + _i += 1 + else: + _last_ms = now_ms + _i = 0 + + return now_ms * 1_000_000 + _i + +def send_by_url(api) : + my_dict = api['params'] + url = host + api['url'] + method = api['method'] + main = api.get('main') is not None + + my_dict['nonce'] = str(get_nonce()) + my_dict['user'] = user + print(str(get_nonce())) + + signature = '' + param = '' + if main: + param = urllib.parse.urlencode(my_dict) + print(param) + signature = sign(param,base58.b58decode(base58_private_key)) + else: + my_dict['signer'] = signer + param = urllib.parse.urlencode(my_dict) + print(param) + typed_data['message']['msg'] = param + message = encode_structured_data(typed_data) + signature = Account.sign_message(message, private_key=signer_pri_key).signature.hex() + + url = url + '?' + param + '&signature=' + signature + print(url) + if method == 'POST': + print(signature) + res = requests.post(url, headers=headers) + print(res.text) + if method == 'GET': + print(signature) + res = requests.get(url, headers=headers) + print(res.text) + if method == 'DELETE': + res = requests.delete(url, headers=headers) + print(res.text) + +if __name__ == '__main__': + send_by_url(approveAgent) + # send_by_url(updateAgent) + # send_by_url(delAgent) + # send_by_url(getAgents) + # send_by_url(approveBuilder) + # send_by_url(updateBuilder) + # send_by_url(delBuilder) + # send_by_url(getBuilders) + # send_by_url(placeOrder) From 8f8fcd4107a06ba105158c9b4365874849314fac Mon Sep 17 00:00:00 2001 From: Vanessa Date: Fri, 27 Mar 2026 20:47:53 +0800 Subject: [PATCH 075/131] openorder add notes --- aster-chain-rpc.md | 2 ++ aster-chain-rpc_CN.md | 2 ++ 2 files changed, 4 insertions(+) diff --git a/aster-chain-rpc.md b/aster-chain-rpc.md index fcea88b..a94efdb 100644 --- a/aster-chain-rpc.md +++ b/aster-chain-rpc.md @@ -141,6 +141,8 @@ POST /info Query all open orders for a given address. +> **Note:** Only orders created at or after block 1 genesis time (`1772678119418`) are returned. Maximum **1000** records returned. + **Method:** `aster_openOrders` **Weight:** diff --git a/aster-chain-rpc_CN.md b/aster-chain-rpc_CN.md index 268accf..fe57a2c 100644 --- a/aster-chain-rpc_CN.md +++ b/aster-chain-rpc_CN.md @@ -141,6 +141,8 @@ POST /info 查询指定地址的所有当前挂单。 +> **说明:** 仅返回创建时间不早于 block 1 创世时间(`1772678119418`)的订单,最多返回 **1000** 条。 + **方法名:** `aster_openOrders` **权重:** From 5625f68df9403d736e3a9a5b98e510def56a4e11 Mon Sep 17 00:00:00 2001 From: Vanessa Date: Fri, 27 Mar 2026 21:02:45 +0800 Subject: [PATCH 076/131] openorder note fix --- aster-chain-rpc.md | 2 +- aster-chain-rpc_CN.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/aster-chain-rpc.md b/aster-chain-rpc.md index a94efdb..1bb73de 100644 --- a/aster-chain-rpc.md +++ b/aster-chain-rpc.md @@ -141,7 +141,7 @@ POST /info Query all open orders for a given address. -> **Note:** Only orders created at or after block 1 genesis time (`1772678119418`) are returned. Maximum **1000** records returned. +> **Note:** Only open orders created at or after block 1 genesis time (`1772678119418`) are returned. Maximum **1000** records returned. **Method:** `aster_openOrders` diff --git a/aster-chain-rpc_CN.md b/aster-chain-rpc_CN.md index fe57a2c..0e10c23 100644 --- a/aster-chain-rpc_CN.md +++ b/aster-chain-rpc_CN.md @@ -141,7 +141,7 @@ POST /info 查询指定地址的所有当前挂单。 -> **说明:** 仅返回创建时间不早于 block 1 创世时间(`1772678119418`)的订单,最多返回 **1000** 条。 +> **说明:** 仅返回创建时间不早于 block 1 创世时间(`1772678119418`)的挂单,最多返回 **1000** 条。 **方法名:** `aster_openOrders` From 8c50121fe7531ff69294e8ef30f23d1ae1be509a Mon Sep 17 00:00:00 2001 From: Vanessa Date: Sat, 28 Mar 2026 11:40:52 +0800 Subject: [PATCH 077/131] modify description for symbol --- aster-chain-rpc.md | 4 ++-- aster-chain-rpc_CN.md | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/aster-chain-rpc.md b/aster-chain-rpc.md index 1bb73de..7e45a5c 100644 --- a/aster-chain-rpc.md +++ b/aster-chain-rpc.md @@ -153,7 +153,7 @@ Query all open orders for a given address. Index | Name | Type | Mandatory | Description ----- | ---- | ---- | --------- | ----------- 0 | address | STRING | YES | The wallet address to query -1 | symbol | STRING | NO | Trading pair symbol (e.g. `"BTCUSDT"`); pass `""` to query all symbols +1 | symbol | STRING | NO | Trading pair symbol (e.g. `"BTCUSDT"`); pass `null` or `""` to query all symbols 2 | blockTag | STRING | YES | Block tag, use `"latest"` for the most recent state > **Request Example:** @@ -238,7 +238,7 @@ Query the trade fill history for a given address within a specified time range. Index | Name | Type | Mandatory | Description ----- | ---- | ---- | --------- | ----------- 0 | address | STRING | YES | The wallet address to query -1 | symbol | STRING | NO | Trading pair symbol (e.g. `"BTCUSDT"`); pass `null` to query all symbols +1 | symbol | STRING | NO | Trading pair symbol (e.g. `"BTCUSDT"`); pass `null` or `""` to query all symbols 2 | from | LONG | NO | Start time in milliseconds. If omitted and `to` is provided, defaults to `to - 7 days`. If both are omitted, defaults to 7 days before current time. Must be ≥ `1772678119418` (block 1 genesis); queries before this timestamp return empty results. 3 | to | LONG | NO | End time in milliseconds. If omitted and `from` is provided, defaults to `from + 7 days`. If both are omitted, defaults to current time. The time range between `from` and `to` must not exceed 7 days. 4 | blockTag | STRING | YES | Block tag, use `"latest"` for the most recent state diff --git a/aster-chain-rpc_CN.md b/aster-chain-rpc_CN.md index 0e10c23..909f4ef 100644 --- a/aster-chain-rpc_CN.md +++ b/aster-chain-rpc_CN.md @@ -153,7 +153,7 @@ POST /info 下标 | 参数名 | 类型 | 是否必填 | 说明 ---- | ------ | ---- | -------- | ---- 0 | address | STRING | 是 | 要查询的钱包地址 -1 | symbol | STRING | 否 | 交易对名称(如 `"BTCUSDT"`);传入 `""` 查询所有交易对 +1 | symbol | STRING | 否 | 交易对名称(如 `"BTCUSDT"`);传 `null` 或 `""` 查询所有交易对 2 | blockTag | STRING | 是 | 区块标签,传入 `"latest"` 表示查询最新状态 > **请求示例:** @@ -238,7 +238,7 @@ POST /info 下标 | 参数名 | 类型 | 是否必填 | 说明 ---- | ------ | ---- | -------- | ---- 0 | address | STRING | 是 | 要查询的钱包地址 -1 | symbol | STRING | 否 | 交易对名称(如 `"BTCUSDT"`),传 `null` 则查询所有交易对 +1 | symbol | STRING | 否 | 交易对名称(如 `"BTCUSDT"`);传 `null` 或 `""` 查询所有交易对 2 | from | LONG | 否 | 查询起始时间(毫秒时间戳)。若不填且填了 `to`,则默认为 `to - 7天`;若两者均不填,则默认为当前时间往前 7 天。最小值为 `1772678119418`(block 1 创世时间),早于此时间的查询默认返回空。 3 | to | LONG | 否 | 查询结束时间(毫秒时间戳)。若不填且填了 `from`,则默认为 `from + 7天`;若两者均不填,则默认为当前时间。`from` 与 `to` 时间间隔不得超过 7 天。 4 | blockTag | STRING | 是 | 区块标签,传入 `"latest"` 表示查询最新状态 From 0287f63a3b61baf263a84d8ea6709d2004a81d7f Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Sat, 28 Mar 2026 14:09:19 +0700 Subject: [PATCH 078/131] removeapikey --- aster-finance-futures-api-testnet.md | 2 +- aster-finance-futures-api-v3.md | 2 +- aster-finance-futures-api-v3_CN.md | 2 +- aster-finance-spot-api-testnet.md | 72 -------------------------- aster-finance-spot-api-v3.md | 70 -------------------------- aster-finance-spot-api.md | 72 -------------------------- aster-finance-spot-api_CN-v3.md | 73 --------------------------- aster-finance-spot-api_CN.md | 75 ---------------------------- 8 files changed, 3 insertions(+), 365 deletions(-) diff --git a/aster-finance-futures-api-testnet.md b/aster-finance-futures-api-testnet.md index 8cd32d3..0b24e21 100644 --- a/aster-finance-futures-api-testnet.md +++ b/aster-finance-futures-api-testnet.md @@ -2819,7 +2819,7 @@ Get all account orders; active, canceled, or filled. } ``` -``GET /fapi/v3/account (HMAC SHA256)`` +``GET /fapi/v3/accountWithJoinMargin (HMAC SHA256)`` Get current account information. diff --git a/aster-finance-futures-api-v3.md b/aster-finance-futures-api-v3.md index 6e325b7..7c3d1e8 100644 --- a/aster-finance-futures-api-v3.md +++ b/aster-finance-futures-api-v3.md @@ -3016,7 +3016,7 @@ Get all account orders; active, canceled, or filled. } ``` -``GET /fapi/v3/account`` +``GET /fapi/v3/accountWithJoinMargin`` Get current account information. diff --git a/aster-finance-futures-api-v3_CN.md b/aster-finance-futures-api-v3_CN.md index 2beb3bd..7b9191e 100644 --- a/aster-finance-futures-api-v3_CN.md +++ b/aster-finance-futures-api-v3_CN.md @@ -3112,7 +3112,7 @@ GET /fapi/v3/balance`` `` -GET /fapi/v3/account`` +GET /fapi/v3/accountWithJoinMargin`` **权重:** 5 diff --git a/aster-finance-spot-api-testnet.md b/aster-finance-spot-api-testnet.md index 2016728..6c4eb0f 100644 --- a/aster-finance-spot-api-testnet.md +++ b/aster-finance-spot-api-testnet.md @@ -1404,78 +1404,6 @@ const types = { const signature = await signer.signTypedData(domain, types, value) ``` -## Get User Create Apikey nonce (NONE) - -> **Response:** -```javascript - -111111 - -``` - -`` -POST /api/v3/getNonce -`` - -**Weight:** -1 - -**Parameters:** - -Name | Type | Mandatory | Description ------------- | ------------ | ------------ | ------------ -address | STRING | YES | -userOperationType | STRING | YES | CREATE_API_KEY -network | STRING | NO | - -**Notes:** -* userOperationType: CREATE_API_KEY -* network: For the Solana network, SOL must be provided; otherwise, this field can be ignored. - -## Create Apikey (NONE) - -> **Response:** -```javascript -{ - "apiKey": "bb3b24d0a3dec88cb06be58a257e4575cb0b1bb256ad6fd90ae8fd0ee1d102ae", - "apiSecret": "9fe8f5642ae1961674ea0cb7f957fa99dc8e0421b607c985a963ad2ced90ae1c" -} -``` - -`` -POST /api/v3/createApiKey -`` - -**Weight:** -1 - -**Parameters:** - -Name | Type | Mandatory | Description ------------- | ------------ | ------------ | ------------ -address | STRING | YES | -userOperationType | STRING | YES | CREATE_API_KEY -network | STRING | NO | -userSignature | STRING | YES | -apikeyIP | STRING | NO | -desc | STRING | YES | -recvWindow | LONG | NO | -timestamp | LONG | YES | - -**Note:** -* userOperationType: CREATE_API_KEY -* network: For the Solana network, SOL must be provided; otherwise, this field can be ignored. -* desc: The same account cannot be duplicated, and the length must not exceed 20 characters. -* apikeyIP: An array of IP addresses, separated by commas. -* Rate limit: 60 requests per minute per IP. -* userSignature: EVM demo - -```shell -const nonce = 111111 -const message = 'You are signing into Astherus ${nonce}'; -const signature = await signer.signMessage(message); -``` - ## Account information (USER\_DATA) **Response** diff --git a/aster-finance-spot-api-v3.md b/aster-finance-spot-api-v3.md index 12fb676..5c8fc6d 100644 --- a/aster-finance-spot-api-v3.md +++ b/aster-finance-spot-api-v3.md @@ -1378,76 +1378,6 @@ const types = { const signature = await signer.signTypedData(domain, types, value) ``` -## Get User Create Apikey nonce (NONE) - -> **Response:** -```javascript - -111111 - -``` - -`` -POST /api/v3/getNonce -`` - -**Weight:** -1 - -**Parameters:** - -Name | Type | Mandatory | Description ------------- | ------------ | ------------ | ------------ -address | STRING | YES | -userOperationType | STRING | YES | CREATE_API_KEY -network | STRING | NO | - -**Notes:** -* userOperationType: CREATE_API_KEY -* network: For the Solana network, SOL must be provided; otherwise, this field can be ignored. - -## Create Apikey (NONE) - -> **Response:** -```javascript -{ - "apiKey": "bb3b24d0a3dec88cb06be58a257e4575cb0b1bb256ad6fd90ae8fd0ee1d102ae", - "apiSecret": "9fe8f5642ae1961674ea0cb7f957fa99dc8e0421b607c985a963ad2ced90ae1c" -} -``` - -`` -POST /api/v3/createApiKey -`` - -**Weight:** -1 - -**Parameters:** - -Name | Type | Mandatory | Description ------------- | ------------ | ------------ | ------------ -address | STRING | YES | -userOperationType | STRING | YES | CREATE_API_KEY -network | STRING | NO | -userSignature | STRING | YES | -apikeyIP | STRING | NO | -desc | STRING | YES | - -**Note:** -* userOperationType: CREATE_API_KEY -* network: For the Solana network, SOL must be provided; otherwise, this field can be ignored. -* desc: The same account cannot be duplicated, and the length must not exceed 20 characters. -* apikeyIP: An array of IP addresses, separated by commas. -* Rate limit: 60 requests per minute per IP. -* userSignature: EVM demo - -```shell -const nonce = 111111 -const message = 'You are signing into Astherus ${nonce}'; -const signature = await signer.signMessage(message); -``` - ## Account information (USER\_DATA) **Response** diff --git a/aster-finance-spot-api.md b/aster-finance-spot-api.md index b3df69c..97f9db6 100644 --- a/aster-finance-spot-api.md +++ b/aster-finance-spot-api.md @@ -1320,78 +1320,6 @@ const types = { const signature = await signer.signTypedData(domain, types, value) ``` -## Get User Create Apikey nonce (NONE) - -> **Response:** -```javascript - -111111 - -``` - -`` -POST /api/v1/getNonce -`` - -**Weight:** -1 - -**Parameters:** - -Name | Type | Mandatory | Description ------------- | ------------ | ------------ | ------------ -address | STRING | YES | -userOperationType | STRING | YES | CREATE_API_KEY -network | STRING | NO | - -**Notes:** -* userOperationType: CREATE_API_KEY -* network: For the Solana network, SOL must be provided; otherwise, this field can be ignored. - -## Create Apikey (NONE) - -> **Response:** -```javascript -{ - "apiKey": "bb3b24d0a3dec88cb06be58a257e4575cb0b1bb256ad6fd90ae8fd0ee1d102ae", - "apiSecret": "9fe8f5642ae1961674ea0cb7f957fa99dc8e0421b607c985a963ad2ced90ae1c" -} -``` - -`` -POST /api/v1/createApiKey -`` - -**Weight:** -1 - -**Parameters:** - -Name | Type | Mandatory | Description ------------- | ------------ | ------------ | ------------ -address | STRING | YES | -userOperationType | STRING | YES | CREATE_API_KEY -network | STRING | NO | -userSignature | STRING | YES | -apikeyIP | STRING | NO | -desc | STRING | YES | -recvWindow | LONG | NO | -timestamp | LONG | YES | - -**Note:** -* userOperationType: CREATE_API_KEY -* network: For the Solana network, SOL must be provided; otherwise, this field can be ignored. -* desc: The same account cannot be duplicated, and the length must not exceed 20 characters. -* apikeyIP: An array of IP addresses, separated by commas. -* Rate limit: 60 requests per minute per IP. -* userSignature: EVM demo - -```shell -const nonce = 111111 -const message = 'You are signing into Astherus ${nonce}'; -const signature = await signer.signMessage(message); -``` - ## Account information (USER\_DATA) **Response** diff --git a/aster-finance-spot-api_CN-v3.md b/aster-finance-spot-api_CN-v3.md index 19ace7a..958a25c 100644 --- a/aster-finance-spot-api_CN-v3.md +++ b/aster-finance-spot-api_CN-v3.md @@ -1509,79 +1509,6 @@ const types = { const signature = await signer.signTypedData(domain, types, value) ``` -## 获取创建apikey nonce (NONE) -> **响应** -```javascript - -111111 - -``` - -`` -POST /api/v3/getNonce -`` - -**权重:** -1 - -**参数:** - -名称 | 类型 | 是否必需 | 描述 ------------- | ------------ | ------------ | ------------ -address | STRING | YES | -userOperationType | STRING | YES | CREATE_API_KEY -network | STRING | NO | - -注意: -* userOperationType 仅可取值: CREATE_API_KEY -* network: sol网络必须传入SOL,其他忽略 -* 限流单IP一分钟60次 - - -## 创建apikey (NONE) -> **响应** -```javascript -{ - "apiKey": "bb3b24d0a3dec88cb06be58a257e4575cb0b1bb256ad6fd90ae8fd0ee1d102ae", - "apiSecret": "9fe8f5642ae1961674ea0cb7f957fa99dc8e0421b607c985a963ad2ced90ae1c" -} -``` - -`` -POST /api/v3/createApiKey -`` - -**权重:** -1 - -**参数:** - -名称 | 类型 | 是否必需 | 描述 ------------- | ------------ | ------------ | ------------ -address | STRING | YES | -userOperationType | STRING | YES | CREATE_API_KEY -network | STRING | NO | -userSignature | STRING | YES | -apikeyIP | STRING | NO | -desc | STRING | YES | - -注意: -* userOperationType 仅可取值: CREATE_API_KEY -* network: sol网络必须传入SOL,其他忽略 -* desc: 同一账户不能重复,长度不能超过20个字符 -* apikeyIP ip数组以,分隔 -* 限流单IP一分钟60次 -* userSignature evm demo - -```shell - -const nonce = 111111 -const message = 'You are signing into Astherus ${nonce}' ; - -const signature = await signer.signMessage(message); -``` - - ## 账户信息 (USER_DATA) > **响应** ```javascript diff --git a/aster-finance-spot-api_CN.md b/aster-finance-spot-api_CN.md index 299326c..5a4419f 100644 --- a/aster-finance-spot-api_CN.md +++ b/aster-finance-spot-api_CN.md @@ -1486,81 +1486,6 @@ const types = { const signature = await signer.signTypedData(domain, types, value) ``` -## 获取创建apikey nonce (NONE) -> **响应** -```javascript - -111111 - -``` - -`` -POST /api/v1/getNonce -`` - -**权重:** -1 - -**参数:** - -名称 | 类型 | 是否必需 | 描述 ------------- | ------------ | ------------ | ------------ -address | STRING | YES | -userOperationType | STRING | YES | CREATE_API_KEY -network | STRING | NO | - -注意: -* userOperationType 仅可取值: CREATE_API_KEY -* network: sol网络必须传入SOL,其他忽略 -* 限流单IP一分钟60次 - - -## 创建apikey (NONE) -> **响应** -```javascript -{ - "apiKey": "bb3b24d0a3dec88cb06be58a257e4575cb0b1bb256ad6fd90ae8fd0ee1d102ae", - "apiSecret": "9fe8f5642ae1961674ea0cb7f957fa99dc8e0421b607c985a963ad2ced90ae1c" -} -``` - -`` -POST /api/v1/createApiKey -`` - -**权重:** -1 - -**参数:** - -名称 | 类型 | 是否必需 | 描述 ------------- | ------------ | ------------ | ------------ -address | STRING | YES | -userOperationType | STRING | YES | CREATE_API_KEY -network | STRING | NO | -userSignature | STRING | YES | -apikeyIP | STRING | NO | -desc | STRING | YES | -recvWindow | LONG | NO | -timestamp | LONG | YES | - -注意: -* userOperationType 仅可取值: CREATE_API_KEY -* network: sol网络必须传入SOL,其他忽略 -* desc: 同一账户不能重复,长度不能超过20个字符 -* apikeyIP ip数组以,分隔 -* 限流单IP一分钟60次 -* userSignature evm demo - -```shell - -const nonce = 111111 -const message = 'You are signing into Astherus ${nonce}' ; - -const signature = await signer.signMessage(message); -``` - - ## 账户信息 (USER_DATA) > **响应** ```javascript From b0d98d2f90c0d2bbbda600d9e47a5148de8080ba Mon Sep 17 00:00:00 2001 From: Vanessa Date: Sat, 28 Mar 2026 15:56:29 +0800 Subject: [PATCH 079/131] modify description for privacy --- aster-chain-rpc.md | 12 ++++++------ aster-chain-rpc_CN.md | 12 ++++++------ 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/aster-chain-rpc.md b/aster-chain-rpc.md index 7e45a5c..9bc9adf 100644 --- a/aster-chain-rpc.md +++ b/aster-chain-rpc.md @@ -64,7 +64,7 @@ curl -X POST "https://tapi.asterdex.com/info" \ { "result": { "address": "0x690931c*********", - "accountPrivy": "disabled", + "accountPrivacy": "disabled", "perpAssets": [ { "asset": "USD1", @@ -111,7 +111,7 @@ curl -X POST "https://tapi.asterdex.com/info" \ Name | Type | Description ---- | ---- | ----------- address | STRING | Wallet address -accountPrivy | STRING | Privacy mode status: `"disabled"` or `"enabled"` +accountPrivacy | STRING | Privacy mode status: `"disabled"` or `"enabled"` perpAssets | ARRAY | List of perpetual assets and balances perpAssets[].asset | STRING | Asset name perpAssets[].walletBalance | DECIMAL | Wallet balance @@ -180,7 +180,7 @@ curl -X POST "https://tapi.asterdex.com/info" \ { "result": { "address": "0x690931c*********", - "accountPrivy": "disabled", + "accountPrivacy": "disabled", "openOrders": [ { "orderId": "web_AD_7jz2xjo0ma4nblniq_98", @@ -210,7 +210,7 @@ curl -X POST "https://tapi.asterdex.com/info" \ Name | Type | Description ---- | ---- | ----------- address | STRING | Wallet address -accountPrivy | STRING | Privacy mode status: `"disabled"` or `"enabled"` +accountPrivacy | STRING | Privacy mode status: `"disabled"` or `"enabled"` openOrders | ARRAY | List of open orders openOrders[].orderId | STRING | Order ID openOrders[].symbol | STRING | Trading pair symbol @@ -269,7 +269,7 @@ curl -X POST "https://tapi.asterdex.com/info" \ { "result": { "address": "0x87EC27*********************", - "accountPrivy": "disabled", + "accountPrivacy": "disabled", "startTime": 1773916057398, "endTime": 1774520857398, "fills": [ @@ -313,7 +313,7 @@ curl -X POST "https://tapi.asterdex.com/info" \ Name | Type | Description ---- | ---- | ----------- address | STRING | Wallet address -accountPrivy | STRING | Privacy mode status: `"disabled"` or `"enabled"` +accountPrivacy | STRING | Privacy mode status: `"disabled"` or `"enabled"` startTime | LONG | Actual query start time in milliseconds endTime | LONG | Actual query end time in milliseconds fills | ARRAY | List of trade fills; returns at most `1000` records diff --git a/aster-chain-rpc_CN.md b/aster-chain-rpc_CN.md index 909f4ef..1ce3dd4 100644 --- a/aster-chain-rpc_CN.md +++ b/aster-chain-rpc_CN.md @@ -64,7 +64,7 @@ curl -X POST "https://tapi.asterdex.com/info" \ { "result": { "address": "0x690931c*********", - "accountPrivy": "disabled", + "accountPrivacy": "disabled", "perpAssets": [ { "asset": "USD1", @@ -111,7 +111,7 @@ curl -X POST "https://tapi.asterdex.com/info" \ 字段名 | 类型 | 说明 ------ | ---- | ---- address | STRING | 钱包地址 -accountPrivy | STRING | 隐私模式状态:`"disabled"` 已关闭 / `"enabled"` 已开启 +accountPrivacy | STRING | 隐私模式状态:`"disabled"` 已关闭 / `"enabled"` 已开启 perpAssets | ARRAY | 永续合约资产列表 perpAssets[].asset | STRING | 资产名称 perpAssets[].walletBalance | DECIMAL | 钱包余额 @@ -180,7 +180,7 @@ curl -X POST "https://tapi.asterdex.com/info" \ { "result": { "address": "0x690931c*********", - "accountPrivy": "disabled", + "accountPrivacy": "disabled", "openOrders": [ { "orderId": "web_AD_7jz2xjo0ma4nblniq_98", @@ -210,7 +210,7 @@ curl -X POST "https://tapi.asterdex.com/info" \ 字段名 | 类型 | 说明 ------ | ---- | ---- address | STRING | 钱包地址 -accountPrivy | STRING | 隐私模式状态:`"disabled"` 已关闭 / `"enabled"` 已开启 +accountPrivacy | STRING | 隐私模式状态:`"disabled"` 已关闭 / `"enabled"` 已开启 openOrders | ARRAY | 当前挂单列表 openOrders[].orderId | STRING | 订单 ID openOrders[].symbol | STRING | 交易对名称 @@ -269,7 +269,7 @@ curl -X POST "https://tapi.asterdex.com/info" \ { "result": { "address": "0x1c3C4*************", - "accountPrivy": "disabled", + "accountPrivacy": "disabled", "startTime": 1773916057398, "endTime": 1774520857398, "fills": [ @@ -313,7 +313,7 @@ curl -X POST "https://tapi.asterdex.com/info" \ 字段名 | 类型 | 说明 ------ | ---- | ---- address | STRING | 钱包地址 -accountPrivy | STRING | 隐私模式状态:`"disabled"` 已关闭 / `"enabled"` 已开启 +accountPrivacy | STRING | 隐私模式状态:`"disabled"` 已关闭 / `"enabled"` 已开启 startTime | LONG | 实际查询起始时间(毫秒时间戳) endTime | LONG | 实际查询结束时间(毫秒时间戳) fills | ARRAY | 成交记录列表,最多返回 `1000` 条 From 3ef429b0f6c8c91dd48cd6f94fdf30ed56cde1af Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Tue, 31 Mar 2026 17:43:00 +0800 Subject: [PATCH 080/131] add MMP endpoints to EN and CN futures API v3 docs Co-Authored-By: Claude Sonnet 4.6 --- aster-finance-futures-api-v3.md | 99 ++++++++++++++++++++++++++ aster-finance-futures-api-v3_CN.md | 108 +++++++++++++++++++++++++++++ 2 files changed, 207 insertions(+) diff --git a/aster-finance-futures-api-v3.md b/aster-finance-futures-api-v3.md index 7c3d1e8..81fc299 100644 --- a/aster-finance-futures-api-v3.md +++ b/aster-finance-futures-api-v3.md @@ -94,6 +94,10 @@ - [Position ADL Quantile Estimation (USER_DATA)](#position-adl-quantile-estimation-user_data) - [User's Force Orders (USER_DATA)](#users-force-orders-user_data) - [User Commission Rate (USER_DATA)](#user-commission-rate-user_data) + - [Update User MMP (USER_DATA)](#update-user-mmp-user_data) + - [Get User MMP (USER_DATA)](#get-user-mmp-user_data) + - [Delete User MMP (USER_DATA)](#delete-user-mmp-user_data) + - [Reset User MMP (USER_DATA)](#reset-user-mmp-user_data) - [User Data Streams](#user-data-streams) - [Start User Data Stream (USER_STREAM)](#start-user-data-stream-user_stream) - [Keepalive User Data Stream (USER_STREAM)](#keepalive-user-data-stream-user_stream) @@ -3510,6 +3514,101 @@ Get trades for a specific account and symbol. | ---------- | ------ | --------- | ----------- | | symbol | STRING | YES | | + +## Update User MMP (USER_DATA) + +> **Response:** + +```javascript +true +``` + +``POST /fapi/v3/mmp`` + +**Weight:** +1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| -------------------------- | ------ | --------- | ----------- | +| symbol | STRING | YES | | +| windowTimeInMilliseconds | LONG | YES | Time window (in ms) for calculating qtyLimit, valueLimit, and deltaLimit | +| frozenTimeInMilliseconds | LONG | YES | Duration (in ms) during which MMP orders are prohibited after a limit is triggered | +| qtyLimit | LONG | FALSE | Maximum cumulative filled quantity (both buy and sell) within the window. If reached, triggers the frozen period | +| valueLimit | LONG | FALSE | Maximum cumulative notional value within the window. If reached, triggers the frozen period | +| deltaLimit | LONG | FALSE | Maximum cumulative net position change (buys minus sells) within the window. If reached, triggers the frozen period | + + +## Get User MMP (USER_DATA) + +> **Response:** + +```javascript +[ + { + "symbol":"BTCUSDT", + "windowTimeInMilliseconds":5000, + "frozenTimeInMilliseconds":10000, + "qtyLimit":10, + "valueLimit":200000000, + "deltaLimit":100000000 + } +] +``` + +``GET /fapi/v3/mmp`` + +**Weight:** +1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ------ | ------ | --------- | ----------- | +| symbol | STRING | FALSE | | + + +## Delete User MMP (USER_DATA) + +> **Response:** + +```javascript +true +``` + +``DELETE /fapi/v3/mmp`` + +**Weight:** +1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ------ | ------ | --------- | ----------- | +| symbol | STRING | YES | | + + +## Reset User MMP (USER_DATA) + +> **Response:** + +```javascript +true +``` + +``POST /fapi/v3/mmpReset`` + +**Weight:** +1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ------ | ------ | --------- | ----------- | +| symbol | STRING | YES | | + + # User Data Streams * The base API endpoint is: **https://fapi.asterdex.com** diff --git a/aster-finance-futures-api-v3_CN.md b/aster-finance-futures-api-v3_CN.md index 7b9191e..684ea81 100644 --- a/aster-finance-futures-api-v3_CN.md +++ b/aster-finance-futures-api-v3_CN.md @@ -92,6 +92,10 @@ - [持仓ADL队列估算 (USER_DATA)](#持仓adl队列估算-user_data) - [用户强平单历史 (USER_DATA)](#用户强平单历史-user_data) - [用户手续费率 (USER_DATA)](#用户手续费率-user_data) + - [更新用户MMP (USER_DATA)](#更新用户mmp-user_data) + - [获取用户MMP (USER_DATA)](#获取用户mmp-user_data) + - [删除用户MMP (USER_DATA)](#删除用户mmp-user_data) + - [重置用户MMP (USER_DATA)](#重置用户mmp-user_data) - [Websocket 账户信息推送](#websocket-账户信息推送) - [生成listenKey (USER_STREAM)](#生成listenkey-user_stream) - [延长listenKey有效期 (USER_STREAM)](#延长listenkey有效期-user_stream) @@ -3652,6 +3656,110 @@ GET /fapi/v3/commissionRate`` symbol | STRING | YES +## 更新用户MMP (USER_DATA) + +> **响应:** + +```javascript +true +``` + +`` +POST /fapi/v3/mmp`` + +**权重:** +1 + + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES +windowTimeInMilliseconds | LONG | YES | 计算qtyLimit、valueLimit、deltaLimit的时间窗口(单位ms) +frozenTimeInMilliseconds | LONG | YES | 在frozenTimeInMilliseconds的时间内,禁止下MMP的订单 +qtyLimit | LONG | FALSE | 在windowTime内,累计成交的数量上限(不区分买卖),如在windowTime内到达了设置的qtyLimit,则触发frozenTimeInMilliseconds +valueLimit | LONG | FALSE | 在windowTime内,累计成交的名义价值上限,如在windowTime内到达了设置的valueLimit,则触发frozenTimeInMilliseconds +deltaLimit | LONG | FALSE |在windowTime内,累计持仓变化上限(买卖对冲后),如在windowTime内到达了设置的deltaLimit,则触发frozenTimeInMilliseconds + + + +## 获取用户MMP (USER_DATA) + +> **响应:** + +```javascript +[ + { + "symbol":"BTCUSDT", + "windowTimeInMilliseconds":5000, + "frozenTimeInMilliseconds":10000, + "qtyLimit":10, + "valueLimit":200000000, + "deltaLimit":100000000 + } +] + +``` + +`` +GET /fapi/v3/mmp`` + +**权重:** +1 + + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | FALSE + + + +## 删除用户MMP (USER_DATA) + +> **响应:** + +```javascript +true +``` + +`` +DELETE /fapi/v3//mmp`` + +**权重:** +1 + + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES + + + +## 重置用户MMP (USER_DATA) + +> **响应:** + +```javascript +true +``` + +`` +POST /fapi/v3/mmpReset`` + +**权重:** +1 + + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES From 87fe70f1b2a1a44ed45ef3c2e688e5e437c022cc Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Wed, 1 Apr 2026 10:44:36 +0800 Subject: [PATCH 081/131] fix double-slash typo in DELETE /fapi/v3/mmp CN doc Co-Authored-By: Claude Sonnet 4.6 --- aster-finance-futures-api-v3_CN.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/aster-finance-futures-api-v3_CN.md b/aster-finance-futures-api-v3_CN.md index 684ea81..a4833a9 100644 --- a/aster-finance-futures-api-v3_CN.md +++ b/aster-finance-futures-api-v3_CN.md @@ -3726,7 +3726,7 @@ true ``` `` -DELETE /fapi/v3//mmp`` +DELETE /fapi/v3/mmp`` **权重:** 1 From 6d37097d1b571114f84a0e425c75f935b243b46b Mon Sep 17 00:00:00 2001 From: Vanessa Date: Wed, 1 Apr 2026 17:54:23 +0800 Subject: [PATCH 082/131] add note --- aster-chain-rpc.md | 4 +++- aster-chain-rpc_CN.md | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/aster-chain-rpc.md b/aster-chain-rpc.md index 9bc9adf..2f4aef3 100644 --- a/aster-chain-rpc.md +++ b/aster-chain-rpc.md @@ -321,4 +321,6 @@ fills[].symbol | STRING | Trading pair symbol fills[].side | STRING | Trade side: `BUY` or `SELL` fills[].price | STRING | Fill price fills[].qty | STRING | Fill quantity -fills[].time | LONG | Fill time in milliseconds \ No newline at end of file +fills[].time | LONG | Fill time in milliseconds + +> **Note:** This endpoint only returns futures trade fill data. \ No newline at end of file diff --git a/aster-chain-rpc_CN.md b/aster-chain-rpc_CN.md index 1ce3dd4..5d05ee8 100644 --- a/aster-chain-rpc_CN.md +++ b/aster-chain-rpc_CN.md @@ -321,4 +321,6 @@ fills[].symbol | STRING | 交易对名称 fills[].side | STRING | 成交方向:`BUY` 买入 / `SELL` 卖出 fills[].price | STRING | 成交价格 fills[].qty | STRING | 成交数量 -fills[].time | LONG | 成交时间(毫秒时间戳) \ No newline at end of file +fills[].time | LONG | 成交时间(毫秒时间戳) + +> **注意:** 该接口仅返回期货成交数据。 \ No newline at end of file From 6257ec4fcc58a21a53ccb9ff1f88e485ddb50b18 Mon Sep 17 00:00:00 2001 From: Vanessa Date: Wed, 1 Apr 2026 17:58:49 +0800 Subject: [PATCH 083/131] add note --- aster-chain-rpc.md | 6 +++--- aster-chain-rpc_CN.md | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/aster-chain-rpc.md b/aster-chain-rpc.md index 2f4aef3..ea2693b 100644 --- a/aster-chain-rpc.md +++ b/aster-chain-rpc.md @@ -3,7 +3,7 @@ - [Chain RPC Endpoints](#chain-rpc-endpoints) - [Get Balance](#get-balance) - [Get Open Orders](#get-open-orders) - - [Get User Fills](#get-user-fills) + - [Get User Futures Fills](#get-user-futures-fills) # General Info @@ -139,7 +139,7 @@ positions[].positions[].marginValue | STRING | Margin value POST /info `` -Query all open orders for a given address. +Query futures open orders for a given address. > **Note:** Only open orders created at or after block 1 genesis time (`1772678119418`) are returned. Maximum **1000** records returned. @@ -220,7 +220,7 @@ openOrders[].origQty | STRING | Original order quantity openOrders[].status | STRING | Order status: e.g. `NEW` -## Get User Fills +## Get User Futures Fills `` POST /info diff --git a/aster-chain-rpc_CN.md b/aster-chain-rpc_CN.md index 5d05ee8..adecf48 100644 --- a/aster-chain-rpc_CN.md +++ b/aster-chain-rpc_CN.md @@ -3,7 +3,7 @@ - [链上 RPC 接口](#链上-rpc-接口) - [查询账户余额](#查询账户余额) - [查询当前挂单](#查询当前挂单) - - [查询用户成交记录](#查询用户成交记录) + - [查询用户期货成交记录](#查询用户期货成交记录) # 基本信息 @@ -139,7 +139,7 @@ positions[].positions[].marginValue | STRING | 保证金价值 POST /info `` -查询指定地址的所有当前挂单。 +查询指定地址的期货当前挂单。 > **说明:** 仅返回创建时间不早于 block 1 创世时间(`1772678119418`)的挂单,最多返回 **1000** 条。 @@ -220,7 +220,7 @@ openOrders[].origQty | STRING | 原始委托数量 openOrders[].status | STRING | 订单状态:如 `NEW` 待成交 -## 查询用户成交记录 +## 查询用户期货成交记录 `` POST /info From 3f8a18c2fb316f7905e8551f3370aa35659ff793 Mon Sep 17 00:00:00 2001 From: aodyc Date: Fri, 3 Apr 2026 14:57:48 +0800 Subject: [PATCH 084/131] docs: add V3 versions of user-withdraw-info and deposit-withdraw-history, deprecate V1 interfaces --- aster-deposit-withdrawal.md | 120 ++++++++++++++++++++++++++++++++++++ 1 file changed, 120 insertions(+) diff --git a/aster-deposit-withdrawal.md b/aster-deposit-withdrawal.md index 2211540..2009db8 100644 --- a/aster-deposit-withdrawal.md +++ b/aster-deposit-withdrawal.md @@ -7,6 +7,8 @@ - [get server time](#get-server-time) - [get user withdraw info](#get-user-withdraw-info) - [get deposit and withdraw history](#get-deposit-and-withdraw-history) + - [get user withdraw info \[v3\]](#get-user-withdraw-infov3) + - [get deposit and withdraw history \[v3\]](#get-deposit-and-withdraw-historyv3) - [Signature](#signature) - [API-KEY Signature (V1)](#api-key-signature-v1) - [Pro API-KEY Signature (V3)](#pro-api-key-signature-v3) @@ -193,6 +195,8 @@ curl 'https://fapi5.asterdex.com/fapi/v3/time' ## get user withdraw info +> **Deprecated:** This V1 interface will be discontinued in the future. Please migrate to the [V3 version](#get-user-withdraw-infov3). + * Note: Follow the [API-KEY Signature (V1)](#api-key-signature-v1) instructions to generate the required request signature. ### request: @@ -254,6 +258,8 @@ No additional parameters required beyond the standard V1 signature parameters (` ## get deposit and withdraw history +> **Deprecated:** This V1 interface will be discontinued in the future. Please migrate to the [V3 version](#get-deposit-and-withdraw-historyv3). + * Note: Follow the [API-KEY Signature (V1)](#api-key-signature-v1) instructions to generate the required request signature. ### request: @@ -297,6 +303,112 @@ No additional parameters required beyond the standard V1 signature parameters (` | chainId | Chain ID | | accountType | Account type: `spot` or `perp` | +## get user withdraw info\[v3\] + +* Note: Follow the [Pro API-KEY Signature (V3)](#pro-api-key-signature-v3) instructions to generate the required request signature. The example below includes only the parameters specific to this endpoint. + +### request: + +```shell +curl --location --request POST 'https://fapi.asterdex.com/fapi/v3/aster/user-withdraw-info' \ + --header 'Content-Type: application/json' +``` + +### params: + +No additional parameters required beyond the standard V3 signature parameters. + +### response: + +```json +{ + "userDailyLimit": "10000", + "userRemainingDailyLimit": "9000", + "totalDailyLimit": "1000000", + "totalRemainingDailyLimit": "980000", + "balances": { + "USDT": { + "currency": "USDT", + "spotTotalWithdrawAmount": "500", + "perpTotalWithdrawAmount": "300", + "dailyLimit": "9000", + "chainBalances": { + "56": { + "chainId": 56, + "spotMaxWithdrawAmount": "500", + "perpMaxWithdrawAmount": "300", + "chainLimit": "800", + "withdrawFee": "0.5" + } + } + } + } +} +``` + +| field | desc | +|--------------------------|-------------------------------------------------------------------| +| userDailyLimit | User's daily withdrawal limit, denominated in USD | +| userRemainingDailyLimit | User's remaining daily withdrawal limit, denominated in USD | +| totalDailyLimit | Global daily withdrawal limit, denominated in USD | +| totalRemainingDailyLimit | Global remaining daily withdrawal limit, denominated in USD | +| balances | Map of non-zero asset balances, keyed by asset name | +| balances.currency | Asset name | +| balances.spotTotalWithdrawAmount | Total spot balance available for withdrawal | +| balances.perpTotalWithdrawAmount | Total futures balance available for withdrawal | +| balances.dailyLimit | Remaining daily withdrawal limit for this asset, denominated in USD | +| balances.chainBalances | Per-chain balance info, keyed by chain ID | +| balances.chainBalances.chainId | Chain ID | +| balances.chainBalances.spotMaxWithdrawAmount | Max withdrawable spot amount on this chain | +| balances.chainBalances.perpMaxWithdrawAmount | Max withdrawable futures amount on this chain | +| balances.chainBalances.chainLimit | Max withdrawable amount on this chain | +| balances.chainBalances.withdrawFee | Withdrawal fee on this chain | + +## get deposit and withdraw history\[v3\] + +* Note: Follow the [Pro API-KEY Signature (V3)](#pro-api-key-signature-v3) instructions to generate the required request signature. The example below includes only the parameters specific to this endpoint. + +### request: + +```shell +curl --location --request POST 'https://fapi.asterdex.com/fapi/v3/aster/deposit-withdraw-history' \ + --header 'Content-Type: application/json' +``` + +### params: + +No additional parameters required beyond the standard V3 signature parameters. + +### response: + +```json +[ + { + "id": "1234567", + "type": "DEPOSIT", + "asset": "USDT", + "amount": "100", + "state": "SUCCESS", + "txHash": "0x9a40f0119b670fb6b155744b51981f91c4c4c8a20c333441a63853fe7d055c90", + "time": 1742198400000, + "chainId": 56, + "accountType": "spot" + } +] +``` + +| field | desc | +|-------------|----------------------------------------------------------------------| +| id | Record ID | +| type | Record type: `DEPOSIT` or `WITHDRAW` | +| asset | Asset name, e.g., USDT | +| amount | Amount | +| state | Status: `PROCESSING`, `SUCCESS`, or `FAILED` | +| txHash | On-chain transaction hash | +| time | Record time in milliseconds (Unix) | +| chainId | Chain ID | +| accountType | Account type: `spot` or `perp` | + --- # Signature @@ -516,6 +628,8 @@ const userSignature = bs58.encode(signatureBytes); ## withdraw by fapi \[evm\] \[futures\] +> **Deprecated:** This V1 interface will be discontinued in the future. Please migrate to the [V3 version](#withdraw-by-fapiv3-evm-futures). + * Note: Follow the [API-KEY Signature (V1)](#api-key-signature-v1) instructions to generate the required request signature. The example below includes only the parameters specific to this endpoint. ### request: @@ -554,6 +668,8 @@ curl --location --request POST 'https://fapi.asterdex.com/fapi/aster/user-withdr ## withdraw by API \[evm\] \[spot\] +> **Deprecated:** This V1 interface will be discontinued in the future. Please migrate to the [V3 version](#withdraw-by-fapiv3-evm-spot). + ### request: ```shell @@ -590,6 +706,8 @@ curl --location --request POST 'https://sapi.asterdex.com/api/v1/aster/user-with ## withdraw by fapi \[solana\] \[futures\] +> **Deprecated:** This V1 interface will be discontinued in the future. Please migrate to the [V3 version](#withdraw-by-fapiv3-solana-futures). + ### request: ```shell @@ -623,6 +741,8 @@ curl --location --request POST 'https://fapi.asterdex.com/fapi/aster/user-solana ## withdraw by API \[solana\] \[spot\] +> **Deprecated:** This V1 interface will be discontinued in the future. Please migrate to the [V3 version](#withdraw-by-fapiv3-solana-spot). + ### request: ```shell From ccc76056925c05a8c8f29c7422d7c85c83df0c9e Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Tue, 7 Apr 2026 16:14:40 +0800 Subject: [PATCH 085/131] transactionHistory --- aster-finance-spot-api-testnet.md | 40 ++++++++++++++++++++++++++++++ aster-finance-spot-api-v3.md | 39 +++++++++++++++++++++++++++++ aster-finance-spot-api.md | 41 +++++++++++++++++++++++++++++++ 3 files changed, 120 insertions(+) diff --git a/aster-finance-spot-api-testnet.md b/aster-finance-spot-api-testnet.md index 6c4eb0f..fcce260 100644 --- a/aster-finance-spot-api-testnet.md +++ b/aster-finance-spot-api-testnet.md @@ -1275,6 +1275,46 @@ Retrieve all account orders; active, canceled, or completed. * By default, query data is from the last 7 days. +`` +GET /api/v3/transactionHistory`` +> **Response** + +```javascript +[ + { + "tranId": 1759115482304540227, + "tradeId": null, + "asset": "ASTER", + "symbol": "", + "balanceDelta": "-500.00000000", + "balanceInfo": "TRADE_SOURCE", + "time": 1759115482000, + "type": "TRADE_SOURCE" + } +] +``` + +Query transaction records + +**Weight:** +30 + +**Parameters:** + +| Name | Type | Is it required? | Description | +------------ | ------------ | ------------ | ------------ +asset | STRING | NO | asset +type | STRING | NO | type +startTime | LONG | NO | startTime +endTime | LONG | NO | endTime +limit | LONG | NO | default:100 max:1000 + +**Note:** + +* `type`: `TRADE_TARGET`,`TRADE_SOURCE`,`TRANSFER_SPOT_TO_FUTURE`,`TRANSFER_FUTURE_TO_SPOT`,`TRANSFER_SPOT_TO_SPOT`,`AIRDROP`,`DIVIDEND`,`TRANSFER_REFUND`,`INTERNAL_TRANSFER`,`TRANSFER`,`SWAP`,`COMMISSION_REBATE`,`CASH_BACK` +* If startTime and endTime are not provided, only data from the most recent 7 days will be returned. + + ## Perp-spot transfer (TRADE) **Response:** diff --git a/aster-finance-spot-api-v3.md b/aster-finance-spot-api-v3.md index 5c8fc6d..f4f6c0d 100644 --- a/aster-finance-spot-api-v3.md +++ b/aster-finance-spot-api-v3.md @@ -1253,6 +1253,45 @@ Retrieve all account orders; active, canceled, or completed. * By default, query data is from the last 7 days. +`` +GET /api/v3/transactionHistory`` +> **Response** + +```javascript +[ + { + "tranId": 1759115482304540227, + "tradeId": null, + "asset": "ASTER", + "symbol": "", + "balanceDelta": "-500.00000000", + "balanceInfo": "TRADE_SOURCE", + "time": 1759115482000, + "type": "TRADE_SOURCE" + } +] +``` + +Query transaction records + +**Weight:** +30 + +**Parameters:** + +| Name | Type | Is it required? | Description | +------------ | ------------ | ------------ | ------------ +asset | STRING | NO | asset +type | STRING | NO | type +startTime | LONG | NO | startTime +endTime | LONG | NO | endTime +limit | LONG | NO | default:100 max:1000 + +**Note:** + +* `type`: `TRADE_TARGET`,`TRADE_SOURCE`,`TRANSFER_SPOT_TO_FUTURE`,`TRANSFER_FUTURE_TO_SPOT`,`TRANSFER_SPOT_TO_SPOT`,`AIRDROP`,`DIVIDEND`,`TRANSFER_REFUND`,`INTERNAL_TRANSFER`,`TRANSFER`,`SWAP`,`COMMISSION_REBATE`,`CASH_BACK` +* If startTime and endTime are not provided, only data from the most recent 7 days will be returned. + ## Perp-spot transfer (TRADE) **Response:** diff --git a/aster-finance-spot-api.md b/aster-finance-spot-api.md index 97f9db6..df8da12 100644 --- a/aster-finance-spot-api.md +++ b/aster-finance-spot-api.md @@ -1191,6 +1191,47 @@ Retrieve all account orders; active, canceled, or completed. * By default, query data is from the last 7 days. + +`` +GET /api/v1/transactionHistory`` +> **Response** + +```javascript +[ + { + "tranId": 1759115482304540227, + "tradeId": null, + "asset": "ASTER", + "symbol": "", + "balanceDelta": "-500.00000000", + "balanceInfo": "TRADE_SOURCE", + "time": 1759115482000, + "type": "TRADE_SOURCE" + } +] +``` + +Query transaction records + +**Weight:** +30 + +**Parameters:** + +| Name | Type | Is it required? | Description | +------------ | ------------ | ------------ | ------------ +asset | STRING | NO | asset +type | STRING | NO | type +startTime | LONG | NO | startTime +endTime | LONG | NO | endTime +limit | LONG | NO | default:100 max:1000 + +**Note:** + +* `type`: `TRADE_TARGET`,`TRADE_SOURCE`,`TRANSFER_SPOT_TO_FUTURE`,`TRANSFER_FUTURE_TO_SPOT`,`TRANSFER_SPOT_TO_SPOT`,`AIRDROP`,`DIVIDEND`,`TRANSFER_REFUND`,`INTERNAL_TRANSFER`,`TRANSFER`,`SWAP`,`COMMISSION_REBATE`,`CASH_BACK` +* If startTime and endTime are not provided, only data from the most recent 7 days will be returned. + + ## Perp-spot transfer (TRADE) **Response:** From cbed1de2ed93c51da6479ceb14d9da3922951bd3 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Tue, 7 Apr 2026 18:11:16 +0800 Subject: [PATCH 086/131] new_dir --- ... V3 interfaces.md => Aster API Overview.md | 5 ++- README.md | 34 +++++++------------ aster-chain-rpc.md => RPC/aster-chain-rpc.md | 0 .../aster-chain-rpc_CN.md | 0 .../EN/aster-finance-futures-api.md | 0 .../EN/aster-finance-spot-api.md | 0 .../aster-finance-futures-api_CN.md" | 0 .../aster-finance-spot-api_CN.md" | 0 .../EN/aster-finance-futures-api-testnet.md | 0 .../EN/aster-finance-futures-api-v3.md | 0 .../EN/aster-finance-spot-api-testnet.md | 0 .../EN/aster-finance-spot-api-v3.md | 0 .../aster-finance-futures-api-v3_CN.md" | 0 .../aster-finance-spot-api_CN-v3.md" | 0 .../aster-api-key-registration.md | 0 .../aster-deposit-withdrawal.md | 0 consolidation.js => demo/consolidation.js | 0 17 files changed, 17 insertions(+), 22 deletions(-) rename Difference between V1 and V3 interfaces.md => Aster API Overview.md (95%) rename aster-chain-rpc.md => RPC/aster-chain-rpc.md (100%) rename aster-chain-rpc_CN.md => RPC/aster-chain-rpc_CN.md (100%) rename aster-finance-futures-api.md => V1(Legacy)/EN/aster-finance-futures-api.md (100%) rename aster-finance-spot-api.md => V1(Legacy)/EN/aster-finance-spot-api.md (100%) rename aster-finance-futures-api_CN.md => "V1(Legacy)/\344\270\255\346\226\207/aster-finance-futures-api_CN.md" (100%) rename aster-finance-spot-api_CN.md => "V1(Legacy)/\344\270\255\346\226\207/aster-finance-spot-api_CN.md" (100%) rename aster-finance-futures-api-testnet.md => V3(Recommended)/EN/aster-finance-futures-api-testnet.md (100%) rename aster-finance-futures-api-v3.md => V3(Recommended)/EN/aster-finance-futures-api-v3.md (100%) rename aster-finance-spot-api-testnet.md => V3(Recommended)/EN/aster-finance-spot-api-testnet.md (100%) rename aster-finance-spot-api-v3.md => V3(Recommended)/EN/aster-finance-spot-api-v3.md (100%) rename aster-finance-futures-api-v3_CN.md => "V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" (100%) rename aster-finance-spot-api_CN-v3.md => "V3(Recommended)/\344\270\255\346\226\207/aster-finance-spot-api_CN-v3.md" (100%) rename aster-api-key-registration.md => demo/aster-api-key-registration.md (100%) rename aster-deposit-withdrawal.md => demo/aster-deposit-withdrawal.md (100%) rename consolidation.js => demo/consolidation.js (100%) diff --git a/Difference between V1 and V3 interfaces.md b/Aster API Overview.md similarity index 95% rename from Difference between V1 and V3 interfaces.md rename to Aster API Overview.md index dc8176f..3ea38b3 100644 --- a/Difference between V1 and V3 interfaces.md +++ b/Aster API Overview.md @@ -1,6 +1,9 @@ # Aster API V1 vs V3 -This page provides a quick comparison between Aster `V1` and `V3`, focusing on authentication, endpoint structure, capability coverage, and the most important architectural value behind V3. +This page provides a quick comparison between Aster `V1` and `V3`, focusing on authentication, endpoint structure, capability coverage, and the most important architectural value behind V3. + +**`Starting from March 25, 2026, V1 new API Key creation is no longer supported. Existing API Keys will continue to work.`** + > **Key takeaways** > diff --git a/README.md b/README.md index eb08047..9e58763 100644 --- a/README.md +++ b/README.md @@ -1,59 +1,51 @@ # API Documentation for Aster Finance Futures -[Aster Finance Futures API Document](./aster-finance-futures-api.md) +[Aster Finance Futures API Document](./V1(Legacy)/EN/aster-finance-futures-api.md) # Aster Finance Futures API 文档 -[Aster Finance Futures API 文档](./aster-finance-futures-api_CN.md) +[Aster Finance Futures API 文档](./V1(Legacy)/中文/aster-finance-futures-api_CN.md) # API V3 Documentation for Aster Finance Futures -[Aster Finance Futures API V3 Document](./aster-finance-futures-api-v3.md) +[Aster Finance Futures API V3 Document](./V3(Recommended)/EN/aster-finance-futures-api-v3.md) # Aster Finance Futures API V3 文档 -[Aster Finance Futures API V3 文档](./aster-finance-futures-api-v3_CN.md) +[Aster Finance Futures API V3 文档](./V3(Recommended)/中文/aster-finance-futures-api-v3_CN.md) # Aster Finance Futures Testnet API V3 文档 -[Aster Finance Futures Testnet API V3 文档](./aster-finance-futures-api-testnet.md) - -# Aster Finance Futures API V3 PYTHON DEMO - -[Aster Finance Futures API V3 PYTHON DEMO](./v3-demo/tx.py) - -# Aster Finance Futures API V3 GO DEMO - -[Aster Finance Futures API V3 GO DEMO](./v3-demo/main.go) +[Aster Finance Futures Testnet API V3 文档](./V3(Recommended)/EN/aster-finance-futures-api-testnet.md) # API Documentation for Aster Finance Spot -[Aster Finance Spot API Document](./aster-finance-spot-api.md) +[Aster Finance Spot API Document](./V1(Legacy)/EN/aster-finance-spot-api.md) # Aster Finance Spot API 文档 -[Aster Finance Spot API 文档](./aster-finance-spot-api_CN.md) +[Aster Finance Spot API 文档](./V1(Legacy)/中文/aster-finance-spot-api_CN.md) # Aster Finance Spot Testnet API V3 文档 -[Aster Finance Spot Testnet API V3 文档](./aster-finance-spot-api-testnet.md) +[Aster Finance Spot Testnet API V3 文档](./V3(Recommended)/EN/aster-finance-spot-api-testnet.md) # Aster Finance Spot Asset Consolidation -[Aster Finance Spot Asset Consolidation](./consolidation.js) +[Aster Finance Spot Asset Consolidation](./Demo/consolidation.js) # Aster Api Key -[Aster Api Key](./aster-api-key-registration.md) +[Aster Api Key](./Demo/aster-api-key-registration.md) # Aster 现货资产归集脚本示例 -[Aster 现货资产归集脚本示例](./consolidation.js) +[Aster 现货资产归集脚本示例](./Demo/consolidation.js) # Aster 充值提现 -[Aster Deposit and Withdrawal](./aster-deposit-withdrawal.md) +[Aster Deposit and Withdrawal](./Demo/aster-deposit-withdrawal.md) # Aster Chain RPC -[Aster Chain RPC](./aster-chain-rpc.md) +[Aster Chain RPC](./RPC/aster-chain-rpc.md) diff --git a/aster-chain-rpc.md b/RPC/aster-chain-rpc.md similarity index 100% rename from aster-chain-rpc.md rename to RPC/aster-chain-rpc.md diff --git a/aster-chain-rpc_CN.md b/RPC/aster-chain-rpc_CN.md similarity index 100% rename from aster-chain-rpc_CN.md rename to RPC/aster-chain-rpc_CN.md diff --git a/aster-finance-futures-api.md b/V1(Legacy)/EN/aster-finance-futures-api.md similarity index 100% rename from aster-finance-futures-api.md rename to V1(Legacy)/EN/aster-finance-futures-api.md diff --git a/aster-finance-spot-api.md b/V1(Legacy)/EN/aster-finance-spot-api.md similarity index 100% rename from aster-finance-spot-api.md rename to V1(Legacy)/EN/aster-finance-spot-api.md diff --git a/aster-finance-futures-api_CN.md "b/V1(Legacy)/\344\270\255\346\226\207/aster-finance-futures-api_CN.md" similarity index 100% rename from aster-finance-futures-api_CN.md rename to "V1(Legacy)/\344\270\255\346\226\207/aster-finance-futures-api_CN.md" diff --git a/aster-finance-spot-api_CN.md "b/V1(Legacy)/\344\270\255\346\226\207/aster-finance-spot-api_CN.md" similarity index 100% rename from aster-finance-spot-api_CN.md rename to "V1(Legacy)/\344\270\255\346\226\207/aster-finance-spot-api_CN.md" diff --git a/aster-finance-futures-api-testnet.md b/V3(Recommended)/EN/aster-finance-futures-api-testnet.md similarity index 100% rename from aster-finance-futures-api-testnet.md rename to V3(Recommended)/EN/aster-finance-futures-api-testnet.md diff --git a/aster-finance-futures-api-v3.md b/V3(Recommended)/EN/aster-finance-futures-api-v3.md similarity index 100% rename from aster-finance-futures-api-v3.md rename to V3(Recommended)/EN/aster-finance-futures-api-v3.md diff --git a/aster-finance-spot-api-testnet.md b/V3(Recommended)/EN/aster-finance-spot-api-testnet.md similarity index 100% rename from aster-finance-spot-api-testnet.md rename to V3(Recommended)/EN/aster-finance-spot-api-testnet.md diff --git a/aster-finance-spot-api-v3.md b/V3(Recommended)/EN/aster-finance-spot-api-v3.md similarity index 100% rename from aster-finance-spot-api-v3.md rename to V3(Recommended)/EN/aster-finance-spot-api-v3.md diff --git a/aster-finance-futures-api-v3_CN.md "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" similarity index 100% rename from aster-finance-futures-api-v3_CN.md rename to "V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" diff --git a/aster-finance-spot-api_CN-v3.md "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-spot-api_CN-v3.md" similarity index 100% rename from aster-finance-spot-api_CN-v3.md rename to "V3(Recommended)/\344\270\255\346\226\207/aster-finance-spot-api_CN-v3.md" diff --git a/aster-api-key-registration.md b/demo/aster-api-key-registration.md similarity index 100% rename from aster-api-key-registration.md rename to demo/aster-api-key-registration.md diff --git a/aster-deposit-withdrawal.md b/demo/aster-deposit-withdrawal.md similarity index 100% rename from aster-deposit-withdrawal.md rename to demo/aster-deposit-withdrawal.md diff --git a/consolidation.js b/demo/consolidation.js similarity index 100% rename from consolidation.js rename to demo/consolidation.js From e395ec7b7e8d29c46cac9a7c007f43f48341208b Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Tue, 7 Apr 2026 18:25:55 +0800 Subject: [PATCH 087/131] chore: ignore .claude directory Co-Authored-By: Claude Sonnet 4.6 --- .claude/settings.local.json | 9 --------- .gitignore | 1 + 2 files changed, 1 insertion(+), 9 deletions(-) delete mode 100644 .claude/settings.local.json diff --git a/.claude/settings.local.json b/.claude/settings.local.json deleted file mode 100644 index 1552e97..0000000 --- a/.claude/settings.local.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "permissions": { - "allow": [ - "Bash(git add:*)", - "Bash(git commit:*)", - "Bash(git push:*)" - ] - } -} diff --git a/.gitignore b/.gitignore index 485dee6..7da2449 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ .idea +.claude From 39e8743825a70699f918962522784707cb550b94 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Tue, 7 Apr 2026 18:26:26 +0800 Subject: [PATCH 088/131] docs: add Query Current Open Order endpoint and CN testnet API docs Co-Authored-By: Claude Sonnet 4.6 --- V1(Legacy)/EN/aster-finance-spot-api.md | 45 + .../EN/aster-finance-spot-api-v3.md | 43 + .../aster-finance-futures-api-testnet_CN.md" | 4606 +++++++++++++++++ .../aster-finance-spot-api-testnet_CN.md" | 2668 ++++++++++ 4 files changed, 7362 insertions(+) create mode 100644 "V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" create mode 100644 "V3(Recommended)/\344\270\255\346\226\207/aster-finance-spot-api-testnet_CN.md" diff --git a/V1(Legacy)/EN/aster-finance-spot-api.md b/V1(Legacy)/EN/aster-finance-spot-api.md index df8da12..cd759d4 100644 --- a/V1(Legacy)/EN/aster-finance-spot-api.md +++ b/V1(Legacy)/EN/aster-finance-spot-api.md @@ -1064,6 +1064,51 @@ Note: * You must send at least one of `orderId` or `origClientOrderId`. +## Query Current Open Order (USER\_DATA) + +**Response** + +```javascript +{ + "orderId": 38, + "symbol": "ADA25SLP25", + "status": "NEW", + "clientOrderId": "afMd4GBQyHkHpGWdiy34Li", + "price": "20", + "avgPrice": "12.0000000000000000", + "origQty": "10", + "executedQty": "10", + "cumQuote": "120", + "timeInForce": "GTC", + "type": "LIMIT", + "side": "BUY", + "stopPrice": "0", + "origType": "LIMIT", + "time": 1649913186270, + "updateTime": 1649913186297 +} +``` + +`GET /api/v1/openOrder (HMAC SHA256)` + +Query current open order status. + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| orderId | LONG | NO | | +| origClientOrderId | STRING | NO | | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +Note: + +* You must send at least one of `orderId` or `origClientOrderId`. + ## Current open orders (USER\_DATA) **Response** diff --git a/V3(Recommended)/EN/aster-finance-spot-api-v3.md b/V3(Recommended)/EN/aster-finance-spot-api-v3.md index f4f6c0d..da350fa 100644 --- a/V3(Recommended)/EN/aster-finance-spot-api-v3.md +++ b/V3(Recommended)/EN/aster-finance-spot-api-v3.md @@ -1133,6 +1133,49 @@ Note: * You must send at least one of `orderId` or `origClientOrderId`. +## Query Current Open Order (USER\_DATA) + +**Response** + +```javascript +{ + "orderId": 38, + "symbol": "ADA25SLP25", + "status": "NEW", + "clientOrderId": "afMd4GBQyHkHpGWdiy34Li", + "price": "20", + "avgPrice": "12.0000000000000000", + "origQty": "10", + "executedQty": "10", + "cumQuote": "120", + "timeInForce": "GTC", + "type": "LIMIT", + "side": "BUY", + "stopPrice": "0", + "origType": "LIMIT", + "time": 1649913186270, + "updateTime": 1649913186297 +} +``` + +`GET /api/v3/openOrder (HMAC SHA256)` + +Query current open order status. + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| orderId | LONG | NO | | +| origClientOrderId | STRING | NO | | + +Note: + +* You must send at least one of `orderId` or `origClientOrderId`. + ## Current open orders (USER\_DATA) **Response** diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" new file mode 100644 index 0000000..430e102 --- /dev/null +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" @@ -0,0 +1,4606 @@ +- [基本信息](#基本信息) + - [Rest 基本信息](#rest-基本信息) + - [HTTP 返回代码](#http-返回代码) + - [接口错误代码](#接口错误代码) + - [接口的基本信息](#接口的基本信息) + - [访问限制](#访问限制) + - [IP 访问限制](#ip-访问限制) + - [下单频率限制](#下单频率限制) + - [接口鉴权类型](#接口鉴权类型) + - [鉴权签名体](#鉴权签名体) + - [需要签名的接口](#需要签名的接口) + - [POST /fapi/v3/order 的示例](#post-fapiv3order-的示例) + - [公开API参数](#公开api参数) + - [术语解释](#术语解释) + - [枚举定义](#枚举定义) + - [过滤器](#过滤器) + - [交易对过滤器](#交易对过滤器) + - [PRICE_FILTER 价格过滤器](#price_filter-价格过滤器) + - [LOT_SIZE 订单尺寸](#lot_size-订单尺寸) + - [MARKET_LOT_SIZE 市价订单尺寸](#market_lot_size-市价订单尺寸) + - [MAX_NUM_ORDERS 最多订单数](#max_num_orders-最多订单数) + - [MAX_NUM_ALGO_ORDERS 最多条件订单数](#max_num_algo_orders-最多条件订单数) + - [PERCENT_PRICE 价格振幅过滤器](#percent_price-价格振幅过滤器) + - [MIN_NOTIONAL 最小名义价值](#min_notional-最小名义价值) +- [行情接口](#行情接口) + - [Noop](#noop) + - [测试服务器连通性 PING](#测试服务器连通性-ping) + - [获取服务器时间](#获取服务器时间) + - [获取交易规则和交易对](#获取交易规则和交易对) + - [深度信息](#深度信息) + - [近期成交](#近期成交) + - [查询历史成交(MARKET_DATA)](#查询历史成交market_data) + - [近期成交(归集)](#近期成交归集) + - [K线数据](#k线数据) + - [价格指数K线数据](#价格指数k线数据) + - [标记价格K线数据](#标记价格k线数据) + - [最新标记价格和资金费率](#最新标记价格和资金费率) + - [查询资金费率历史](#查询资金费率历史) + - [24hr价格变动情况](#24hr价格变动情况) + - [最新价格](#最新价格) + - [当前最优挂单](#当前最优挂单)- [Websocket 行情推送](#websocket-行情推送) + - [实时订阅/取消数据流](#实时订阅取消数据流) + - [订阅一个信息流](#订阅一个信息流) + - [取消订阅一个信息流](#取消订阅一个信息流) + - [已订阅信息流](#已订阅信息流) + - [设定属性](#设定属性) + - [检索属性](#检索属性) + - [错误信息](#错误信息) + - [最新合约价格](#最新合约价格) + - [归集交易](#归集交易) + - [最新标记价格](#最新标记价格) + - [全市场最新标记价格](#全市场最新标记价格) + - [K线](#k线) + - [按Symbol的精简Ticker](#按symbol的精简ticker) + - [全市场的精简Ticker](#全市场的精简ticker) + - [按Symbol的完整Ticker](#按symbol的完整ticker) + - [全市场的完整Ticker](#全市场的完整ticker) + - [按Symbol的最优挂单信息](#按symbol的最优挂单信息) + - [全市场最优挂单信息](#全市场最优挂单信息) + - [有限档深度信息](#有限档深度信息) + - [增量深度信息](#增量深度信息) + - [如何正确在本地维护一个orderbook副本](#如何正确在本地维护一个orderbook副本) +- [账户和交易接口](#账户和交易接口) + - [更改持仓模式(TRADE)](#更改持仓模式trade) + - [查询持仓模式(USER_DATA)](#查询持仓模式user_data) + - [更改联合保证金模式(TRADE)](#更改联合保证金模式trade) + - [查询联合保证金模式(USER_DATA)](#查询联合保证金模式user_data) + - [下单 (TRADE)](#下单-trade) + - [测试下单接口 (TRADE)](#测试下单接口-trade) + - [批量下单 (TRADE)](#批量下单-trade) + - [查询订单 (USER_DATA)](#查询订单-user_data) + - [撤销订单 (TRADE)](#撤销订单-trade) + - [撤销全部订单 (TRADE)](#撤销全部订单-trade) + - [批量撤销订单 (TRADE)](#批量撤销订单-trade) + - [倒计时撤销所有订单 (TRADE)](#倒计时撤销所有订单-trade) + - [查询当前挂单 (USER_DATA)](#查询当前挂单-user_data) + - [查看当前全部挂单 (USER_DATA)](#查看当前全部挂单-user_data) + - [查询所有订单(包括历史订单) (USER_DATA)](#查询所有订单包括历史订单-user_data) + - [账户余额v3 (USER_DATA)](#账户余额v3-user_data) + - [账户信息v3 (USER_DATA)](#账户信息v3-user_data) + - [调整开仓杠杆 (TRADE)](#调整开仓杠杆-trade) + - [变换逐全仓模式 (TRADE)](#变换逐全仓模式-trade) + - [调整逐仓保证金 (TRADE)](#调整逐仓保证金-trade) + - [逐仓保证金变动历史 (TRADE)](#逐仓保证金变动历史-trade) + - [用户持仓风险v3 (USER_DATA)](#用户持仓风险v3-user_data) + - [账户成交历史 (USER_DATA)](#账户成交历史-user_data) + - [获取账户损益资金流水(USER_DATA)](#获取账户损益资金流水user_data) + - [杠杆分层标准 (USER_DATA)](#杠杆分层标准-user_data) + - [持仓ADL队列估算 (USER_DATA)](#持仓adl队列估算-user_data) + - [用户强平单历史 (USER_DATA)](#用户强平单历史-user_data) + - [用户手续费率 (USER_DATA)](#用户手续费率-user_data)- [Websocket 账户信息推送](#websocket-账户信息推送) + - [生成listenKey (USER_STREAM)](#生成listenkey-user_stream) + - [延长listenKey有效期 (USER_STREAM)](#延长listenkey有效期-user_stream) + - [关闭listenKey (USER_STREAM)](#关闭listenkey-user_stream) + - [listenKey 过期推送](#listenkey-过期推送) + - [追加保证金通知](#追加保证金通知) + - [Balance和Position更新推送](#balance和position更新推送) + - [订单/交易 更新推送](#订单交易-更新推送) + - [杠杆倍数等账户配置 更新推送](#杠杆倍数等账户配置-更新推送) + - [Event: TradePro](#event-tradepro) +- [错误代码](#错误代码) + - [10xx - 常规服务器或网络问题](#10xx---常规服务器或网络问题) + - [11xx - Request issues](#11xx---request-issues) + - [20xx - Processing Issues](#20xx---processing-issues) + - [40xx - Filters and other Issues](#40xx---filters-and-other-issues) + +# 基本信息 + + +## Rest 基本信息 + +* 接口可能需要用户的AGENT +* AGENT创建请[点击这里](https://www.asterdex-testnet.com/zh-CN/api-wallet) 并且切换到API管理上方的`专业API` +* 本篇列出REST接口的baseurl **https://fapi.asterdex-testnet.com** +* 所有接口的响应都是JSON格式 +* 响应中如有数组,数组元素以时间升序排列,越早的数据越提前。 +* 所有时间、时间戳均为UNIX时间,单位为毫秒 +* 所有数据类型采用JAVA的数据类型定义 + +### HTTP 返回代码 +* HTTP `4XX` 错误码用于指示错误的请求内容、行为、格式。 +* HTTP `403` 错误码表示违反WAF限制(Web应用程序防火墙)。 +* HTTP `429` 错误码表示警告访问频次超限,即将被封IP +* HTTP `418` 表示收到429后继续访问,于是被封了。 +* HTTP `5XX` 错误码用于指示Aster Finance服务侧的问题。 +* HTTP `503` 表示API服务端已经向业务核心提交了请求但未能获取响应,特别需要注意的是其不代表请求失败,而是未知。很可能已经得到了执行,也有可能执行失败,需要做进一步确认。 + + +### 接口错误代码 +* 每个接口都有可能抛出异常 + +> 异常响应格式如下: + +```javascript +{ + "code": -1121, + "msg": "Invalid symbol." +} +``` + +* 具体的错误码及其解释在[错误代码](#错误代码) + +### 接口的基本信息 +* `GET`方法的接口, 参数必须在`query string`中发送. +* `POST`, `PUT`, 和 `DELETE` 方法的接口, 在 `request body`中发送(content type `application/x-www-form-urlencoded`) +* 对参数的顺序不做要求。 + +## 访问限制 +* 在 `/fapi/v3/exchangeInfo`接口中`rateLimits`数组里包含有REST接口(不限于本篇的REST接口)的访问限制。包括带权重的访问频次限制、下单速率限制。本篇`枚举定义`章节有限制类型的进一步说明。 +* 违反上述任何一个访问限制都会收到HTTP 429,这是一个警告. + + + + +### IP 访问限制 +* 每个请求将包含一个`X-MBX-USED-WEIGHT-(intervalNum)(intervalLetter)`的头,其中包含当前IP所有请求的已使用权重。 +* 每个路由都有一个"权重",该权重确定每个接口计数的请求数。较重的接口和对多个交易对进行操作的接口将具有较重的"权重"。 +* 收到429时,您有责任作为API退回而不向其发送更多的请求。 +* **如果屡次违反速率限制和/或在收到429后未能退回,将导致API的IP被禁(http状态418)。** +* 频繁违反限制,封禁时间会逐渐延长 ,**对于重复违反者,将会被封从2分钟到3天**。 +* **访问限制是基于IP的,而不是AGENT** + + + + +### 下单频率限制 +* 每个下单请求回报将包含一个`X-MBX-ORDER-COUNT-(intervalNum)(intervalLetter)`的头,其中包含当前账户已用的下单限制数量。 +* 被拒绝或不成功的下单并不保证回报中包含以上头内容。 +* **下单频率限制是基于每个账户计数的。**> + +## 接口鉴权类型 +* 每个接口都有自己的鉴权类型,鉴权类型决定了访问时应当进行何种鉴权 +* 如果需要鉴权,应当在请求体中添加signer + +鉴权类型 | 描述 +------------ | ------------ +NONE | 不需要鉴权的接口 +TRADE | 需要有效的signer和签名 +USER_DATA | 需要有效的signer和签名 +USER_STREAM | 需要有效的signer和签名 +MARKET_DATA | 不需要鉴权的接口 + +## 鉴权签名体 +参数 | 描述 +------------ | ------------ +user | 主账户钱包地址 +signer | API钱包地址 +nonce | 当前时间戳,单位为微秒 +signature | 签名 + +## POST /fapi/v3/order 的示例 + + +#### 示例 : 以下参数为api注册信息,user,signer,privateKey仅供示范(privateKey为signer的私钥) + + +Key | Value | Desc +------------ | ------------ | ------------ +user | 0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e | 登陆钱包地址 +signer | 0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0 | [点击这里获取](https://www.asterdex-testnet.com/zh-CN/api-wallet) +privateKey | 0x4fd0a42218f3eae43a6ce26d22544e986139a01e5b34a62db53757ffca81bae1 | [点击这里获取](https://www.asterdex-testnet.com/zh-CN/api-wallet) + +#### 示例 : nonce参数为当前系统微秒值,超过系统时间,或者落后系统时间超过5s为非法请求 +```python +#python +nonce = math.trunc(time.time()*1000000) +print(nonce) +#1748310859508867 +``` +```java +//java +Instant now = Instant.now(); +long microsecond = now.getEpochSecond() * 1000000 + now.getNano() / 1000; +``` + +#### 示例 : 下单 (方法以python为例) + +```python +import time +import urllib +import threading + +import requests +from eth_account.messages import encode_structured_data +from eth_account import Account + +typed_data = { + "types": { + "EIP712Domain": [ + {"name": "name", "type": "string"}, + {"name": "version", "type": "string"}, + {"name": "chainId", "type": "uint256"}, + {"name": "verifyingContract", "type": "address"} + ], + "Message": [ + { "name": "msg", "type": "string" } + ] + }, + "primaryType": "Message", + "domain": { + "name": "AsterSignTransaction", + "version": "1", + "chainId": 714, + "verifyingContract": "0x0000000000000000000000000000000000000000" + }, + "message": { + "msg": "$msg" + } +} + +headers = { + 'Content-Type': 'application/x-www-form-urlencoded', + 'User-Agent': 'PythonApp/1.0' +} +host = 'https://fapi.asterdex-testnet.com' + +# config your user and agent info here +user = '*' +signer = '*' +private_key = '*' + +place_order = {"url":"/fapi/v3/order","method":"POST","params":{"symbol": "ASTERUSDT", "type": "LIMIT", "side": "BUY", + "timeInForce": "GTC", "quantity": "20", "price": "0.5"}} +batch_orders = {"url":"/fapi/v3/batchOrders","method":"POST","params":{ + "batchOrders":"[{'symbol':'ASTERUSDT','type':'LIMIT','side':'BUY','timeInForce':'GTC','quantity':'20','price':'0.5'},{'symbol':'ASTERUSDT','type':'LIMIT','side':'BUY','timeInForce':'GTC','quantity':'20','price':'0.5'}]" }} + +batch_orders_delete = {"url": "/fapi/v3/batchOrders", "method": "DELETE", + "params": {"symbol": "BTCUSDT", "origClientOrderIdList": '["123aaaa","111ccc","321313"]'}} + +_last_ms = 0 +_i = 0 +_nonce_lock = threading.Lock() + +def get_nonce(): + global _last_ms, _i + with _nonce_lock: + now_ms = int(time.time()) + + if now_ms == _last_ms: + _i += 1 + else: + _last_ms = now_ms + _i = 0 + + return now_ms * 1_000_000 + _i + +def send_by_url(api) : + my_dict = api['params'] + url = host + api['url'] + method = api['method'] + + my_dict['nonce'] = str(get_nonce()) + my_dict['user'] = user + my_dict['signer'] = signer + + param = urllib.parse.urlencode(my_dict) + + print(param) + typed_data['message']['msg'] = param + message = encode_structured_data(typed_data) + signed = Account.sign_message(message, private_key=private_key) + + url = url + '?' + param + '&signature=' + signed.signature.hex() + print(url) + + if method == 'DELETE': + res = requests.delete(url, headers=headers) + print(res.text) + if method == 'POST': + res = requests.post(url, headers=headers) + print(res.text) + +def send_by_body(api) : + my_dict = api['params'] + url = host +api['url'] + method = api['method'] + + my_dict['nonce'] = str(get_nonce()) + my_dict['user'] = user + my_dict['signer'] = signer + + param = urllib.parse.urlencode(my_dict) + typed_data['message']['msg'] = param + message = encode_structured_data(typed_data) + + signed = Account.sign_message(message, private_key=private_key) + print(signed.signature.hex()) + + my_dict['signature'] = signed.signature.hex() + + print(my_dict) + if method == 'DELETE': + res = requests.delete(url, data=my_dict, headers=headers) + print(res.text) + if method == 'POST': + res = requests.post(url, data=my_dict, headers=headers) + print(res.text) + +if __name__ == '__main__': + send_by_url(place_order) + # send_by_body(place_order) + # send_by_body(batch_orders) + # send_by_url(batch_orders_delete) + # send_by_body(batch_orders_delete) + +``` + +## 公开API参数 +### 术语解释 +* `base asset` 指一个交易对的交易对象,即写在靠前部分的资产名 +* `quote asset` 指一个交易对的定价资产,即写在靠后部分资产名 + + +### 枚举定义 + +**交易对类型:** + +* FUTURE 期货 + +**合约类型 (contractType):** + +* PERPETUAL 永续合约 + + +**合约状态 (contractStatus, status):** + +* PENDING_TRADING 待上市 +* TRADING 交易中 +* PRE_SETTLE 预结算 +* SETTLING 结算中 +* CLOSE 已下架 + + +**订单状态 (status):** + +* NEW 新建订单 +* PARTIALLY_FILLED 部分成交 +* FILLED 全部成交 +* CANCELED 已撤销 +* REJECTED 订单被拒绝 +* EXPIRED 订单过期(根据timeInForce参数规则) + +**订单种类 (orderTypes, type):** + +* LIMIT 限价单 +* MARKET 市价单 +* STOP 止损限价单 +* STOP_MARKET 止损市价单 +* TAKE_PROFIT 止盈限价单 +* TAKE_PROFIT_MARKET 止盈市价单 +* TRAILING_STOP_MARKET 跟踪止损单 + +**订单方向 (side):** + +* BUY 买入 +* SELL 卖出 + +**持仓方向:** + +* BOTH 单一持仓方向 +* LONG 多头(双向持仓下) +* SHORT 空头(双向持仓下) + +**有效方式 (timeInForce):** + +* GTC - Good Till Cancel 成交为止 +* IOC - Immediate or Cancel 无法立即成交(吃单)的部分就撤销 +* FOK - Fill or Kill 无法全部立即成交就撤销 +* GTX - Good Till Crossing 无法成为挂单方就撤销 +* HIDDEN - HIDDEN 该类型订单在订单薄里不可见 + +**条件价格触发类型 (workingType)** + +* MARK_PRICE +* CONTRACT_PRICE + +**响应类型 (newOrderRespType)** + +* ACK +* RESULT + +**K线间隔:** + +m -> 分钟; h -> 小时; d -> 天; w -> 周; M -> 月 + +* 1m +* 3m +* 5m +* 15m +* 30m +* 1h +* 2h +* 4h +* 6h +* 8h +* 12h +* 1d +* 3d +* 1w +* 1M + +**限制种类 (rateLimitType)** + +> REQUEST_WEIGHT + +```javascript + { + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 2400 + } +``` + +> ORDERS + +```javascript + { + "rateLimitType": "ORDERS", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200 + } +``` + +* REQUESTS_WEIGHT 单位时间请求权重之和上限 + +* ORDERS 单位时间下单(撤单)次数上限 + + +**限制间隔** + +* MINUTE + + + +## 过滤器 +过滤器,即Filter,定义了一系列交易规则。 +共有两类,分别是针对交易对的过滤器`symbol filters`,和针对整个交易所的过滤器`exchange filters`(暂不支持) + +### 交易对过滤器 +#### PRICE_FILTER 价格过滤器 + +> **/exchangeInfo 响应中的格式:** + +```javascript + { + "filterType": "PRICE_FILTER", + "minPrice": "0.00000100", + "maxPrice": "100000.00000000", + "tickSize": "0.00000100" + } +``` + +价格过滤器用于检测order订单中price参数的合法性 + +* `minPrice` 定义了 `price`/`stopPrice` 允许的最小值 +* `maxPrice` 定义了 `price`/`stopPrice` 允许的最大值。 +* `tickSize` 定义了 `price`/`stopPrice` 的步进间隔,即price必须等于minPrice+(tickSize的整数倍) +以上每一项均可为0,为0时代表这一项不再做限制。 + +逻辑伪代码如下: + +* `price` >= `minPrice` +* `price` <= `maxPrice` +* (`price`-`minPrice`) % `tickSize` == 0 + + + +#### LOT_SIZE 订单尺寸 + +> */exchangeInfo 响应中的格式:** + +```javascript + { + "filterType": "LOT_SIZE", + "minQty": "0.00100000", + "maxQty": "100000.00000000", + "stepSize": "0.00100000" + } +``` + +lots是拍卖术语,这个过滤器对订单中的`quantity`也就是数量参数进行合法性检查。包含三个部分: + +* `minQty` 表示 `quantity` 允许的最小值. +* `maxQty` 表示 `quantity` 允许的最大值 +* `stepSize` 表示 `quantity`允许的步进值。 + +逻辑伪代码如下: + +* `quantity` >= `minQty` +* `quantity` <= `maxQty` +* (`quantity`-`minQty`) % `stepSize` == 0 + + +#### MARKET_LOT_SIZE 市价订单尺寸 +参考LOT_SIZE,区别仅在于对市价单还是限价单生效 + +#### MAX_NUM_ORDERS 最多订单数 + + +> **/exchangeInfo 响应中的格式:** + +```javascript + { + "filterType": "MAX_NUM_ORDERS", + "limit": 200 + } +``` + +定义了某个交易对最多允许的挂单数量(不包括已关闭的订单) + +普通订单与条件订单均计算在内 + + +#### MAX_NUM_ALGO_ORDERS 最多条件订单数 + +> **/exchangeInfo format:** + +```javascript + { + "filterType": "MAX_NUM_ALGO_ORDERS", + "limit": 100 + } +``` + +定义了某个交易对最多允许的条件订单的挂单数量(不包括已关闭的订单)。 + +条件订单目前包括`STOP`, `STOP_MARKET`, `TAKE_PROFIT`, `TAKE_PROFIT_MARKET`, 和 `TRAILING_STOP_MARKET` + + +#### PERCENT_PRICE 价格振幅过滤器 + +> **/exchangeInfo 响应中的格式:** + +```javascript + { + "filterType": "PERCENT_PRICE", + "multiplierUp": "1.1500", + "multiplierDown": "0.8500", + "multiplierDecimal": 4 + } +``` + +`PERCENT_PRICE` 定义了基于标记价格计算的挂单价格的可接受区间. + +挂单价格必须同时满足以下条件: + +* 买单: `price` <= `markPrice` * `multiplierUp` +* 卖单: `price` >= `markPrice` * `multiplierDown` + + +#### MIN_NOTIONAL 最小名义价值 + +> **/exchangeInfo 响应中的格式:** + +```javascript + { + "filterType": "MIN_NOTIONAL", + "notioanl": "1" + } +``` + +MIN_NOTIONAL过滤器定义了交易对订单所允许的最小名义价值(成交额)。 +订单的名义价值是`价格`*`数量`。 +由于`MARKET`订单没有价格,因此会使用 mark price 计算。 + + + + + + +--- + + +# 行情接口 + +## Noop + +> **Response:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +``POST /fapi/v3/noop`` + +通过此请求,可以高效取消已发送但仍在队列中且尚未完成链上操作的交易(Nonce需与该请求一致,不保证成功) + +#### 示例 : Noop (方法以python为例) + +```python +import time +import urllib + +import aiohttp +from eth_account.messages import encode_structured_data +from eth_account import Account +import asyncio + +typed_data = { + "types": { + "EIP712Domain": [ + {"name": "name", "type": "string"}, + {"name": "version", "type": "string"}, + {"name": "chainId", "type": "uint256"}, + {"name": "verifyingContract", "type": "address"} + ], + "Message": [ + { "name": "msg", "type": "string" } + ] + }, + "primaryType": "Message", + "domain": { + "name": "AsterSignTransaction", + "version": "1", + "chainId": 714, + "verifyingContract": "0x0000000000000000000000000000000000000000" + }, + "message": { + "msg": "$msg" + } +} + +headers = { + 'Content-Type': 'application/x-www-form-urlencoded', + 'User-Agent': 'PythonApp/1.0' +} +host = 'https://fapi.asterdex-testnet.com' + +# config your user and agent info here +user = '*' +signer = '*' +private_key = "**" + +noop = {'url':'/fapi/v3/noop','method':'POST','params':{}} +place_order = {"url":"/fapi/v3/order","method":"POST","params":{"symbol": "ASTERUSDT", "type": "LIMIT", "side": "BUY", + "timeInForce": "GTC", "quantity": "20", "price": "0.5"}} +_last_ms = 0 +_i = 0 + +def get_nonce(): + global _last_ms, _i + now_ms = int(time.time()) + + if now_ms == _last_ms: + _i += 1 + else: + _last_ms = now_ms + _i = 0 + + return now_ms * 1_000_000 + _i + +async def send_by_url(api,nonce) : + my_dict = api['params'] + url = host + api['url'] + + my_dict['nonce'] = nonce + my_dict['user'] = user + my_dict['signer'] = signer + param = urllib.parse.urlencode(my_dict) + + typed_data['message']['msg'] = param + message = encode_structured_data(typed_data) + signed = Account.sign_message(message, private_key=private_key) + + url = url + '?' + param + '&signature=' + signed.signature.hex() + print(url) + async with aiohttp.ClientSession() as session: + async with session.post(url, headers=headers) as resp: + text = await resp.text() + return {"status_code": resp.status, "text": text,'nonce': nonce} + +async def main(): + _place_order_nonce = get_nonce() + task_place_order =asyncio.create_task( send_by_url(place_order, _place_order_nonce)) + task_noop= asyncio.create_task( send_by_url(noop, _place_order_nonce)) + place_order_result, noop_result = await asyncio.gather(task_place_order, task_noop) + print(f"place_order_result : {place_order_result['text']},nonce: {place_order_result['nonce']}") + print(f"noop_result : {noop_result['text']},nonce: {noop_result['nonce']}") + +if __name__ == '__main__': + asyncio.run(main()) + +# This operation may not succeed every time. Please retry. +# place_order_result : {"code":-4225,"msg":"Nonce Expired"},nonce: 1773321233000000 +# noop_result : {"code": 200,"msg": "success"},nonce: 1773321233000000 + +``` + +**Weight:** +1 + +## 测试服务器连通性 PING +`` +GET /fapi/v3/ping +`` + +> **响应:** + +```javascript +{} +``` + +测试能否联通 + +**权重:** +1 + +**参数:** +NONE + + + +## 获取服务器时间 + +> **响应:** + +```javascript +{ + "serverTime": 1499827319559 // 当前的系统时间 +} +``` + +`` +GET /fapi/v3/time +`` + +获取服务器时间 + +**权重:** +1 + +**参数:** +NONE + + +## 获取交易规则和交易对 + +> **响应:** + +```javascript +{ + "exchangeFilters": [], + "rateLimits": [ // API访问的限制 + { + "interval": "MINUTE", // 按照分钟计算 + "intervalNum": 1, // 按照1分钟计算 + "limit": 2400, // 上限次数 + "rateLimitType": "REQUEST_WEIGHT" // 按照访问权重来计算 + }, + { + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200, + "rateLimitType": "ORDERS" // 按照订单数量来计算 + } + ], + "serverTime": 1565613908500, // 请忽略。如果需要获取当前系统时间,请查询接口 “GET /fapi/v3/time” + "assets": [ // 资产信息 + { + "asset": "BUSD", + "marginAvailable": true, // 是否可用作保证金 + "autoAssetExchange": 0 // 保证金资产自动兑换阈值 + }, + { + "asset": "USDT", + "marginAvailable": true, // 是否可用作保证金 + "autoAssetExchange": 0 // 保证金资产自动兑换阈值 + }, + { + "asset": "BNB", + "marginAvailable": false, // 是否可用作保证金 + "autoAssetExchange": null // 保证金资产自动兑换阈值 + } + ], + "symbols": [ // 交易对信息 + { + "symbol": "BLZUSDT", // 交易对 + "pair": "BLZUSDT", // 标的交易对 + "contractType": "PERPETUAL", // 合约类型 + "deliveryDate": 4133404800000, // 交割日期 + "onboardDate": 1598252400000, // 上线日期 + "status": "TRADING", // 交易对状态 + "maintMarginPercent": "2.5000", // 请忽略 + "requiredMarginPercent": "5.0000", // 请忽略 + "baseAsset": "BLZ", // 标的资产 + "quoteAsset": "USDT", // 报价资产 + "marginAsset": "USDT", // 保证金资产 + "pricePrecision": 5, // 价格小数点位数(仅作为系统精度使用,注意同tickSize 区分) + "quantityPrecision": 0, // 数量小数点位数(仅作为系统精度使用,注意同stepSize 区分) + "baseAssetPrecision": 8, // 标的资产精度 + "quotePrecision": 8, // 报价资产精度 + "underlyingType": "COIN", + "underlyingSubType": ["STORAGE"], + "settlePlan": 0, + "triggerProtect": "0.15", // 开启"priceProtect"的条件订单的触发阈值 + "filters": [ + { + "filterType": "PRICE_FILTER", // 价格限制 + "maxPrice": "300", // 价格上限, 最大价格 + "minPrice": "0.0001", // 价格下限, 最小价格 + "tickSize": "0.0001" // 订单最小价格间隔 + }, + { + "filterType": "LOT_SIZE", // 数量限制 + "maxQty": "10000000", // 数量上限, 最大数量 + "minQty": "1", // 数量下限, 最小数量 + "stepSize": "1" // 订单最小数量间隔 + }, + { + "filterType": "MARKET_LOT_SIZE", // 市价订单数量限制 + "maxQty": "590119", // 数量上限, 最大数量 + "minQty": "1", // 数量下限, 最小数量 + "stepSize": "1" // 允许的步进值 + }, + { + "filterType": "MAX_NUM_ORDERS", // 最多订单数限制 + "limit": 200 + }, + { + "filterType": "MAX_NUM_ALGO_ORDERS", // 最多条件订单数限制 + "limit": 100 + }, + { + "filterType": "MIN_NOTIONAL", // 最小名义价值 + "notional": "1", + }, + { + "filterType": "PERCENT_PRICE", // 价格比限制 + "multiplierUp": "1.1500", // 价格上限百分比 + "multiplierDown": "0.8500", // 价格下限百分比 + "multiplierDecimal": 4 + } + ], + "OrderType": [ // 订单类型 + "LIMIT", // 限价单 + "MARKET", // 市价单 + "STOP", // 止损单 + "STOP_MARKET", // 止损市价单 + "TAKE_PROFIT", // 止盈单 + "TAKE_PROFIT_MARKET", // 止盈暑市价单 + "TRAILING_STOP_MARKET" // 跟踪止损市价单 + ], + "timeInForce": [ // 有效方式 + "GTC", // 成交为止, 一直有效 + "IOC", // 无法立即成交(吃单)的部分就撤销 + "FOK", // 无法全部立即成交就撤销 + "GTX", // 无法成为挂单方就撤销 + "HIDDEN" + ], + "liquidationFee": "0.010000", // 强平费率 + "marketTakeBound": "0.30", // 市价吃单(相对于标记价格)允许可造成的最大价格偏离比例 + } + ], + "timezone": "UTC" // 服务器所用的时间区域 +} + +``` + +`` +GET /fapi/v3/exchangeInfo +`` + +获取交易规则和交易对 + +**权重:** +1 + +**参数:** +NONE + + + +## 深度信息 + +> **响应:** + +```javascript +{ + "lastUpdateId": 1027024, + "E": 1589436922972, // 消息时间 + "T": 1589436922959, // 撮合引擎时间 + "bids": [ // 买单 + [ + "4.00000000", // 价格 + "431.00000000" // 数量 + ] + ], + "asks": [ // 卖单 + [ + "4.00000200", // 价格 + "12.00000000" // 数量 + ] + ] +} +``` + +`` +GET /fapi/v3/depth +`` + +**权重:** + +limit | 权重 +------------ | ------------ +5, 10, 20, 50 | 2 +100 | 5 +500 | 10 +1000 | 20 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +------ | ------ | -------- | ----------------------------------------------------------- +symbol | STRING | YES | 交易对 +limit | INT | NO | 默认 500; 可选值:[5, 10, 20, 50, 100, 500, 1000] + + + +## 近期成交 + +> **响应:** + +```javascript +[ + { + "id": 28457, // 成交ID + "price": "4.00000100", // 成交价格 + "qty": "12.00000000", // 成交量 + "quoteQty": "48.00", // 成交额 + "time": 1499865549590, // 时间 + "isBuyerMaker": true // 买方是否为挂单方 + } +] +``` + +`` +GET /fapi/v3/trades +`` + +获取近期订单簿成交 + +**权重:** +1 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +------ | ------ | -------- | ---------------------- +symbol | STRING | YES | 交易对 +limit | INT | NO | 默认:500,最大1000 + +* 仅返回订单簿成交,即不会返回保险基金和自动减仓(ADL)成交 + +## 查询历史成交(MARKET_DATA) + +> **响应:** + +```javascript +[ + { + "id": 28457, // 成交ID + "price": "4.00000100", // 成交价格 + "qty": "12.00000000", // 成交量 + "quoteQty": "48.00", // 成交额 + "time": 1499865549590, // 时间 + "isBuyerMaker": true // 买方是否为挂单方 + } +] +``` + +`` +GET /fapi/v3/historicalTrades +`` + +查询订单簿历史成交 + +**权重:** +20 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +------ | ------ | -------- | ---------------------------------------------- +symbol | STRING | YES | 交易对 +limit | INT | NO | 默认值:500 最大值:1000. +fromId | LONG | NO | 从哪一条成交id开始返回. 缺省返回最近的成交记录 + +* 仅返回订单簿成交,即不会返回保险基金和自动减仓(ADL)成交 + +## 近期成交(归集) + +> **响应:** + +```javascript +[ + { + "a": 26129, // 归集成交ID + "p": "0.01633102", // 成交价 + "q": "4.70443515", // 成交量 + "f": 27781, // 被归集的首个成交ID + "l": 27781, // 被归集的末个成交ID + "T": 1498793709153, // 成交时间 + "m": true, // 是否为主动卖出单 + } +] +``` + +`` +GET /fapi/v3/aggTrades +`` + +归集交易与逐笔交易的区别在于,同一价格、同一方向、同一时间(按秒计算)的订单簿trade会被聚合为一条 + +**权重:** +20 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +--------- | ------ | -------- | ---------------------------------- +symbol | STRING | YES | 交易对 +fromId | LONG | NO | 从包含fromID的成交开始返回结果 +startTime | LONG | NO | 从该时刻之后的成交记录开始返回结果 +endTime | LONG | NO | 返回该时刻为止的成交记录 +limit | INT | NO | 默认 500; 最大 1000. + +* 如果同时发送`startTime`和`endTime`,间隔必须小于一小时 +* 如果没有发送任何筛选参数(`fromId`, `startTime`, `endTime`),默认返回最近的成交记录 +* 保险基金和自动减仓(ADL)成交不属于订单簿成交,故不会被归并聚合 + + +## K线数据 + +> **响应:** + +```javascript +[ + [ + 1499040000000, // 开盘时间 + "0.01634790", // 开盘价 + "0.80000000", // 最高价 + "0.01575800", // 最低价 + "0.01577100", // 收盘价(当前K线未结束的即为最新价) + "148976.11427815", // 成交量 + 1499644799999, // 收盘时间 + "2434.19055334", // 成交额 + 308, // 成交笔数 + "1756.87402397", // 主动买入成交量 + "28.46694368", // 主动买入成交额 + "17928899.62484339" // 请忽略该参数 + ] +] +``` + +`` +GET /fapi/v3/klines +`` + +每根K线的开盘时间可视为唯一ID + +**权重:** 取决于请求中的LIMIT参数 + +LIMIT参数 | 权重 +---|--- +[1,100) | 1 +[100, 500) | 2 +[500, 1000] | 5 +> 1000 | 10 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +--------- | ------ | -------- | ---------------------- +symbol | STRING | YES | 交易对 +interval | ENUM | YES | 时间间隔 +startTime | LONG | NO | 起始时间 +endTime | LONG | NO | 结束时间 +limit | INT | NO | 默认值:500 最大值:1500. + +* 缺省返回最近的数据 + + + +## 价格指数K线数据 + +> **响应:** + +```javascript +[ + [ + 1591256400000, // 开盘时间 + "9653.69440000", // 开盘价 + "9653.69640000", // 最高价 + "9651.38600000", // 最低价 + "9651.55200000", // 收盘价(当前K线未结束的即为最新价) + "0 ", // 请忽略 + 1591256459999, // 收盘时间 + "0", // 请忽略 + 60, // 构成记录数 + "0", // 请忽略 + "0", // 请忽略 + "0" // 请忽略 + ] +] +``` + +`` +GET /fapi/v3/indexPriceKlines +`` + +每根K线的开盘时间可视为唯一ID + +**权重:** 取决于请求中的LIMIT参数 + +LIMIT参数 | 权重 +---|--- +[1,100) | 1 +[100, 500) | 2 +[500, 1000] | 5 +> 1000 | 10 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +--------- | ------ | -------- | ---------------------- +pair | STRING | YES | 标的交易对 +interval | ENUM | YES | 时间间隔 +startTime | LONG | NO | 起始时间 +endTime | LONG | NO | 结束时间 +limit | INT | NO | 默认值:500 最大值:1500 + +* 缺省返回最近的数据 + + +## 标记价格K线数据 + +> **响应:** + +```javascript +[ + [ + 1591256400000, // 开盘时间 + "9653.69440000", // 开盘价 + "9653.69640000", // 最高价 + "9651.38600000", // 最低价 + "9651.55200000", // 收盘价(当前K线未结束的即为最新价) + "0 ", // 请忽略 + 1591256459999, // 收盘时间 + "0", // 请忽略 + 60, // 构成记录数 + "0", // 请忽略 + "0", // 请忽略 + "0" // 请忽略 + ] +] +``` + +`` +GET /fapi/v3/markPriceKlines +`` +每根K线的开盘时间可视为唯一ID + +**权重:** 取决于请求中的LIMIT参数 + +LIMIT参数 | 权重 +---|--- +[1,100) | 1 +[100, 500) | 2 +[500, 1000] | 5 +> 1000 | 10 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +--------- | ------ | -------- | ---------------------- +symbol | STRING | YES | 交易对 +interval | ENUM | YES | 时间间隔 +startTime | LONG | NO | 起始时间 +endTime | LONG | NO | 结束时间 +limit | INT | NO | 默认值:500 最大值:1500 + +* 缺省返回最近的数据 + + +## 最新标记价格和资金费率 + +> **响应:** + +```javascript +{ + "symbol": "BTCUSDT", // 交易对 + "markPrice": "11793.63104562", // 标记价格 + "indexPrice": "11781.80495970", // 指数价格 + "estimatedSettlePrice": "11781.16138815", // 预估结算价,仅在交割开始前最后一小时有意义 + "lastFundingRate": "0.00038246", // 最近更新的资金费率 + "nextFundingTime": 1597392000000, // 下次资金费时间 + "interestRate": "0.00010000", // 标的资产基础利率 + "time": 1597370495002 // 更新时间 +} +``` + +> **当不指定symbol时相应** + +```javascript +[ + { + "symbol": "BTCUSDT", // 交易对 + "markPrice": "11793.63104562", // 标记价格 + "indexPrice": "11781.80495970", // 指数价格 + "estimatedSettlePrice": "11781.16138815", // 预估结算价,仅在交割开始前最后一小时有意义 + "lastFundingRate": "0.00038246", // 最近更新的资金费率 + "nextFundingTime": 1597392000000, // 下次资金费时间 + "interestRate": "0.00010000", // 标的资产基础利率 + "time": 1597370495002 // 更新时间 + } +] +``` + + +`` +GET /fapi/v3/premiumIndex +`` + +采集各大交易所数据加权平均 + +**权重:** +1 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +------ | ------ | -------- | ------ +symbol | STRING | NO | 交易对 + + +## 查询资金费率历史 + +> **响应:** + +```javascript +[ + { + "symbol": "BTCUSDT", // 交易对 + "fundingRate": "-0.03750000", // 资金费率 + "fundingTime": 1570608000000, // 资金费时间 + }, + { + "symbol": "BTCUSDT", + "fundingRate": "0.00010000", + "fundingTime": 1570636800000, + } +] +``` + +`` +GET /fapi/v3/fundingRate +`` + +**权重:** +1 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +--------- | ------ | -------- | ----------------------------------------------------- +symbol | STRING | NO | 交易对 +startTime | LONG | NO | 起始时间 +endTime | LONG | NO | 结束时间 +limit | INT | NO | 默认值:100 最大值:1000 + +* 如果 `startTime` 和 `endTime` 都未发送, 返回最近 `limit` 条数据. +* 如果 `startTime` 和 `endTime` 之间的数据量大于 `limit`, 返回 `startTime` + `limit`情况下的数据。 + + +## 查询资金费率配置 + +> **响应:** + +```javascript +[ + { + "symbol": "INJUSDT", // 交易对 + "interestRate": "0.00010000", // 利率 + "time": 1756197479000, // 更新时间 + "fundingIntervalHours": 8, // 资金费间隔小时数 + "fundingFeeCap": 0.03, // 资金费上限 + "fundingFeeFloor": -0.03 // 资金费下限 + }, + { + "symbol": "ZORAUSDT", + "interestRate": "0.00005000", + "time": 1756197479000, + "fundingIntervalHours": 4, + "fundingFeeCap": 0.02, + "fundingFeeFloor": -0.02 + } +] +``` + +`` +GET /fapi/v3/fundingInfo +`` + +**权重:** +1 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +--------- | ------ | -------- | ----------------------------------------------------- +symbol | STRING | NO | 交易对 + + +## 24hr价格变动情况 + +> **响应:** + +```javascript +{ + "symbol": "BTCUSDT", + "priceChange": "-94.99999800", //24小时价格变动 + "priceChangePercent": "-95.960", //24小时价格变动百分比 + "weightedAvgPrice": "0.29628482", //加权平均价 + "lastPrice": "4.00000200", //最近一次成交价 + "lastQty": "200.00000000", //最近一次成交额 + "openPrice": "99.00000000", //24小时内第一次成交的价格 + "highPrice": "100.00000000", //24小时最高价 + "lowPrice": "0.10000000", //24小时最低价 + "volume": "8913.30000000", //24小时成交量 + "quoteVolume": "15.30000000", //24小时成交额 + "openTime": 1499783499040, //24小时内,第一笔交易的发生时间 + "closeTime": 1499869899040, //24小时内,最后一笔交易的发生时间 + "firstId": 28385, // 首笔成交id + "lastId": 28460, // 末笔成交id + "count": 76 // 成交笔数 +} +``` + +> 或(当不发送交易对信息) + +```javascript +[ + { + "symbol": "BTCUSDT", + "priceChange": "-94.99999800", //24小时价格变动 + "priceChangePercent": "-95.960", //24小时价格变动百分比 + "weightedAvgPrice": "0.29628482", //加权平均价 + "lastPrice": "4.00000200", //最近一次成交价 + "lastQty": "200.00000000", //最近一次成交额 + "openPrice": "99.00000000", //24小时内第一次成交的价格 + "highPrice": "100.00000000", //24小时最高价 + "lowPrice": "0.10000000", //24小时最低价 + "volume": "8913.30000000", //24小时成交量 + "quoteVolume": "15.30000000", //24小时成交额 + "openTime": 1499783499040, //24小时内,第一笔交易的发生时间 + "closeTime": 1499869899040, //24小时内,最后一笔交易的发生时间 + "firstId": 28385, // 首笔成交id + "lastId": 28460, // 末笔成交id + "count": 76 // 成交笔数 + } +] +``` + +`` +GET /fapi/v3/ticker/24hr +`` + +请注意,不携带symbol参数会返回全部交易对数据,不仅数据庞大,而且权重极高 + +**权重:** +* 带symbol为`1` +* 不带为`40` + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +------ | ------ | -------- | ------ +symbol | STRING | NO | 交易对 + +* 不发送交易对参数,则会返回所有交易对信息 + + +## 最新价格 + +> **响应:** + +```javascript +{ + "symbol": "LTCBTC", // 交易对 + "price": "4.00000200", // 价格 + "time": 1589437530011 // 撮合引擎时间 +} +``` + +> 或(当不发送symbol) + +```javascript +[ + { + "symbol": "BTCUSDT", // 交易对 + "price": "6000.01", // 价格 + "time": 1589437530011 // 撮合引擎时间 + } +] +``` + +`` +GET /fapi/v3/ticker/price +`` + +返回最近价格 + +**权重:** +* 单交易对`1` +* 无交易对`2` + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +------ | ------ | -------- | ------ +symbol | STRING | NO | 交易对 + +* 不发送交易对参数,则会返回所有交易对信息 + + +## 当前最优挂单 + +> **响应:** + +```javascript +{ + "symbol": "BTCUSDT", // 交易对 + "bidPrice": "4.00000000", //最优买单价 + "bidQty": "431.00000000", //挂单量 + "askPrice": "4.00000200", //最优卖单价 + "askQty": "9.00000000", //挂单量 + "time": 1589437530011 // 撮合引擎时间 +} +``` +> 或(当不发送symbol) + +```javascript +[ + { + "symbol": "BTCUSDT", // 交易对 + "bidPrice": "4.00000000", //最优买单价 + "bidQty": "431.00000000", //挂单量 + "askPrice": "4.00000200", //最优卖单价 + "askQty": "9.00000000", //挂单量 + "time": 1589437530011 // 撮合引擎时间 + } +] +``` + +`` +GET /fapi/v3/ticker/bookTicker +`` + +返回当前最优的挂单(最高买单,最低卖单) + +**权重:** +* 单交易对`1` +* 无交易对`2` + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +------ | ------ | -------- | ------ +symbol | STRING | NO | 交易对 + +* 不发送交易对参数,则会返回所有交易对信息 + + + +# Websocket 行情推送 + +* 本篇所列出的所有wss接口baseurl: **wss://fstream.asterdex-testnet.com** +* 订阅单一stream格式为 **/ws/\** +* 组合streams的URL格式为 **/stream?streams=\/\/\** +* 订阅组合streams时,事件payload会以这样的格式封装 **{"stream":"\","data":\}** +* stream名称中所有交易对均为**小写** +* 每个链接有效期不超过24小时,请妥善处理断线重连。 +* 服务端每5分钟会发送ping帧,客户端应当在15分钟内回复pong帧,否则服务端会主动断开链接。允许客户端发送不成对的pong帧(即客户端可以以高于15分钟每次的频率发送pong帧保持链接)。 +* Websocket服务器每秒最多接受10个订阅消息。 +* 如果用户发送的消息超过限制,连接会被断开连接。反复被断开连接的IP有可能被服务器屏蔽。 +* 单个连接最多可以订阅 **200** 个Streams。 + + + + +## 实时订阅/取消数据流 + +* 以下数据可以通过websocket发送以实现订阅或取消订阅数据流。示例如下。 +* 响应内容中的`id`是无符号整数,作为往来信息的唯一标识。 + +### 订阅一个信息流 + +> **响应** + + ```javascript + { + "result": null, + "id": 1 + } + ``` + +* **请求** + + { + "method": "SUBSCRIBE", + "params": + [ + "btcusdt@aggTrade", + "btcusdt@depth" + ], + "id": 1 + } + + + +### 取消订阅一个信息流 + +> **响应** + + ```javascript + { + "result": null, + "id": 312 + } + ``` + +* **请求** + + { + "method": "UNSUBSCRIBE", + "params": + [ + "btcusdt@depth" + ], + "id": 312 + } + + + +### 已订阅信息流 + +> **响应** + + ```javascript + { + "result": [ + "btcusdt@aggTrade" + ], + "id": 3 + } + ``` + + +* **请求** + + { + "method": "LIST_SUBSCRIPTIONS", + "id": 3 + } + + + +### 设定属性 +当前,唯一可以设置的属性是设置是否启用`combined`("组合")信息流。 +当使用`/ws/`("原始信息流")进行连接时,combined属性设置为`false`,而使用 `/stream/`进行连接时则将属性设置为`true`。 + + +> **响应** + + ```javascript + { + "result": null + "id": 5 + } + ``` + +* **请求** + + { + "method": "SET_PROPERTY", + "params": + [ + "combined", + true + ], + "id": 5 + } + + + + +### 检索属性 + +> **响应** + + ```javascript + { + "result": true, // Indicates that combined is set to true. + "id": 2 + } + ``` + +* **请求** + + { + "method": "GET_PROPERTY", + "params": + [ + "combined" + ], + "id": 2 + } + + + + +### 错误信息 + +错误信息 | 描述 +---|--- +{"code": 0, "msg": "Unknown property"} | `SET_PROPERTY` 或 `GET_PROPERTY`中应用的参数无效 +{"code": 1, "msg": "Invalid value type: expected Boolean"} | 仅接受`true`或`false` +{"code": 2, "msg": "Invalid request: property name must be a string"}| 提供的属性名无效 +{"code": 2, "msg": "Invalid request: request ID must be an unsigned integer"}| 参数`id`未提供或`id`值是无效类型 +{"code": 2, "msg": "Invalid request: unknown variant %s, expected one of `SUBSCRIBE`, `UNSUBSCRIBE`, `LIST_SUBSCRIPTIONS`, `SET_PROPERTY`, `GET_PROPERTY` at line 1 column 28"} | 错字提醒,或提供的值不是预期类型 +{"code": 2, "msg": "Invalid request: too many parameters"}| 数据中提供了不必要参数 +{"code": 2, "msg": "Invalid request: property name must be a string"} | 未提供属性名 +{"code": 2, "msg": "Invalid request: missing field `method` at line 1 column 73"} | 数据未提供`method` +{"code":3,"msg":"Invalid JSON: expected value at line %s column %s"} | JSON 语法有误. + + + + +## 最新合约价格 +aggTrade中的价格'p'或ticker/miniTicker中的价格'c'均可以作为最新成交价。 + +## 归集交易 + +> **Payload:** + +```javascript +{ + "e": "aggTrade", // 事件类型 + "E": 123456789, // 事件时间 + "s": "BNBUSDT", // 交易对 + "a": 5933014, // 归集成交 ID + "p": "0.001", // 成交价格 + "q": "100", // 成交量 + "f": 100, // 被归集的首个交易ID + "l": 105, // 被归集的末次交易ID + "T": 123456785, // 成交时间 + "m": true // 买方是否是做市方。如true,则此次成交是一个主动卖出单,否则是一个主动买入单。 +} +``` + +同一价格、同一方向、同一时间(100ms计算)的trade会被聚合为一条. + +**Stream Name:** +``@aggTrade`` + +**Update Speed:** 100ms + + + + + +## 最新标记价格 + +> **Payload:** + +```javascript + { + "e": "markPriceUpdate", // 事件类型 + "E": 1562305380000, // 事件时间 + "s": "BTCUSDT", // 交易对 + "p": "11794.15000000", // 标记价格 + "i": "11784.62659091", // 现货指数价格 + "P": "11784.25641265", // 预估结算价,仅在结算前最后一小时有参考价值 + "r": "0.00038167", // 资金费率 + "T": 1562306400000 // 下次资金时间 + } +``` + + +**Stream Name:** +``@markPrice`` 或 ``@markPrice@1s`` + +**Update Speed:** 3000ms 或 1000ms + + + + + + +## 全市场最新标记价格 + +> **Payload:** + +```javascript +[ + { + "e": "markPriceUpdate", // 事件类型 + "E": 1562305380000, // 事件时间 + "s": "BTCUSDT", // 交易对 + "p": "11185.87786614", // 标记价格 + "i": "11784.62659091" // 现货指数价格 + "P": "11784.25641265", // 预估结算价,仅在结算前最后一小时有参考价值 + "r": "0.00030000", // 资金费率 + "T": 1562306400000 // 下个资金时间 + } +] +``` + + +**Stream Name:** +``!markPrice@arr`` 或 ``!markPrice@arr@1s`` + +**Update Speed:** 3000ms 或 1000ms + + + + + +## K线 + +> **Payload:** + +```javascript +{ + "e": "kline", // 事件类型 + "E": 123456789, // 事件时间 + "s": "BNBUSDT", // 交易对 + "k": { + "t": 123400000, // 这根K线的起始时间 + "T": 123460000, // 这根K线的结束时间 + "s": "BNBUSDT", // 交易对 + "i": "1m", // K线间隔 + "f": 100, // 这根K线期间第一笔成交ID + "L": 200, // 这根K线期间末一笔成交ID + "o": "0.0010", // 这根K线期间第一笔成交价 + "c": "0.0020", // 这根K线期间末一笔成交价 + "h": "0.0025", // 这根K线期间最高成交价 + "l": "0.0015", // 这根K线期间最低成交价 + "v": "1000", // 这根K线期间成交量 + "n": 100, // 这根K线期间成交笔数 + "x": false, // 这根K线是否完结(是否已经开始下一根K线) + "q": "1.0000", // 这根K线期间成交额 + "V": "500", // 主动买入的成交量 + "Q": "0.500", // 主动买入的成交额 + "B": "123456" // 忽略此参数 + } +} +``` + +K线stream逐秒推送所请求的K线种类(最新一根K线)的更新。推送间隔250毫秒(如有刷新) + +**订阅Kline需要提供间隔参数,最短为分钟线,最长为月线。支持以下间隔:** + +m -> 分钟; h -> 小时; d -> 天; w -> 周; M -> 月 + +* 1m +* 3m +* 5m +* 15m +* 30m +* 1h +* 2h +* 4h +* 6h +* 8h +* 12h +* 1d +* 3d +* 1w +* 1M + +**Stream Name:** +``@kline_`` + +**Update Speed:** 250ms + + + + +## 按Symbol的精简Ticker + +> **Payload:** + +```javascript + { + "e": "24hrMiniTicker", // 事件类型 + "E": 123456789, // 事件时间(毫秒) + "s": "BNBUSDT", // 交易对 + "c": "0.0025", // 最新成交价格 + "o": "0.0010", // 24小时前开始第一笔成交价格 + "h": "0.0025", // 24小时内最高成交价 + "l": "0.0010", // 24小时内最低成交价 + "v": "10000", // 成交量 + "q": "18" // 成交额 + } +``` + +按Symbol刷新的24小时精简ticker信息. + +**Stream Name:** +``@miniTicker` + +**Update Speed:** 500ms + + + +## 全市场的精简Ticker + +> **Payload:** + +```javascript +[ + { + "e": "24hrMiniTicker", // 事件类型 + "E": 123456789, // 事件时间(毫秒) + "s": "BNBUSDT", // 交易对 + "c": "0.0025", // 最新成交价格 + "o": "0.0010", // 24小时前开始第一笔成交价格 + "h": "0.0025", // 24小时内最高成交价 + "l": "0.0010", // 24小时内最低成交价 + "v": "10000", // 成交量 + "q": "18" // 成交额 + } +] +``` + +所有symbol24小时精简ticker信息.需要注意的是,只有发生变化的ticker更新才会被推送。 + +**Stream Name:** +`!miniTicker@arr` + +**Update Speed:** 1000ms + + + + +## 按Symbol的完整Ticker + + +> **Payload:** + +```javascript +{ + "e": "24hrTicker", // 事件类型 + "E": 123456789, // 事件时间 + "s": "BNBUSDT", // 交易对 + "p": "0.0015", // 24小时价格变化 + "P": "250.00", // 24小时价格变化(百分比) + "w": "0.0018", // 平均价格 + "c": "0.0025", // 最新成交价格 + "Q": "10", // 最新成交价格上的成交量 + "o": "0.0010", // 24小时内第一比成交的价格 + "h": "0.0025", // 24小时内最高成交价 + "l": "0.0010", // 24小时内最低成交价 + "v": "10000", // 24小时内成交量 + "q": "18", // 24小时内成交额 + "O": 0, // 统计开始时间 + "C": 86400000, // 统计关闭时间 + "F": 0, // 24小时内第一笔成交交易ID + "L": 18150, // 24小时内最后一笔成交交易ID + "n": 18151 // 24小时内成交数 +} +``` + +按Symbol刷新的24小时完整ticker信息 + +**Stream Name:** +``@ticker`` + +**Update Speed:** 500ms + + + +## 全市场的完整Ticker + + +> **Payload:** + +```javascript +[ + { + "e": "24hrTicker", // 事件类型 + "E": 123456789, // 事件时间 + "s": "BNBUSDT", // 交易对 + "p": "0.0015", // 24小时价格变化 + "P": "250.00", // 24小时价格变化(百分比) + "w": "0.0018", // 平均价格 + "c": "0.0025", // 最新成交价格 + "Q": "10", // 最新成交价格上的成交量 + "o": "0.0010", // 24小时内第一比成交的价格 + "h": "0.0025", // 24小时内最高成交价 + "l": "0.0010", // 24小时内最低成交价 + "v": "10000", // 24小时内成交量 + "q": "18", // 24小时内成交额 + "O": 0, // 统计开始时间 + "C": 86400000, // 统计结束时间 + "F": 0, // 24小时内第一笔成交交易ID + "L": 18150, // 24小时内最后一笔成交交易ID + "n": 18151 // 24小时内成交数 + } +] +``` + +所有symbol 24小时完整ticker信息.需要注意的是,只有发生变化的ticker更新才会被推送。 + +**Stream Name:** +``!ticker@arr`` + +**Update Speed:** 1000ms + + +## 按Symbol的最优挂单信息 + +> **Payload:** + +```javascript +{ + "e":"bookTicker", // 事件类型 + "u":400900217, // 更新ID + "E": 1568014460893, // 事件推送时间 + "T": 1568014460891, // 撮合时间 + "s":"BNBUSDT", // 交易对 + "b":"25.35190000", // 买单最优挂单价格 + "B":"31.21000000", // 买单最优挂单数量 + "a":"25.36520000", // 卖单最优挂单价格 + "A":"40.66000000" // 卖单最优挂单数量 +} +``` + + +实时推送指定交易对最优挂单信息 + +**Stream Name:** `@bookTicker` + +**Update Speed:** 实时 + + + + + +## 全市场最优挂单信息 + +> **Payload:** + +```javascript +{ + // Same as @bookTicker payload +} +``` + +所有交易对交易对最优挂单信息 + +**Stream Name:** `!bookTicker` + +**Update Speed:** 实时 + + + +##强平订单 + +> **Payload:** + +```javascript +{ + + "e":"forceOrder",                   // 事件类型 + "E":1568014460893,                  // 事件时间 + "o":{ + + "s":"BTCUSDT",                   // 交易对 + "S":"SELL",                      // 订单方向 + "o":"LIMIT",                     // 订单类型 + "f":"IOC",                       // 有效方式 + "q":"0.014",                     // 订单数量 + "p":"9910",                      // 订单价格 + "ap":"9910",                     // 平均价格 + "X":"FILLED",                    // 订单状态 + "l":"0.014",                     // 订单最近成交量 + "z":"0.014",                     // 订单累计成交量 + "T":1568014460893,          // 交易时间 + + } + +} +``` + +推送特定`symbol`的强平订单快照信息。 + +1000ms内至多仅推送一条最近的强平订单作为快照 + +**Stream Name:**  ``@forceOrder`` + +**Update Speed:** 1000ms + + + + + +## 有限档深度信息 + +> **Payload:** + +```javascript +{ + "e": "depthUpdate", // 事件类型 + "E": 1571889248277, // 事件时间 + "T": 1571889248276, // 交易时间 + "s": "BTCUSDT", + "U": 390497796, + "u": 390497878, + "pu": 390497794, + "b": [ // 买方 + [ + "7403.89", // 价格 + "0.002" // 数量 + ], + [ + "7403.90", + "3.906" + ], + [ + "7404.00", + "1.428" + ], + [ + "7404.85", + "5.239" + ], + [ + "7405.43", + "2.562" + ] + ], + "a": [ // 卖方 + [ + "7405.96", // 价格 + "3.340" // 数量 + ], + [ + "7406.63", + "4.525" + ], + [ + "7407.08", + "2.475" + ], + [ + "7407.15", + "4.800" + ], + [ + "7407.20", + "0.175" + ] + ] +} +``` + +推送有限档深度信息。levels表示几档买卖单信息, 可选 5/10/20档 + +**Stream Names:** `@depth` 或 `@depth@500ms` 或 `@depth@100ms`. + +**Update Speed:** 250ms 或 500ms 或 100ms + + + + +## 增量深度信息 + +> **Payload:** + +```javascript +{ + "e": "depthUpdate", // 事件类型 + "E": 123456789, // 事件时间 + "T": 123456788, // 撮合时间 + "s": "BNBUSDT", // 交易对 + "U": 157, // 从上次推送至今新增的第一个 update Id + "u": 160, // 从上次推送至今新增的最后一个 update Id + "pu": 149, // 上次推送的最后一个update Id(即上条消息的‘u’) + "b": [ // 变动的买单深度 + [ + "0.0024", // 价格 + "10" // 数量 + ] + ], + "a": [ // 变动的卖单深度 + [ + "0.0026", // 价格 + "100" // 数量 + ] + ] +} +``` + +orderbook的变化部分,推送间隔250毫秒,500毫秒,100毫秒(如有刷新) + +**Stream 名称:** +``@depth`` OR ``@depth@500ms`` OR ``@depth@100ms`` + +**Update Speed:** 250ms 或 500ms 或 100ms + + +## 如何正确在本地维护一个orderbook副本 +1. 订阅 **wss://fstream.asterdex-testnet.com/stream?streams=btcusdt@depth** +2. 开始缓存收到的更新。同一个价位,后收到的更新覆盖前面的。 +3. 访问Rest接口 **https://fapi.asterdex-testnet.com/fapi/v3/depth?symbol=BTCUSDT&limit=1000**获得一个1000档的深度快照 +4. 将目前缓存到的信息中`u`< 步骤3中获取到的快照中的`lastUpdateId`的部分丢弃(丢弃更早的信息,已经过期)。 +5. 将深度快照中的内容更新到本地orderbook副本中,并从websocket接收到的第一个`U` <= `lastUpdateId` **且** `u` >= `lastUpdateId` 的event开始继续更新本地副本。 +6. 每一个新event的`pu`应该等于上一个event的`u`,否则可能出现了丢包,请从step3重新进行初始化。 +7. 每一个event中的挂单量代表这个价格目前的挂单量**绝对值**,而不是相对变化。 +8. 如果某个价格对应的挂单量为0,表示该价位的挂单已经撤单或者被吃,应该移除这个价位。 + + + + +# 账户和交易接口 + + + + +## 更改持仓模式(TRADE) + +> **响应:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +`` +POST /fapi/v3/positionSide/dual`` + +变换用户在 ***所有symbol*** 合约上的持仓模式:双向持仓或单向持仓。 + +**权重:** +1 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +---------- | ------ | -------- | ----------------- +dualSidePosition | STRING | YES | "true": 双向持仓模式;"false": 单向持仓模式 + + + +## 查询持仓模式(USER_DATA) + +> **响应:** + +```javascript +{ + "dualSidePosition": true // "true": 双向持仓模式;"false": 单向持仓模式 +} +``` + +`` +GET /fapi/v3/positionSide/dual`` + +查询用户目前在 ***所有symbol*** 合约上的持仓模式:双向持仓或单向持仓。 + +**权重:** +30 + +## 更改联合保证金模式(TRADE) + +> **响应:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +`` +POST /fapi/v3/multiAssetsMargin`` + +变换用户在 ***所有symbol*** 合约上的联合保证金模式:开启或关闭联合保证金模式。 + +**权重:** +1 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +---------- | ------ | -------- | ----------------- +multiAssetsMargin | STRING | YES | "true": 联合保证金模式开启;"false": 联合保证金模式关闭 + + + +## 查询联合保证金模式(USER_DATA) + +> **响应:** + +```javascript +{ + "multiAssetsMargin": true // "true": 联合保证金模式开启;"false": 联合保证金模式关闭 +} +``` + +`` +GET /fapi/v3/multiAssetsMargin`` + +查询用户目前在 ***所有symbol*** 合约上的联合保证金模式。 + +**权重:** +30 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +---------- | ------ | -------- | ----------------- + + +## 下单 (TRADE) + + +> **响应:** + +```javascript +{ + "clientOrderId": "testOrder", // 用户自定义的订单号 + "cumQty": "0", + "cumQuote": "0", // 成交金额 + "executedQty": "0", // 成交量 + "orderId": 22542179, // 系统订单号 + "avgPrice": "0.00000", // 平均成交价 + "origQty": "10", // 原始委托数量 + "price": "0", // 委托价格 + "reduceOnly": false, // 仅减仓 + "side": "SELL", // 买卖方向 + "positionSide": "SHORT", // 持仓方向 + "status": "NEW", // 订单状态 + "stopPrice": "0", // 触发价,对`TRAILING_STOP_MARKET`无效 + "closePosition": false, // 是否条件全平仓 + "symbol": "BTCUSDT", // 交易对 + "timeInForce": "GTC", // 有效方法 + "type": "TRAILING_STOP_MARKET", // 订单类型 + "origType": "TRAILING_STOP_MARKET", // 触发前订单类型 + "activatePrice": "9020", // 跟踪止损激活价格, 仅`TRAILING_STOP_MARKET` 订单返回此字段 + "priceRate": "0.3", // 跟踪止损回调比例, 仅`TRAILING_STOP_MARKET` 订单返回此字段 + "updateTime": 1566818724722, // 更新时间 + "workingType": "CONTRACT_PRICE", // 条件价格触发类型 + "priceProtect": false // 是否开启条件单触发保护 +} +``` + +`` +POST /fapi/v3/order `` + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +---------------- | ------- | -------- | --- +symbol | STRING | YES | 交易对 +side | ENUM | YES | 买卖方向 `SELL`, `BUY` +positionSide | ENUM | NO | 持仓方向,单向持仓模式下非必填,默认且仅可填`BOTH`;在双向持仓模式下必填,且仅可选择 `LONG` 或 `SHORT` +type | ENUM | YES | 订单类型 `LIMIT`, `MARKET`, `STOP`, `TAKE_PROFIT`, `STOP_MARKET`, `TAKE_PROFIT_MARKET`, `TRAILING_STOP_MARKET` +reduceOnly | STRING | NO | `true`, `false`; 非双开模式下默认`false`;双开模式下不接受此参数; 使用`closePosition`不支持此参数。 +quantity | DECIMAL | NO | 下单数量,使用`closePosition`不支持此参数。 +price | DECIMAL | NO | 委托价格 +newClientOrderId | STRING | NO | 用户自定义的订单号,不可以重复出现在挂单中。如空缺系统会自动赋值。必须满足正则规则 `^[\.A-Z\:/a-z0-9_-]{1,36}$` +stopPrice | DECIMAL | NO | 触发价, 仅 `STOP`, `STOP_MARKET`, `TAKE_PROFIT`, `TAKE_PROFIT_MARKET` 需要此参数 +closePosition | STRING | NO | `true`, `false`;触发后全部平仓,仅支持`STOP_MARKET`和`TAKE_PROFIT_MARKET`;不与`quantity`合用;自带只平仓效果,不与`reduceOnly` 合用 +activationPrice | DECIMAL | NO | 追踪止损激活价格,仅`TRAILING_STOP_MARKET` 需要此参数, 默认为下单当前市场价格(支持不同`workingType`) +callbackRate | DECIMAL | NO | 追踪止损回调比例,可取值范围[0.1, 5],其中 1代表1% ,仅`TRAILING_STOP_MARKET` 需要此参数 +timeInForce | ENUM | NO | 有效方法 +workingType | ENUM | NO | stopPrice 触发类型: `MARK_PRICE`(标记价格), `CONTRACT_PRICE`(合约最新价). 默认 `CONTRACT_PRICE` +priceProtect | STRING | NO | 条件单触发保护:"TRUE","FALSE", 默认"FALSE". 仅 `STOP`, `STOP_MARKET`, `TAKE_PROFIT`, `TAKE_PROFIT_MARKET` 需要此参数 +newOrderRespType | ENUM | NO | "ACK", "RESULT", 默认 "ACK" + +根据 order `type`的不同,某些参数强制要求,具体如下: + +Type | 强制要求的参数 +----------------------------------- | ---------------------------------- +`LIMIT` | `timeInForce`, `quantity`, `price` +`MARKET` | `quantity` +`STOP`, `TAKE_PROFIT` | `quantity`, `price`, `stopPrice` +`STOP_MARKET`, `TAKE_PROFIT_MARKET` | `stopPrice` +`TRAILING_STOP_MARKET` | `callbackRate` + + + +* 条件单的触发必须: + + * 如果订单参数`priceProtect`为true: + * 达到触发价时,`MARK_PRICE`(标记价格)与`CONTRACT_PRICE`(合约最新价)之间的价差不能超过改symbol触发保护阈值 + * 触发保护阈值请参考接口`GET /fapi/v3/exchangeInfo` 返回内容相应symbol中"triggerProtect"字段 + + * `STOP`, `STOP_MARKET` 止损单: + * 买入: 最新合约价格/标记价格高于等于触发价`stopPrice` + * 卖出: 最新合约价格/标记价格低于等于触发价`stopPrice` + * `TAKE_PROFIT`, `TAKE_PROFIT_MARKET` 止盈单: + * 买入: 最新合约价格/标记价格低于等于触发价`stopPrice` + * 卖出: 最新合约价格/标记价格高于等于触发价`stopPrice` + + * `TRAILING_STOP_MARKET` 跟踪止损单: + * 买入: 当合约价格/标记价格区间最低价格低于激活价格`activationPrice`,且最新合约价格/标记价高于等于最低价设定回调幅度。 + * 卖出: 当合约价格/标记价格区间最高价格高于激活价格`activationPrice`,且最新合约价格/标记价低于等于最高价设定回调幅度。 + +* `TRAILING_STOP_MARKET` 跟踪止损单如果遇到报错 ``{"code": -2021, "msg": "Order would immediately trigger."}`` +表示订单不满足以下条件: + * 买入: 指定的`activationPrice` 必须小于 latest price + * 卖出: 指定的`activationPrice` 必须大于 latest price + +* `newOrderRespType` 如果传 `RESULT`: + * `MARKET` 订单将直接返回成交结果; + * 配合使用特殊 `timeInForce` 的 `LIMIT` 订单将直接返回成交或过期拒绝结果。 + +* `STOP_MARKET`, `TAKE_PROFIT_MARKET` 配合 `closePosition`=`true`: + * 条件单触发依照上述条件单触发逻辑 + * 条件触发后,平掉当时持有所有多头仓位(若为卖单)或当时持有所有空头仓位(若为买单) + * 不支持 `quantity` 参数 + * 自带只平仓属性,不支持`reduceOnly`参数 + * 双开模式下,`LONG`方向上不支持`BUY`; `SHORT` 方向上不支持`SELL` + + +## 测试下单接口 (TRADE) + + +> **响应:** + +```javascript +字段与下单接口一致,但均为无效值 +``` + + +`` +POST /fapi/v3/order/test`` + +用于测试订单请求,但不会提交到撮合引擎 + +**权重:** +1 + +**参数:** + +参考 `POST /fapi/v3/order` + + + +## 批量下单 (TRADE) + + +> **响应:** + +```javascript +[ + { + "clientOrderId": "testOrder", // 用户自定义的订单号 + "cumQty": "0", + "cumQuote": "0", // 成交金额 + "executedQty": "0", // 成交量 + "orderId": 22542179, // 系统订单号 + "avgPrice": "0.00000", // 平均成交价 + "origQty": "10", // 原始委托数量 + "price": "0", // 委托价格 + "reduceOnly": false, // 仅减仓 + "side": "SELL", // 买卖方向 + "positionSide": "SHORT", // 持仓方向 + "status": "NEW", // 订单状态 + "stopPrice": "0", // 触发价,对`TRAILING_STOP_MARKET`无效 + "closePosition": false, // 是否条件全平仓 + "symbol": "BTCUSDT", // 交易对 + "timeInForce": "GTC", // 有效方法 + "type": "TRAILING_STOP_MARKET", // 订单类型 + "origType": "TRAILING_STOP_MARKET", // 触发前订单类型 + "activatePrice": "9020", // 跟踪止损激活价格, 仅`TRAILING_STOP_MARKET` 订单返回此字段 + "priceRate": "0.3", // 跟踪止损回调比例, 仅`TRAILING_STOP_MARKET` 订单返回此字段 + "updateTime": 1566818724722, // 更新时间 + "workingType": "CONTRACT_PRICE", // 条件价格触发类型 + "priceProtect": false // 是否开启条件单触发保护 + }, + { + "code": -2022, + "msg": "ReduceOnly Order is rejected." + } +] +``` + +`` +POST /fapi/v3/batchOrders `` + +**权重:** +5 + +**参数:** + + +名称 | 类型 | 是否必需 | 描述 +---------------- | ------- | -------- | ---- +batchOrders | list | YES | 订单列表,最多支持5个订单 + +**其中``batchOrders``应以list of JSON格式填写订单参数** + +名称 | 类型 | 是否必需 | 描述 +---------------- | ------- | -------- | ---- +symbol | STRING | YES | 交易对 +side | ENUM | YES | 买卖方向 `SELL`, `BUY` +positionSide | ENUM | NO | 持仓方向,单向持仓模式下非必填,默认且仅可填`BOTH`;在双向持仓模式下必填,且仅可选择 `LONG` 或 `SHORT` +type | ENUM | YES | 订单类型 `LIMIT`, `MARKET`, `STOP`, `TAKE_PROFIT`, `STOP_MARKET`, `TAKE_PROFIT_MARKET`, `TRAILING_STOP_MARKET` +reduceOnly | STRING | NO | `true`, `false`; 非双开模式下默认`false`;双开模式下不接受此参数。 +quantity | DECIMAL | YES | 下单数量 +price | DECIMAL | NO | 委托价格 +newClientOrderId | STRING | NO | 用户自定义的订单号,不可以重复出现在挂单中。如空缺系统会自动赋值. 必须满足正则规则 `^[\.A-Z\:/a-z0-9_-]{1,36}$` +stopPrice | DECIMAL | NO | 触发价, 仅 `STOP`, `STOP_MARKET`, `TAKE_PROFIT`, `TAKE_PROFIT_MARKET` 需要此参数 +activationPrice | DECIMAL | NO | 追踪止损激活价格,仅`TRAILING_STOP_MARKET` 需要此参数, 默认为下单当前市场价格(支持不同`workingType`) +callbackRate | DECIMAL | NO | 追踪止损回调比例,可取值范围[0.1, 4],其中 1代表1% ,仅`TRAILING_STOP_MARKET` 需要此参数 +timeInForce | ENUM | NO | 有效方法 +workingType | ENUM | NO | stopPrice 触发类型: `MARK_PRICE`(标记价格), `CONTRACT_PRICE`(合约最新价). 默认 `CONTRACT_PRICE` +priceProtect | STRING | NO | 条件单触发保护:"TRUE","FALSE", 默认"FALSE". 仅 `STOP`, `STOP_MARKET`, `TAKE_PROFIT`, `TAKE_PROFIT_MARKET` 需要此参数 +newOrderRespType | ENUM | NO | "ACK", "RESULT", 默认 "ACK" + + +* 具体订单条件规则,与普通下单一致 +* 批量下单采取并发处理,不保证订单撮合顺序 +* 批量下单的返回内容顺序,与订单列表顺序一致 + + + +## 期货现货互转 (TRANSFER) + +> **响应:** + +```javascript +{ + "tranId": 21841, //交易id + "status": "SUCCESS" //状态 +} +``` + +`` +POST /fapi/v3/asset/wallet/transfer (TRANSFER) +`` + +**权重:** +5 + +**参数:** + + +名称 | 类型 | 是否必需 | 描述 +---------------- | ------- | -------- | ---- +amount | DECIMAL | YES | 数量 +asset | STRING | YES | 资产 +clientTranId | STRING | YES | 交易id +kindType | STRING | YES | 交易类型 + +* kindType 取值为FUTURE_SPOT(期货转现货),SPOT_FUTURE(现货转期货) + + +## 查询订单 (USER_DATA) + + +> **响应:** + +```javascript +{ + "avgPrice": "0.00000", // 平均成交价 + "clientOrderId": "abc", // 用户自定义的订单号 + "cumQuote": "0", // 成交金额 + "executedQty": "0", // 成交量 + "orderId": 1573346959, // 系统订单号 + "origQty": "0.40", // 原始委托数量 + "origType": "TRAILING_STOP_MARKET", // 触发前订单类型 + "price": "0", // 委托价格 + "reduceOnly": false, // 是否仅减仓 + "side": "BUY", // 买卖方向 + "positionSide": "SHORT", // 持仓方向 + "status": "NEW", // 订单状态 + "stopPrice": "9300", // 触发价,对`TRAILING_STOP_MARKET`无效 + "closePosition": false, // 是否条件全平仓 + "symbol": "BTCUSDT", // 交易对 + "time": 1579276756075, // 订单时间 + "timeInForce": "GTC", // 有效方法 + "type": "TRAILING_STOP_MARKET", // 订单类型 + "activatePrice": "9020", // 跟踪止损激活价格, 仅`TRAILING_STOP_MARKET` 订单返回此字段 + "priceRate": "0.3", // 跟踪止损回调比例, 仅`TRAILING_STOP_MARKET` 订单返回此字段 + "updateTime": 1579276756075, // 更新时间 + "workingType": "CONTRACT_PRICE", // 条件价格触发类型 + "priceProtect": false // 是否开启条件单触发保护 +} +``` + +`` +GET /fapi/v3/order`` + +查询订单状态 + +* 请注意,如果订单满足如下条件,不会被查询到: + * 订单的最终状态为 `CANCELED` 或者 `EXPIRED`, **并且** + * 订单没有任何的成交记录, **并且** + * 订单生成时间 + 7天 < 当前时间 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +----------------- | ------ | -------- | ---- +symbol | STRING | YES | 交易对 +orderId | LONG | NO | 系统订单号 +origClientOrderId | STRING | NO | 用户自定义的订单号 + +注意: + +* 至少需要发送 `orderId` 与 `origClientOrderId`中的一个 + + +## 撤销订单 (TRADE) + +> **响应:** + +```javascript +{ + "clientOrderId": "myOrder1", // 用户自定义的订单号 + "cumQty": "0", + "cumQuote": "0", // 成交金额 + "executedQty": "0", // 成交量 + "orderId": 283194212, // 系统订单号 + "origQty": "11", // 原始委托数量 + "price": "0", // 委托价格 + "reduceOnly": false, // 仅减仓 + "side": "BUY", // 买卖方向 + "positionSide": "SHORT", // 持仓方向 + "status": "CANCELED", // 订单状态 + "stopPrice": "9300", // 触发价,对`TRAILING_STOP_MARKET`无效 + "closePosition": false, // 是否条件全平仓 + "symbol": "BTCUSDT", // 交易对 + "timeInForce": "GTC", // 有效方法 + "origType": "TRAILING_STOP_MARKET", // 触发前订单类型 + "type": "TRAILING_STOP_MARKET", // 订单类型 + "activatePrice": "9020", // 跟踪止损激活价格, 仅`TRAILING_STOP_MARKET` 订单返回此字段 + "priceRate": "0.3", // 跟踪止损回调比例, 仅`TRAILING_STOP_MARKET` 订单返回此字段 + "updateTime": 1571110484038, // 更新时间 + "workingType": "CONTRACT_PRICE", // 条件价格触发类型 + "priceProtect": false // 是否开启条件单触发保护 +} +``` + +`` +DELETE /fapi/v3/order `` + +**权重:** +1 + +**Parameters:** + +名称 | 类型 | 是否必需 | 描述 +----------------- | ------ | -------- | ------------------ +symbol | STRING | YES | 交易对 +orderId | LONG | NO | 系统订单号 +origClientOrderId | STRING | NO | 用户自定义的订单号 + +`orderId` 与 `origClientOrderId` 必须至少发送一个 + + +## 撤销全部订单 (TRADE) + +> **响应:** + +```javascript +{ + "code": "200", + "msg": "The operation of cancel all open order is done." +} +``` + +`` +DELETE /fapi/v3/allOpenOrders `` + +**权重:** +1 + +**Parameters:** + + 名称 | 类型 | 是否必需 | 描述 +---------- | ------ | -------- | ------ +symbol | STRING | YES | 交易对 + + +## 批量撤销订单 (TRADE) + +> **响应:** + +```javascript +[ + { + "clientOrderId": "myOrder1", // 用户自定义的订单号 + "cumQty": "0", + "cumQuote": "0", // 成交金额 + "executedQty": "0", // 成交量 + "orderId": 283194212, // 系统订单号 + "origQty": "11", // 原始委托数量 + "price": "0", // 委托价格 + "reduceOnly": false, // 仅减仓 + "side": "BUY", // 买卖方向 + "positionSide": "SHORT", // 持仓方向 + "status": "CANCELED", // 订单状态 + "stopPrice": "9300", // 触发价,对`TRAILING_STOP_MARKET`无效 + "closePosition": false, // 是否条件全平仓 + "symbol": "BTCUSDT", // 交易对 + "timeInForce": "GTC", // 有效方法 + "origType": "TRAILING_STOP_MARKET", // 触发前订单类型 + "type": "TRAILING_STOP_MARKET", // 订单类型 + "activatePrice": "9020", // 跟踪止损激活价格, 仅`TRAILING_STOP_MARKET` 订单返回此字段 + "priceRate": "0.3", // 跟踪止损回调比例, 仅`TRAILING_STOP_MARKET` 订单返回此字段 + "updateTime": 1571110484038, // 更新时间 + "workingType": "CONTRACT_PRICE", // 条件价格触发类型 + "priceProtect": false // 是否开启条件单触发保护 + }, + { + "code": -2011, + "msg": "Unknown order sent." + } +] +``` + +`` +DELETE /fapi/v3/batchOrders `` + +**权重:** +1 + +**Parameters:** + + 名称 | 类型 | 是否必需 | 描述 +--------------------- | -------------- | -------- | ---------------- +symbol | STRING | YES | 交易对 +orderIdList | LIST\ | NO | 系统订单号, 最多支持10个订单
比如`[1234567,2345678]` +origClientOrderIdList | LIST\ | NO | 用户自定义的订单号, 最多支持10个订单
比如`["my_id_1","my_id_2"]` 需要encode双引号。逗号后面没有空格。 + +`orderIdList` 与 `origClientOrderIdList` 必须至少发送一个,不可同时发送 + + +## 倒计时撤销所有订单 (TRADE) + +> **响应:** + +```javascript +{ + "symbol": "BTCUSDT", + "countdownTime": "100000" +} +``` + + +`` +POST /fapi/v3/countdownCancelAll `` + +**权重:** +10 + +**Parameters:** + + 名称 | 类型 | 是否必需 | 描述 +--------------------- | -------------- | -------- | ---------------- +symbol | STRING | YES | +countdownTime | LONG | YES | 倒计时。 1000 表示 1 秒; 0 表示取消倒计时撤单功能。 + +* 该接口可以被用于确保在倒计时结束时撤销指定symbol上的所有挂单。 在使用这个功能时,接口应像心跳一样在倒计时内被反复调用,以便可以取消既有的倒计时并开始新的倒数计时设置。 + +* 用法示例: + 以30s的间隔重复此接口,每次倒计时countdownTime设置为120000(120s)。 + 如果在120秒内未再次调用此接口,则您指定symbol上的所有挂单都会被自动撤销。 + 如果在120秒内以将countdownTime设置为0,则倒数计时器将终止,自动撤单功能取消。 + +* 系统会**大约每10毫秒**检查一次所有倒计时情况,因此请注意,使用此功能时应考虑足够的冗余。 +我们不建议将倒记时设置得太精确或太小。 + + + + + +## 查询当前挂单 (USER_DATA) + +> **响应:** + +```javascript + +{ + "avgPrice": "0.00000", // 平均成交价 + "clientOrderId": "abc", // 用户自定义的订单号 + "cumQuote": "0", // 成交金额 + "executedQty": "0", // 成交量 + "orderId": 1917641, // 系统订单号 + "origQty": "0.40", // 原始委托数量 + "origType": "TRAILING_STOP_MARKET", // 触发前订单类型 + "price": "0", // 委托价格 + "reduceOnly": false, // 是否仅减仓 + "side": "BUY", // 买卖方向 + "status": "NEW", // 订单状态 + "positionSide": "SHORT", // 持仓方向 + "stopPrice": "9300", // 触发价,对`TRAILING_STOP_MARKET`无效 + "closePosition": false, // 是否条件全平仓 + "symbol": "BTCUSDT", // 交易对 + "time": 1579276756075, // 订单时间 + "timeInForce": "GTC", // 有效方法 + "type": "TRAILING_STOP_MARKET", // 订单类型 + "activatePrice": "9020", // 跟踪止损激活价格, 仅`TRAILING_STOP_MARKET` 订单返回此字段 + "priceRate": "0.3", // 跟踪止损回调比例, 仅`TRAILING_STOP_MARKET` 订单返回此字段 + "updateTime": 1579276756075, // 更新时间 + "workingType": "CONTRACT_PRICE", // 条件价格触发类型 + "priceProtect": false // 是否开启条件单触发保护 +} +``` + +`` +GET /fapi/v3/openOrder `` + +请小心使用不带symbol参数的调用 + +**权重: 1** + + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +---------- | ------ | -------- | ------ +symbol | STRING | YES | 交易对 +orderId | LONG | NO | 系统订单号 +origClientOrderId | STRING | NO | 用户自定义的订单号 + +* `orderId` 与 `origClientOrderId` 中的一个为必填参数 +* 查询的订单如果已经成交或取消,将返回报错 "Order does not exist." + + +## 查看当前全部挂单 (USER_DATA) + +> **响应:** + +```javascript +[ + { + "avgPrice": "0.00000", // 平均成交价 + "clientOrderId": "abc", // 用户自定义的订单号 + "cumQuote": "0", // 成交金额 + "executedQty": "0", // 成交量 + "orderId": 1917641, // 系统订单号 + "origQty": "0.40", // 原始委托数量 + "origType": "TRAILING_STOP_MARKET", // 触发前订单类型 + "price": "0", // 委托价格 + "reduceOnly": false, // 是否仅减仓 + "side": "BUY", // 买卖方向 + "positionSide": "SHORT", // 持仓方向 + "status": "NEW", // 订单状态 + "stopPrice": "9300", // 触发价,对`TRAILING_STOP_MARKET`无效 + "closePosition": false, // 是否条件全平仓 + "symbol": "BTCUSDT", // 交易对 + "time": 1579276756075, // 订单时间 + "timeInForce": "GTC", // 有效方法 + "type": "TRAILING_STOP_MARKET", // 订单类型 + "activatePrice": "9020", // 跟踪止损激活价格, 仅`TRAILING_STOP_MARKET` 订单返回此字段 + "priceRate": "0.3", // 跟踪止损回调比例, 仅`TRAILING_STOP_MARKET` 订单返回此字段 + "updateTime": 1579276756075, // 更新时间 + "workingType": "CONTRACT_PRICE", // 条件价格触发类型 + "priceProtect": false // 是否开启条件单触发保护 + } +] +``` + +`` +GET /fapi/v3/openOrders `` + +请小心使用不带symbol参数的调用 + +**权重:** +- 带symbol ***1*** +- 不带 ***40*** + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +---------- | ------ | -------- | ------ +symbol | STRING | NO | 交易对 + +* 不带symbol参数,会返回所有交易对的挂单 + + + +## 查询所有订单(包括历史订单) (USER_DATA) + + +> **响应:** + +```javascript +[ + { + "avgPrice": "0.00000", // 平均成交价 + "clientOrderId": "abc", // 用户自定义的订单号 + "cumQuote": "0", // 成交金额 + "executedQty": "0", // 成交量 + "orderId": 1917641, // 系统订单号 + "origQty": "0.40", // 原始委托数量 + "origType": "TRAILING_STOP_MARKET", // 触发前订单类型 + "price": "0", // 委托价格 + "reduceOnly": false, // 是否仅减仓 + "side": "BUY", // 买卖方向 + "positionSide": "SHORT", // 持仓方向 + "status": "NEW", // 订单状态 + "stopPrice": "9300", // 触发价,对`TRAILING_STOP_MARKET`无效 + "closePosition": false, // 是否条件全平仓 + "symbol": "BTCUSDT", // 交易对 + "time": 1579276756075, // 订单时间 + "timeInForce": "GTC", // 有效方法 + "type": "TRAILING_STOP_MARKET", // 订单类型 + "activatePrice": "9020", // 跟踪止损激活价格, 仅`TRAILING_STOP_MARKET` 订单返回此字段 + "priceRate": "0.3", // 跟踪止损回调比例, 仅`TRAILING_STOP_MARKET` 订单返回此字段 + "updateTime": 1579276756075, // 更新时间 + "workingType": "CONTRACT_PRICE", // 条件价格触发类型 + "priceProtect": false // 是否开启条件单触发保护 + } +] +``` + +`` +GET /fapi/v3/allOrders`` + +* 请注意,如果订单满足如下条件,不会被查询到: + * 订单的最终状态为 `CANCELED` 或者 `EXPIRED`, **并且** + * 订单没有任何的成交记录, **并且** + * 订单生成时间 + 7天 < 当前时间 + +**权重:** +5 + +**Parameters:** + + 名称 | 类型 | 是否必需 | 描述 +---------- | ------ | -------- | ----------------------------------------------- +symbol | STRING | YES | 交易对 +orderId | LONG | NO | 只返回此orderID及之后的订单,缺省返回最近的订单 +startTime | LONG | NO | 起始时间 +endTime | LONG | NO | 结束时间 +limit | INT | NO | 返回的结果集数量 默认值:500 最大值:1000 + +* 查询时间范围最大不得超过7天 +* 默认查询最近7天内的数据 + + + +## 账户余额v3 (USER_DATA) + +> **响应:** + +```javascript +[ + { + "accountAlias": "SgsR", // 账户唯一识别码 + "asset": "USDT", // 资产 + "balance": "122607.35137903", // 总余额 + "crossWalletBalance": "23.72469206", // 全仓余额 + "crossUnPnl": "0.00000000" // 全仓持仓未实现盈亏 + "availableBalance": "23.72469206", // 下单可用余额 + "maxWithdrawAmount": "23.72469206", // 最大可转出余额 + "marginAvailable": true, // 是否可用作联合保证金 + "updateTime": 1617939110373 + } +] +``` + +`` +GET /fapi/v3/balance`` + +**Weight:** +5 + +**Parameters:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ + + + + +## 账户信息v3 (USER_DATA) + +> **响应:** + +```javascript + +{ + "feeTier": 0, // 手续费等级 + "canTrade": true, // 是否可以交易 + "canDeposit": true, // 是否可以入金 + "canWithdraw": true, // 是否可以出金 + "updateTime": 0, + "totalInitialMargin": "0.00000000", // 但前所需起始保证金总额(存在逐仓请忽略), 仅计算usdt资产 + "totalMaintMargin": "0.00000000", // 维持保证金总额, 仅计算usdt资产 + "totalWalletBalance": "23.72469206", // 账户总余额, 仅计算usdt资产 + "totalUnrealizedProfit": "0.00000000", // 持仓未实现盈亏总额, 仅计算usdt资产 + "totalMarginBalance": "23.72469206", // 保证金总余额, 仅计算usdt资产 + "totalPositionInitialMargin": "0.00000000", // 持仓所需起始保证金(基于最新标记价格), 仅计算usdt资产 + "totalOpenOrderInitialMargin": "0.00000000", // 当前挂单所需起始保证金(基于最新标记价格), 仅计算usdt资产 + "totalCrossWalletBalance": "23.72469206", // 全仓账户余额, 仅计算usdt资产 + "totalCrossUnPnl": "0.00000000", // 全仓持仓未实现盈亏总额, 仅计算usdt资产 + "availableBalance": "23.72469206", // 可用余额, 仅计算usdt资产 + "maxWithdrawAmount": "23.72469206" // 最大可转出余额, 仅计算usdt资产 + "assets": [ + { + "asset": "USDT", //资产 + "walletBalance": "23.72469206", //余额 + "unrealizedProfit": "0.00000000", // 未实现盈亏 + "marginBalance": "23.72469206", // 保证金余额 + "maintMargin": "0.00000000", // 维持保证金 + "initialMargin": "0.00000000", // 当前所需起始保证金 + "positionInitialMargin": "0.00000000", // 持仓所需起始保证金(基于最新标记价格) + "openOrderInitialMargin": "0.00000000", // 当前挂单所需起始保证金(基于最新标记价格) + "crossWalletBalance": "23.72469206", //全仓账户余额 + "crossUnPnl": "0.00000000" // 全仓持仓未实现盈亏 + "availableBalance": "23.72469206", // 可用余额 + "maxWithdrawAmount": "23.72469206", // 最大可转出余额 + "marginAvailable": true, // 是否可用作联合保证金 + "updateTime": 1625474304765 //更新时间 + }, + { + "asset": "BUSD", //资产 + "walletBalance": "103.12345678", //余额 + "unrealizedProfit": "0.00000000", // 未实现盈亏 + "marginBalance": "103.12345678", // 保证金余额 + "maintMargin": "0.00000000", // 维持保证金 + "initialMargin": "0.00000000", // 当前所需起始保证金 + "positionInitialMargin": "0.00000000", // 持仓所需起始保证金(基于最新标记价格) + "openOrderInitialMargin": "0.00000000", // 当前挂单所需起始保证金(基于最新标记价格) + "crossWalletBalance": "103.12345678", //全仓账户余额 + "crossUnPnl": "0.00000000" // 全仓持仓未实现盈亏 + "availableBalance": "103.12345678", // 可用余额 + "maxWithdrawAmount": "103.12345678", // 最大可转出余额 + "marginAvailable": true, // 否可用作联合保证金 + "updateTime": 0 // 更新时间 + } + ], + "positions": [ // 头寸,将返回所有市场symbol。 + //根据用户持仓模式展示持仓方向,即单向模式下只返回BOTH持仓情况,双向模式下只返回 LONG 和 SHORT 持仓情况 + { + "symbol": "BTCUSDT", // 交易对 + "initialMargin": "0", // 当前所需起始保证金(基于最新标记价格) + "maintMargin": "0", //维持保证金 + "unrealizedProfit": "0.00000000", // 持仓未实现盈亏 + "positionInitialMargin": "0", // 持仓所需起始保证金(基于最新标记价格) + "openOrderInitialMargin": "0", // 当前挂单所需起始保证金(基于最新标记价格) + "leverage": "100", // 杠杆倍率 + "isolated": true, // 是否是逐仓模式 + "entryPrice": "0.00000", // 持仓成本价 + "maxNotional": "250000", // 当前杠杆下用户可用的最大名义价值 + "positionSide": "BOTH", // 持仓方向 + "positionAmt": "0", // 持仓数量 + "updateTime": 0 // 更新时间 + } + ] +} +``` + + +`` +GET /fapi/v3/accountWithJoinMargin`` + +**权重:** +5 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ + + + + +## 调整开仓杠杆 (TRADE) + +> **响应:** + +```javascript +{ + "leverage": 21, // 杠杆倍数 + "maxNotionalValue": "1000000", // 当前杠杆倍数下允许的最大名义价值 + "symbol": "BTCUSDT" // 交易对 +} +``` + +`` +POST /fapi/v3/leverage`` + +调整用户在指定symbol合约的开仓杠杆。 + +**权重:** +1 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +---------- | ------ | -------- | --------------------------- +symbol | STRING | YES | 交易对 +leverage | INT | YES | 目标杠杆倍数:1 到 125 整数 + + +## 变换逐全仓模式 (TRADE) + +> **响应:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +`` +POST /fapi/v3/marginType`` + +变换用户在指定symbol合约上的保证金模式:逐仓或全仓。 + +**权重:** +1 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +---------- | ------ | -------- | ----------------- +symbol | STRING | YES | 交易对 +marginType | ENUM | YES | 保证金模式 ISOLATED(逐仓), CROSSED(全仓) + + +## 调整逐仓保证金 (TRADE) + +> **响应:** + +```javascript +{ + "amount": 100.0, + "code": 200, + "msg": "Successfully modify position margin.", + "type": 1 +} +``` + +`` +POST /fapi/v3/positionMargin`` + +针对逐仓模式下的仓位,调整其逐仓保证金资金。 + +**权重:** +1 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +---------- | ------- | -------- | ------------------------------------ +symbol | STRING | YES | 交易对 +positionSide| ENUM | NO | 持仓方向,单向持仓模式下非必填,默认且仅可填`BOTH`;在双向持仓模式下必填,且仅可选择 `LONG` 或 `SHORT` +amount | DECIMAL | YES | 保证金资金 +type | INT | YES | 调整方向 1: 增加逐仓保证金,2: 减少逐仓保证金 + +* 只针对逐仓symbol 与 positionSide(如有) + + +## 逐仓保证金变动历史 (TRADE) + +> **响应:** + +```javascript +[ + { + "amount": "23.36332311", // 数量 + "asset": "USDT", // 资产 + "symbol": "BTCUSDT", // 交易对 + "time": 1578047897183, // 时间 + "type": 1, // 调整方向 + "positionSide": "BOTH" // 持仓方向 + }, + { + "amount": "100", + "asset": "USDT", + "symbol": "BTCUSDT", + "time": 1578047900425, + "type": 1, + "positionSide": "LONG" + } +] +``` + +`` +GET /fapi/v3/positionMargin/history`` + + + +**权重:** +1 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +---------- | ------ | -------- | ------------------------------------ +symbol | STRING | YES | 交易对 +type | INT | NO | 调整方向 1: 增加逐仓保证金,2: 减少逐仓保证金 +startTime | LONG | NO | 起始时间 +endTime | LONG | NO | 结束时间 +limit | INT | NO | 返回的结果集数量 默认值: 500 + + + + +## 用户持仓风险v3 (USER_DATA) + +> **响应:** + +> 单向持仓模式下: + +```javascript +[ + { + "entryPrice": "0.00000", // 开仓均价 + "marginType": "isolated", // 逐仓模式或全仓模式 + "isAutoAddMargin": "false", + "isolatedMargin": "0.00000000", // 逐仓保证金 + "leverage": "10", // 当前杠杆倍数 + "liquidationPrice": "0", // 参考强平价格 + "markPrice": "6679.50671178", // 当前标记价格 + "maxNotionalValue": "20000000", // 当前杠杆倍数允许的名义价值上限 + "positionAmt": "0.000", // 头寸数量,符号代表多空方向, 正数为多,负数为空 + "symbol": "BTCUSDT", // 交易对 + "unRealizedProfit": "0.00000000", // 持仓未实现盈亏 + "positionSide": "BOTH", // 持仓方向 + "updateTime": 1625474304765 // 更新时间 + } +] +``` + +> 双向持仓模式下: + +```javascript +[ + { + "entryPrice": "6563.66500", // 开仓均价 + "marginType": "isolated", // 逐仓模式或全仓模式 + "isAutoAddMargin": "false", + "isolatedMargin": "15517.54150468", // 逐仓保证金 + "leverage": "10", // 当前杠杆倍数 + "liquidationPrice": "5930.78", // 参考强平价格 + "markPrice": "6679.50671178", // 当前标记价格 + "maxNotionalValue": "20000000", // 当前杠杆倍数允许的名义价值上限 + "positionAmt": "20.000", // 头寸数量,符号代表多空方向, 正数为多,负数为空 + "symbol": "BTCUSDT", // 交易对 + "unRealizedProfit": "2316.83423560" // 持仓未实现盈亏 + "positionSide": "LONG", // 持仓方向 + "updateTime": 1625474304765 // 更新时间 + }, + { + "entryPrice": "0.00000", // 开仓均价 + "marginType": "isolated", // 逐仓模式或全仓模式 + "isAutoAddMargin": "false", + "isolatedMargin": "5413.95799991", // 逐仓保证金 + "leverage": "10", // 当前杠杆倍数 + "liquidationPrice": "7189.95", // 参考强平价格 + "markPrice": "6679.50671178", // 当前标记价格 + "maxNotionalValue": "20000000", // 当前杠杆倍数允许的名义价值上限 + "positionAmt": "-10.000", // 头寸数量,符号代表多空方向, 正数为多,负数为空 + "symbol": "BTCUSDT", // 交易对 + "unRealizedProfit": "-1156.46711780" // 持仓未实现盈亏 + "positionSide": "SHORT", // 持仓方向 + "updateTime": 1625474304765 //更新时间 + } +] +``` + +`` +GET /fapi/v3/positionRisk`` + +**权重:** +5 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +---------- | ---- | -------- | ---- +symbol | STRING | NO | + + +**注意** +请与账户推送信息`ACCOUNT_UPDATE`配合使用,以满足您的及时性和准确性需求。 + + + + +## 账户成交历史 (USER_DATA) + + +> **响应:** + +```javascript +[ + { + "buyer": false, // 是否是买方 + "commission": "-0.07819010", // 手续费 + "commissionAsset": "USDT", // 手续费计价单位 + "id": 698759, // 交易ID + "maker": false, // 是否是挂单方 + "orderId": 25851813, // 订单编号 + "price": "7819.01", // 成交价 + "qty": "0.002", // 成交量 + "quoteQty": "15.63802", // 成交额 + "realizedPnl": "-0.91539999", // 实现盈亏 + "side": "SELL", // 买卖方向 + "positionSide": "SHORT", // 持仓方向 + "symbol": "BTCUSDT", // 交易对 + "time": 1569514978020 // 时间 + } +] +``` + +`` +GET /fapi/v3/userTrades `` + +获取某交易对的成交历史 + +**权重:** +5 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +---------- | ------ | -------- | -------------------------------------------- +symbol | STRING | YES | 交易对 +startTime | LONG | NO | 起始时间 +endTime | LONG | NO | 结束时间 +fromId | LONG | NO | 返回该fromId及之后的成交,缺省返回最近的成交 +limit | INT | NO | 返回的结果集数量 默认值:500 最大值:1000. + +* 如果`startTime` 和 `endTime` 均未发送, 只会返回最近7天的数据。 +* startTime 和 endTime 的最大间隔为7天 + + +## 获取账户损益资金流水(USER_DATA) + +> **响应:** + +```javascript +[ + { + "symbol": "", // 交易对,仅针对涉及交易对的资金流 + "incomeType": "TRANSFER", // 资金流类型 + "income": "-0.37500000", // 资金流数量,正数代表流入,负数代表流出 + "asset": "USDT", // 资产内容 + "info":"TRANSFER", // 备注信息,取决于流水类型 + "time": 1570608000000, // 时间 + "tranId":"9689322392", // 划转ID + "tradeId":"" // 引起流水产生的原始交易ID + }, + { + "symbol": "BTCUSDT", + "incomeType": "COMMISSION", + "income": "-0.01000000", + "asset": "USDT", + "info":"COMMISSION", + "time": 1570636800000, + "tranId":"9689322392", + "tradeId":"2059192" + } +] +``` + +`` +GET /fapi/v3/income`` + +**权重:** +30 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +---------- | ------ | -------- | ----------------------------------------------------------------------------------------------- +symbol | STRING | NO | 交易对 +incomeType | STRING | NO | 收益类型 "TRANSFER","WELCOME_BONUS", "REALIZED_PNL","FUNDING_FEE", "COMMISSION", "INSURANCE_CLEAR", and "MARKET_MERCHANT_RETURN_REWARD" +startTime | LONG | NO | 起始时间 +endTime | LONG | NO | 结束时间 +limit | INT | NO | 返回的结果集数量 默认值:100 最大值:1000 + +* 如果`startTime` 和 `endTime` 均未发送, 只会返回最近7天的数据。 +* 如果`incomeType`没有发送,返回所有类型账户损益资金流水。 +* "trandId" 在相同用户的同一种收益流水类型中是唯一的。 + + +## 杠杆分层标准 (USER_DATA) + + +> **响应:** + +```javascript +[ + { + "symbol": "ETHUSDT", + "brackets": [ + { + "bracket": 1, // 层级 + "initialLeverage": 75, // 该层允许的最高初始杠杆倍数 + "notionalCap": 10000, // 该层对应的名义价值上限 + "notionalFloor": 0, // 该层对应的名义价值下限 + "maintMarginRatio": 0.0065, // 该层对应的维持保证金率 + "cum":0 // 速算数 + }, + ] + } +] +``` + +> **或** (若发送symbol) + +```javascript + +{ + "symbol": "ETHUSDT", + "brackets": [ + { + "bracket": 1, + "initialLeverage": 75, + "notionalCap": 10000, + "notionalFloor": 0, + "maintMarginRatio": 0.0065, + "cum":0 + }, + ] +} +``` + + +`` +GET /fapi/v3/leverageBracket +`` + + +**权重:** 1 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +------ | ------ | -------- | ------ +symbol | STRING | NO + + + +## 持仓ADL队列估算 (USER_DATA) + + +> **响应:** + +```javascript +[ + { + "symbol": "ETHUSDT", + "adlQuantile": + { + // 对于全仓状态下的双向持仓模式的交易对,会返回 "LONG", "SHORT" 和 "HEDGE", 其中"HEDGE"的存在仅作为标记;如果多空均有持仓的情况下,"LONG"和"SHORT"应返回共同计算后相同的队列分数。 + "LONG": 3, + "SHORT": 3, + "HEDGE": 0 // HEDGE 仅作为指示出现,请忽略数值 + } + }, + { + "symbol": "BTCUSDT", + "adlQuantile": + { + // 对于单向持仓模式或者是逐仓状态下的双向持仓模式的交易对,会返回 "LONG", "SHORT" 和 "BOTH" 分别表示不同持仓方向上持仓的adl队列分数 + "LONG": 1, // 双开模式下多头持仓的ADL队列估算分 + "SHORT": 2, // 双开模式下空头持仓的ADL队列估算分 + "BOTH": 0 // 单开模式下持仓的ADL队列估算分 + } + } + ] +``` + +`` +GET /fapi/v3/adlQuantile +`` + + +**权重:** 5 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +------ | ------ | -------- | ------ +symbol | STRING | NO + +* 每30秒更新数据 + +* 队列分数0,1,2,3,4,分数越高说明在ADL队列中的位置越靠前 + +* 对于单向持仓模式或者是逐仓状态下的双向持仓模式的交易对,会返回 "LONG", "SHORT" 和 "BOTH" 分别表示不同持仓方向上持仓的adl队列分数 + +* 对于全仓状态下的双向持仓模式的交易对,会返回 "LONG", "SHORT" 和 "HEDGE", 其中"HEDGE"的存在仅作为标记;其中如果多空均有持仓的情况下,"LONG"和"SHORT"返回共同计算后相同的队列分数。 + + +## 用户强平单历史 (USER_DATA) + + +> **响应:** + +```javascript +[ + { + "orderId": 6071832819, + "symbol": "BTCUSDT", + "status": "FILLED", + "clientOrderId": "autoclose-1596107620040000020", + "price": "10871.09", + "avgPrice": "10913.21000", + "origQty": "0.001", + "executedQty": "0.001", + "cumQuote": "10.91321", + "timeInForce": "IOC", + "type": "LIMIT", + "reduceOnly": false, + "closePosition": false, + "side": "SELL", + "positionSide": "BOTH", + "stopPrice": "0", + "workingType": "CONTRACT_PRICE", + "origType": "LIMIT", + "time": 1596107620044, + "updateTime": 1596107620087 + } + { + "orderId": 6072734303, + "symbol": "BTCUSDT", + "status": "FILLED", + "clientOrderId": "adl_autoclose", + "price": "11023.14", + "avgPrice": "10979.82000", + "origQty": "0.001", + "executedQty": "0.001", + "cumQuote": "10.97982", + "timeInForce": "GTC", + "type": "LIMIT", + "reduceOnly": false, + "closePosition": false, + "side": "BUY", + "positionSide": "SHORT", + "stopPrice": "0", + "workingType": "CONTRACT_PRICE", + "origType": "LIMIT", + "time": 1596110725059, + "updateTime": 1596110725071 + } +] +``` + + +`` +GET /fapi/v3/forceOrders +`` + + +**权重:** 带symbol 20, 不带symbol 50 + +**参数:** + + 名称 | 类型 | 是否必需 | 描述 +------------- | ------ | -------- | ---------------------------------------- +symbol | STRING | NO | +autoCloseType | ENUM | NO | "LIQUIDATION": 强平单, "ADL": ADL减仓单. +startTime | LONG | NO | +endTime | LONG | NO | +limit | INT | NO | Default 50; max 100. + +* 如果没有传 "autoCloseType", 强平单和ADL减仓单都会被返回 +* 如果没有传"startTime", 只会返回"endTime"之前7天内的数据 + + + +## 用户手续费率 (USER_DATA) + +> **响应:** + +```javascript +{ + "symbol": "BTCUSDT", + "makerCommissionRate": "0.0002", // 0.02% + "takerCommissionRate": "0.0004" // 0.04% +} +``` + +`` +GET /fapi/v3/commissionRate`` + +**权重:** +20 + + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES + + + +# Websocket 账户信息推送 + + +* 本篇所列出REST接口的baseurl **https://fapi.asterdex-testnet.com** +* 用于订阅账户数据的 `listenKey` 从创建时刻起有效期为60分钟 +* 可以通过`PUT`一个`listenKey`延长60分钟有效期 +* 可以通过`DELETE`一个 `listenKey` 立即关闭当前数据流,并使该`listenKey` 无效 +* 在具有有效`listenKey`的帐户上执行`POST`将返回当前有效的`listenKey`并将其有效期延长60分钟 +* 本篇所列出的websocket接口baseurl: **wss://fstream.asterdex-testnet.com** +* 订阅账户数据流的stream名称为 **/ws/\** +* 每个链接有效期不超过24小时,请妥善处理断线重连。 +* 账户数据流的消息**不保证**严格时间序; **请使用 E 字段进行排序** +* 考虑到剧烈行情下, RESTful接口可能存在查询延迟,我们强烈建议您优先从Websocket user data stream推送的消息来获取订单,仓位等信息。 + + +## 生成listenKey (USER_STREAM) + + +> **响应:** + +```javascript +{ + "listenKey": "pqia91ma19a5s61cv6a81va65sdf19v8a65a1a5s61cv6a81va65sdf19v8a65a1" +} +``` + +`` +POST /fapi/v3/listenKey +`` + +创建一个新的user data stream,返回值为一个listenKey,即websocket订阅的stream名称。如果该帐户具有有效的`listenKey`,则将返回该`listenKey`并将其有效期延长60分钟。 + +**权重:** +1 + +**参数:** + +None + + +## 延长listenKey有效期 (USER_STREAM) + + +> **响应:** + +```javascript +{} +``` + +`` +PUT /fapi/v3/listenKey +`` + +有效期延长至本次调用后60分钟 + +**权重:** +1 + +**参数:** + +None + + + +## 关闭listenKey (USER_STREAM) + +> **响应:** + +```javascript +{} +``` + +`` +DELETE /fapi/v3/listenKey +`` + +关闭某账户数据流 + +**权重:** +1 + +**参数:** + +None + + + +## listenKey 过期推送 + +> **Payload:** + +```javascript +{ + 'e': 'listenKeyExpired', // 事件类型 + 'E': 1576653824250 // 事件时间 +} +``` + +当前连接使用的有效listenKey过期时,user data stream 将会推送此事件。 + +**注意:** + +* 此事件与websocket连接中断没有必然联系 +* 只有正在连接中的有效`listenKey`过期时才会收到此消息 +* 收到此消息后user data stream将不再更新,直到用户使用新的有效的`listenKey` + + + + +## 追加保证金通知 + +> **Payload:** + +```javascript +{ + "e":"MARGIN_CALL", // 事件类型 + "E":1587727187525, // 事件时间 + "cw":"3.16812045", // 除去逐仓仓位保证金的钱包余额, 仅在全仓 margin call 情况下推送此字段 + "p":[ // 涉及持仓 + { + "s":"ETHUSDT", // symbol + "ps":"LONG", // 持仓方向 + "pa":"1.327", // 仓位 + "mt":"CROSSED", // 保证金模式 + "iw":"0", // 若为逐仓,仓位保证金 + "mp":"187.17127", // 标记价格 + "up":"-1.166074", // 未实现盈亏 + "mm":"1.614445" // 持仓需要的维持保证金 + } + ] +} + +``` + + +* 当用户持仓风险过高,会推送此消息。 +* 此消息仅作为风险指导信息,不建议用于投资策略。 +* 在大波动市场行情下,不排除此消息发出的同时用户仓位已被强平的可能。 + + + + +## Balance和Position更新推送 + +> **Payload:** + +```javascript +{ + "e": "ACCOUNT_UPDATE", // 事件类型 + "E": 1564745798939, // 事件时间 + "T": 1564745798938 , // 撮合时间 + "a": // 账户更新事件 + { + "m":"ORDER", // 事件推出原因 + "B":[ // 余额信息 + { + "a":"USDT", // 资产名称 + "wb":"122624.12345678", // 钱包余额 + "cw":"100.12345678", // 除去逐仓仓位保证金的钱包余额 + "bc":"50.12345678" // 除去盈亏与交易手续费以外的钱包余额改变量 + }, + { + "a":"BUSD", + "wb":"1.00000000", + "cw":"0.00000000", + "bc":"-49.12345678" + } + ], + "P":[ + { + "s":"BTCUSDT", // 交易对 + "pa":"0", // 仓位 + "ep":"0.00000", // 入仓价格 + "cr":"200", // (费前)累计实现损益 + "up":"0", // 持仓未实现盈亏 + "mt":"isolated", // 保证金模式 + "iw":"0.00000000", // 若为逐仓,仓位保证金 + "ps":"BOTH" // 持仓方向 + }, + { + "s":"BTCUSDT", + "pa":"20", + "ep":"6563.66500", + "cr":"0", + "up":"2850.21200", + "mt":"isolated", + "iw":"13200.70726908", + "ps":"LONG" + }, + { + "s":"BTCUSDT", + "pa":"-10", + "ep":"6563.86000", + "cr":"-45.04000000", + "up":"-1423.15600", + "mt":"isolated", + "iw":"6570.42511771", + "ps":"SHORT" + } + ] + } +} +``` + +账户更新事件的 event type 固定为 `ACCOUNT_UPDATE` + +* 当账户信息有变动时,会推送此事件: + * 仅当账户信息有变动时(包括资金、仓位、保证金模式等发生变化),才会推送此事件; + * 订单状态变化没有引起账户和持仓变化的,不会推送此事件; + * 每次因持仓变动推送的position 信息,仅包含当前持仓不为0或逐仓仓位保证金不为0的symbol position。 + +* "FUNDING FEE" 引起的资金余额变化,仅推送简略事件: + * 当用户某**全仓**持仓发生"FUNDING FEE"时,事件`ACCOUNT_UPDATE`将只会推送相关的用户资产余额信息`B`(仅推送FUNDING FEE 发生相关的资产余额信息),而不会推送任何持仓信息`P`。 + * 当用户某**逐仓**仓持仓发生"FUNDING FEE"时,事件`ACCOUNT_UPDATE`将只会推送相关的用户资产余额信息`B`(仅推送"FUNDING FEE"所使用的资产余额信息),和相关的持仓信息`P`(仅推送这笔"FUNDING FEE"发生所在的持仓信息),其余持仓信息不会被推送。 + +* 字段"m"代表了事件推出的原因,包含了以下可能类型: + * DEPOSIT + * WITHDRAW + * ORDER + * FUNDING_FEE + * WITHDRAW_REJECT + * ADJUSTMENT + * INSURANCE_CLEAR + * ADMIN_DEPOSIT + * ADMIN_WITHDRAW + * MARGIN_TRANSFER + * MARGIN_TYPE_CHANGE + * ASSET_TRANSFER + * OPTIONS_PREMIUM_FEE + * OPTIONS_SETTLE_PROFIT + * AUTO_EXCHANGE + +* 字段"bc"代表了钱包余额的改变量,即 balance change,但注意其不包含仓位盈亏及交易手续费。 + +## 订单/交易 更新推送 + +> **Payload:** + +```javascript +{ + + "e":"ORDER_TRADE_UPDATE", // 事件类型 + "E":1568879465651, // 事件时间 + "T":1568879465650, // 撮合时间 + "o":{ + "s":"BTCUSDT", // 交易对 + "c":"TEST", // 客户端自定订单ID + // 特殊的自定义订单ID: + // "autoclose-"开头的字符串: 系统强平订单 + // "adl_autoclose": ADL自动减仓订单 + "S":"SELL", // 订单方向 + "o":"TRAILING_STOP_MARKET", // 订单类型 + "f":"GTC", // 有效方式 + "q":"0.001", // 订单原始数量 + "p":"0", // 订单原始价格 + "ap":"0", // 订单平均价格 + "sp":"7103.04", // 条件订单触发价格,对追踪止损单无效 + "x":"NEW", // 本次事件的具体执行类型 + "X":"NEW", // 订单的当前状态 + "i":8886774, // 订单ID + "l":"0", // 订单末次成交量 + "z":"0", // 订单累计已成交量 + "L":"0", // 订单末次成交价格 + "N": "USDT", // 手续费资产类型 + "n": "0", // 手续费数量 + "T":1568879465651, // 成交时间 + "t":0, // 成交ID + "b":"0", // 买单净值 + "a":"9.91", // 卖单净值 + "m": false, // 该成交是作为挂单成交吗? + "R":false , // 是否是只减仓单 + "wt": "CONTRACT_PRICE", // 触发价类型 + "ot": "TRAILING_STOP_MARKET", // 原始订单类型 + "ps":"LONG" // 持仓方向 + "cp":false, // 是否为触发平仓单; 仅在条件订单情况下会推送此字段 + "AP":"7476.89", // 追踪止损激活价格, 仅在追踪止损单时会推送此字段 + "cr":"5.0", // 追踪止损回调比例, 仅在追踪止损单时会推送此字段 + "rp":"0" // 该交易实现盈亏 + + } + +} +``` + + +当有新订单创建、订单有新成交或者新的状态变化时会推送此类事件 +事件类型统一为 `ORDER_TRADE_UPDATE` + +**订单方向** + +* BUY 买入 +* SELL 卖出 + +**订单类型** + +* MARKET 市价单 +* LIMIT 限价单 +* STOP 止损单 +* TAKE_PROFIT 止盈单 +* LIQUIDATION 强平单 + +**本次事件的具体执行类型** + +* NEW +* CANCELED 已撤 +* CALCULATED +* EXPIRED 订单失效 +* TRADE 交易 + + +**订单状态** + +* NEW +* PARTIALLY_FILLED +* FILLED +* CANCELED +* EXPIRED +* NEW_INSURANCE 风险保障基金(强平) +* NEW_ADL 自动减仓序列(强平) + +**有效方式:** + +* GTC +* IOC +* FOK +* GTX + + +## 杠杆倍数等账户配置 更新推送 + +> **Payload:** + +```javascript +{ + "e":"ACCOUNT_CONFIG_UPDATE", // 事件类型 + "E":1611646737479, // 事件时间 + "T":1611646737476, // 撮合时间 + "ac":{ + "s":"BTCUSDT", // 交易对 + "l":25 // 杠杆倍数 + + } +} + +``` + +> **Or** + +```javascript +{ + "e":"ACCOUNT_CONFIG_UPDATE", // 事件类型 + "E":1611646737479, // 事件时间 + "T":1611646737476, // 撮合时间 + "ai":{ // 用户账户配置 + "j":true, // 联合保证金状态 + "f":true, // 指定币种抵扣手续费 + "d":true // 持仓模式 true 为双向持仓模式, false为单向持仓模式 + } +} +``` + +当账户配置发生变化时会推送此类事件类型统一为`ACCOUNT_CONFIG_UPDATE ` + +当交易对杠杆倍数发生变化时推送消息体会包含对象`ac`表示交易对账户配置,其中`s`代表具体的交易对,`l`代表杠杆倍数 + +当用户联合保证金状态发生变化时推送消息体会包含对象`ai`表示用户账户配置,其中`j`代表用户联合保证金状态 + +# 错误代码 + +> error JSON payload: + +```javascript +{ + "code":-1121, + "msg":"Invalid symbol." +} +``` + +错误由两部分组成:错误代码和消息。 代码是通用的,但是消息可能会有所不同。 + + +## 10xx - 常规服务器或网络问题 +> -1000 UNKNOWN + * An unknown error occured while processing the request. + * 处理请求时发生未知错误。 + +> -1001 DISCONNECTED + * Internal error; unable to process your request. Please try again. + * 内部错误; 无法处理您的请求。 请再试一次. + +> -1002 UNAUTHORIZED + * You are not authorized to execute this request. + * 您无权执行此请求。 + +> -1003 TOO_MANY_REQUESTS + * Too many requests queued. + * 排队的请求过多。 + * Too many requests; please use the websocket for live updates. + * 请求权重过多; 请使用websocket获取最新更新。 + * Too many requests; current limit is %s requests per minute. Please use the websocket for live updates to avoid polling the API. + * 请求权重过多; 当前限制为每分钟%s请求权重。 请使用websocket进行实时更新,以避免轮询API。 + * Way too many requests; IP banned until %s. Please use the websocket for live updates to avoid bans. + * 请求权重过多; IP被禁止,直到%s。 请使用websocket进行实时更新,以免被禁。 + +> -1004 DUPLICATE_IP + * This IP is already on the white list + * IP地址已经在白名单 + +> -1005 NO_SUCH_IP + * No such IP has been white listed + * 白名单上没有此IP地址 + +> -1006 UNEXPECTED_RESP + * An unexpected response was received from the message bus. Execution status unknown. + * 从消息总线收到意外的响应。执行状态未知。 + +> -1007 TIMEOUT + * Timeout waiting for response from backend server. Send status unknown; execution status unknown. + * 等待后端服务器响应超时。 发送状态未知; 执行状态未知。 + +> -1014 UNKNOWN_ORDER_COMPOSITION + * Unsupported order combination. + * 不支持当前的下单参数组合 + +> -1015 TOO_MANY_ORDERS + * Too many new orders. + * 新订单太多。 + * Too many new orders; current limit is %s orders per %s. + * 新订单太多; 当前限制为每%s %s个订单。 + +> -1016 SERVICE_SHUTTING_DOWN + * This service is no longer available. + * 该服务不可用。 + +> -1020 UNSUPPORTED_OPERATION + * This operation is not supported. + * 不支持此操作。 + +> -1022 INVALID_SIGNATURE + * Signature for this request is not valid. + * 此请求的签名无效。 + +> -1023 START_TIME_GREATER_THAN_END_TIME + * Start time is greater than end time. + * 参数里面的开始时间在结束时间之后 + + +## 11xx - Request issues +> -1100 ILLEGAL_CHARS + * Illegal characters found in a parameter. + * 在参数中发现非法字符。 + * Illegal characters found in parameter '%s'; legal range is '%s'. + * 在参数`%s`中发现非法字符; 合法范围是`%s`。 + +> -1101 TOO_MANY_PARAMETERS + * Too many parameters sent for this endpoint. + * 为此端点发送的参数太多。 + * Too many parameters; expected '%s' and received '%s'. + * 参数太多;预期为`%s`并收到了`%s`。 + * Duplicate values for a parameter detected. + * 检测到的参数值重复。 + +> -1102 MANDATORY_PARAM_EMPTY_OR_MALFORMED + * A mandatory parameter was not sent, was empty/null, or malformed. + * 未发送强制性参数,该参数为空/空或格式错误。 + * Mandatory parameter '%s' was not sent, was empty/null, or malformed. + * 强制参数`%s`未发送,为空/空或格式错误。 + * Param '%s' or '%s' must be sent, but both were empty/null! + * 必须发送参数`%s`或`%s`,但两者均为空! + +> -1103 UNKNOWN_PARAM + * An unknown parameter was sent. + * 发送了未知参数。 + +> -1104 UNREAD_PARAMETERS + * Not all sent parameters were read. + * 并非所有发送的参数都被读取。 + * Not all sent parameters were read; read '%s' parameter(s) but was sent '%s'. + * 并非所有发送的参数都被读取; 读取了`%s`参数,但被发送了`%s`。 + +> -1105 PARAM_EMPTY + * A parameter was empty. + * 参数为空。 + * Parameter '%s' was empty. + * 参数`%s`为空。 + +> -1106 PARAM_NOT_REQUIRED + * A parameter was sent when not required. + * 发送了不需要的参数。 + * Parameter '%s' sent when not required. + * 发送了不需要参数`%s`。 + +> -1111 BAD_PRECISION + * Precision is over the maximum defined for this asset. + * 精度超过为此资产定义的最大值。 + +> -1112 NO_DEPTH + * No orders on book for symbol. + * 交易对没有挂单。 + +> -1114 TIF_NOT_REQUIRED + * TimeInForce parameter sent when not required. + * 发送的`TimeInForce`参数不需要。 + +> -1115 INVALID_TIF + * Invalid timeInForce. + * 无效的`timeInForce` + +> -1116 INVALID_ORDER_TYPE + * Invalid orderType. + * 无效订单类型。 + +> -1117 INVALID_SIDE + * Invalid side. + * 无效买卖方向。 + +> -1118 EMPTY_NEW_CL_ORD_ID + * New client order ID was empty. + * 新的客户订单ID为空。 + +> -1119 EMPTY_ORG_CL_ORD_ID + * Original client order ID was empty. + * 客户自定义的订单ID为空。 + +> -1120 BAD_INTERVAL + * Invalid interval. + * 无效时间间隔。 + +> -1121 BAD_SYMBOL + * Invalid symbol. + * 无效的交易对。 + +> -1125 INVALID_LISTEN_KEY + * This listenKey does not exist. + * 此`listenKey`不存在。 + +> -1127 MORE_THAN_XX_HOURS + * Lookup interval is too big. + * 查询间隔太大。 + * More than %s hours between startTime and endTime. + * 从开始时间到结束时间之间超过`%s`小时。 + +> -1128 OPTIONAL_PARAMS_BAD_COMBO + * Combination of optional parameters invalid. + * 可选参数组合无效。 + +> -1130 INVALID_PARAMETER + * Invalid data sent for a parameter. + * 发送的参数为无效数据。 + * Data sent for parameter '%s' is not valid. + * 发送参数`%s`的数据无效。 + +> -1136 INVALID_NEW_ORDER_RESP_TYPE + * Invalid newOrderRespType. + * 无效的 newOrderRespType。 + + +## 20xx - Processing Issues +> -2010 NEW_ORDER_REJECTED + * NEW_ORDER_REJECTED + * 新订单被拒绝 + +> -2011 CANCEL_REJECTED + * CANCEL_REJECTED + * 取消订单被拒绝 + +> -2013 NO_SUCH_ORDER + * Order does not exist. + * 订单不存在。 + +> -2014 BAD_API_KEY_FMT + * API-key format invalid. + * API-key 格式无效。 + +> -2015 REJECTED_MBX_KEY + * Invalid API-key, IP, or permissions for action. + * 无效的API密钥,IP或操作权限。 + +> -2016 NO_TRADING_WINDOW + * No trading window could be found for the symbol. Try ticker/24hrs instead. + * 找不到该交易对的交易窗口。 尝试改为24小时自动报价。 + +> -2018 BALANCE_NOT_SUFFICIENT + * Balance is insufficient. + * 余额不足 + +> -2019 MARGIN_NOT_SUFFICIEN + * Margin is insufficient. + * 杠杆账户余额不足 + +> -2020 UNABLE_TO_FILL + * Unable to fill. + * 无法成交 + +> -2021 ORDER_WOULD_IMMEDIATELY_TRIGGER + * Order would immediately trigger. + * 订单可能被立刻触发 + +> -2022 REDUCE_ONLY_REJECT + * ReduceOnly Order is rejected. + * `ReduceOnly`订单被拒绝 + +> -2023 USER_IN_LIQUIDATION + * User in liquidation mode now. + * 用户正处于被强平模式 + +> -2024 POSITION_NOT_SUFFICIENT + * Position is not sufficient. + * 持仓不足 + +> -2025 MAX_OPEN_ORDER_EXCEEDED + * Reach max open order limit. + * 挂单量达到上限 + +> -2026 REDUCE_ONLY_ORDER_TYPE_NOT_SUPPORTED + * This OrderType is not supported when reduceOnly. + * 当前订单类型不支持`reduceOnly` + +> -2027 MAX_LEVERAGE_RATIO + * Exceeded the maximum allowable position at current leverage. + * 挂单或持仓超出当前初始杠杆下的最大值 + +> -2028 MIN_LEVERAGE_RATIO + * Leverage is smaller than permitted: insufficient margin balance. + * 调整初始杠杆过低,导致可用余额不足 + +## 40xx - Filters and other Issues +> -4000 INVALID_ORDER_STATUS + * Invalid order status. + * 订单状态不正确 + +> -4001 PRICE_LESS_THAN_ZERO + * Price less than 0. + * 价格小于0 + +> -4002 PRICE_GREATER_THAN_MAX_PRICE + * Price greater than max price. + * 价格超过最大值 + +> -4003 QTY_LESS_THAN_ZERO + * Quantity less than zero. + * 数量小于0 + +> -4004 QTY_LESS_THAN_MIN_QTY + * Quantity less than min quantity. + * 数量小于最小值 + +> -4005 QTY_GREATER_THAN_MAX_QTY + * Quantity greater than max quantity. + * 数量大于最大值 + +> -4006 STOP_PRICE_LESS_THAN_ZERO + * Stop price less than zero. + * 触发价小于最小值 + +> -4007 STOP_PRICE_GREATER_THAN_MAX_PRICE + * Stop price greater than max price. + * 触发价大于最大值 + +> -4008 TICK_SIZE_LESS_THAN_ZERO + * Tick size less than zero. + * 价格精度小于0 + +> -4009 MAX_PRICE_LESS_THAN_MIN_PRICE + * Max price less than min price. + * 最大价格小于最小价格 + +> -4010 MAX_QTY_LESS_THAN_MIN_QTY + * Max qty less than min qty. + * 最大数量小于最小数量 + +> -4011 STEP_SIZE_LESS_THAN_ZERO + * Step size less than zero. + * 步进值小于0 + +> -4012 MAX_NUM_ORDERS_LESS_THAN_ZERO + * Max num orders less than zero. + * 最大订单量小于0 + +> -4013 PRICE_LESS_THAN_MIN_PRICE + * Price less than min price. + * 价格小于最小价格 + +> -4014 PRICE_NOT_INCREASED_BY_TICK_SIZE + * Price not increased by tick size. + * 价格增量不是价格精度的倍数。 + +> -4015 INVALID_CL_ORD_ID_LEN + * Client order id is not valid. + * 客户订单ID有误。 + * Client order id length should not be more than 36 chars + * 客户订单ID长度应该不多于36字符 + +> -4016 PRICE_HIGHTER_THAN_MULTIPLIER_UP + * Price is higher than mark price multiplier cap. + +> -4017 MULTIPLIER_UP_LESS_THAN_ZERO + * Multiplier up less than zero. + * 价格上限小于0 + +> -4018 MULTIPLIER_DOWN_LESS_THAN_ZERO + * Multiplier down less than zero. + * 价格下限小于0 + +> -4019 COMPOSITE_SCALE_OVERFLOW + * Composite scale too large. + +> -4020 TARGET_STRATEGY_INVALID + * Target strategy invalid for orderType '%s',reduceOnly '%b'. + * 目标策略值不适合`%s`订单状态, 只减仓`%b`。 + +> -4021 INVALID_DEPTH_LIMIT + * Invalid depth limit. + * 深度信息的`limit`值不正确。 + * '%s' is not valid depth limit. + * `%s`不是合理的深度信息的`limit`值。 + +> -4022 WRONG_MARKET_STATUS + * market status sent is not valid. + * 发送的市场状态不正确。 + +> -4023 QTY_NOT_INCREASED_BY_STEP_SIZE + * Qty not increased by step size. + * 数量的递增值不是步进值的倍数。 + +> -4024 PRICE_LOWER_THAN_MULTIPLIER_DOWN + * Price is lower than mark price multiplier floor. + +> -4025 MULTIPLIER_DECIMAL_LESS_THAN_ZERO + * Multiplier decimal less than zero. + +> -4026 COMMISSION_INVALID + * Commission invalid. + * 收益值不正确 + * `%s` less than zero. + * `%s`少于0 + * `%s` absolute value greater than `%s` + * `%s`绝对值大于`%s` + +> -4027 INVALID_ACCOUNT_TYPE + * Invalid account type. + * 账户类型不正确。 + +> -4028 INVALID_LEVERAGE + * Invalid leverage + * 杠杆倍数不正确 + * Leverage `%s` is not valid + * 杠杆`%s`不正确 + * Leverage `%s` already exist with `%s` + * 杠杆`%s`已经存在于`%s` + +> -4029 INVALID_TICK_SIZE_PRECISION + * Tick size precision is invalid. + * 价格精度小数点位数不正确。 + +> -4030 INVALID_STEP_SIZE_PRECISION + * Step size precision is invalid. + * 步进值小数点位数不正确。 + +> -4031 INVALID_WORKING_TYPE + * Invalid parameter working type + * 不正确的参数类型 + * Invalid parameter working type: `%s` + * 不正确的参数类型: `%s` + +> -4032 EXCEED_MAX_CANCEL_ORDER_SIZE + * Exceed maximum cancel order size. + * 超过可以取消的最大订单量。 + * Invalid parameter working type: `%s` + * 不正确的参数类型: `%s` + +> -4033 INSURANCE_ACCOUNT_NOT_FOUND + * Insurance account not found. + * 风险保障基金账号没找到。 + +> -4044 INVALID_BALANCE_TYPE + * Balance Type is invalid. + * 余额类型不正确。 + +> -4045 MAX_STOP_ORDER_EXCEEDED + * Reach max stop order limit. + * 达到止损单的上限。 + +> -4046 NO_NEED_TO_CHANGE_MARGIN_TYPE + * No need to change margin type. + * 不需要切换仓位模式。 + +> -4047 THERE_EXISTS_OPEN_ORDERS + * Margin type cannot be changed if there exists open orders. + * 如果有挂单,仓位模式不能切换。 + +> -4048 THERE_EXISTS_QUANTITY + * Margin type cannot be changed if there exists position. + * 如果有仓位,仓位模式不能切换。 + +> -4049 ADD_ISOLATED_MARGIN_REJECT + * Add margin only support for isolated position. + +> -4050 CROSS_BALANCE_INSUFFICIENT + * Cross balance insufficient. + * 全仓余额不足。 + +> -4051 ISOLATED_BALANCE_INSUFFICIENT + * Isolated balance insufficient. + * 逐仓余额不足。 + +> -4052 NO_NEED_TO_CHANGE_AUTO_ADD_MARGIN + * No need to change auto add margin. + +> -4053 AUTO_ADD_CROSSED_MARGIN_REJECT + * Auto add margin only support for isolated position. + * 自动增加保证金只适用于逐仓。 + +> -4054 ADD_ISOLATED_MARGIN_NO_POSITION_REJECT + * Cannot add position margin: position is 0. + * 不能增加逐仓保证金: 持仓为0 + +> -4055 AMOUNT_MUST_BE_POSITIVE + * Amount must be positive. + * 数量必须是正整数 + +> -4056 INVALID_API_KEY_TYPE + * Invalid api key type. + * API key的类型不正确 + +> -4057 INVALID_RSA_PUBLIC_KEY + * Invalid api public key + * API key不正确 + +> -4058 MAX_PRICE_TOO_LARGE + * maxPrice and priceDecimal too large,please check. + * maxPrice和priceDecimal太大,请检查。 + +> -4059 NO_NEED_TO_CHANGE_POSITION_SIDE + * No need to change position side. + * 无需变更仓位方向 + +> -4060 INVALID_POSITION_SIDE + * Invalid position side. + * 仓位方向不正确。 + +> -4061 POSITION_SIDE_NOT_MATCH + * Order's position side does not match user's setting. + * 订单的持仓方向和用户设置不一致。 + +> -4062 REDUCE_ONLY_CONFLICT + * Invalid or improper reduceOnly value. + * 仅减仓的设置不正确。 + +> -4063 INVALID_OPTIONS_REQUEST_TYPE + * Invalid options request type + * 无效的期权请求类型 + +> -4064 INVALID_OPTIONS_TIME_FRAME + * Invalid options time frame + * 无效的期权时间窗口 + +> -4065 INVALID_OPTIONS_AMOUNT + * Invalid options amount + * 无效的期权数量 + +> -4066 INVALID_OPTIONS_EVENT_TYPE + * Invalid options event type + * 无效的期权事件类型 + +> -4067 POSITION_SIDE_CHANGE_EXISTS_OPEN_ORDERS + * Position side cannot be changed if there exists open orders. + * 如果有挂单,无法修改仓位方向。 + +> -4068 POSITION_SIDE_CHANGE_EXISTS_QUANTITY + * Position side cannot be changed if there exists position. + * 如果有仓位, 无法修改仓位方向。 + +> -4069 INVALID_OPTIONS_PREMIUM_FEE + * Invalid options premium fee + * 无效的期权费 + +> -4070 INVALID_CL_OPTIONS_ID_LEN + * Client options id is not valid. + * 客户的期权ID不合法 + * Client options id length should be less than 32 chars + * 客户的期权ID长度应该小于32个字符 + +> -4071 INVALID_OPTIONS_DIRECTION + * Invalid options direction + * 期权的方向无效 + +> -4072 OPTIONS_PREMIUM_NOT_UPDATE + * premium fee is not updated, reject order + * 期权费没有更新 + +> -4073 OPTIONS_PREMIUM_INPUT_LESS_THAN_ZERO + * input premium fee is less than 0, reject order + * 输入的期权费小于0 + +> -4074 OPTIONS_AMOUNT_BIGGER_THAN_UPPER + * Order amount is bigger than upper boundary or less than 0, reject order + +> -4075 OPTIONS_PREMIUM_OUTPUT_ZERO + * output premium fee is less than 0, reject order + +> -4076 OPTIONS_PREMIUM_TOO_DIFF + * original fee is too much higher than last fee + * 期权的费用比之前的费用高 + +> -4077 OPTIONS_PREMIUM_REACH_LIMIT + * place order amount has reached to limit, reject order + * 下单的数量达到上限 + +> -4078 OPTIONS_COMMON_ERROR + * options internal error + * 期权内部系统错误 + +> -4079 INVALID_OPTIONS_ID + * invalid options id + * invalid options id: %s + * duplicate options id %d for user %d + * 期权ID无效 + +> -4080 OPTIONS_USER_NOT_FOUND + * user not found + * user not found with id: %s + * 用户找不到 + +> -4081 OPTIONS_NOT_FOUND + * options not found + * options not found with id: %s + * 期权找不到 + +> -4082 INVALID_BATCH_PLACE_ORDER_SIZE + * Invalid number of batch place orders. + * Invalid number of batch place orders: %s + * 批量下单的数量不正确 + +> -4083 PLACE_BATCH_ORDERS_FAIL + * Fail to place batch orders. + * 无法批量下单 + +> -4084 UPCOMING_METHOD + * Method is not allowed currently. Upcoming soon. + * 方法不支持 + +> -4085 INVALID_NOTIONAL_LIMIT_COEF + * Invalid notional limit coefficient + * 期权的有限系数不正确 + +> -4086 INVALID_PRICE_SPREAD_THRESHOLD + * Invalid price spread threshold + * 无效的价差阀值 + +> -4087 REDUCE_ONLY_ORDER_PERMISSION + * User can only place reduce only order + * 用户只能下仅减仓订单 + +> -4088 NO_PLACE_ORDER_PERMISSION + * User can not place order currently + * 用户当前不能下单 + +> -4104 INVALID_CONTRACT_TYPE + * Invalid contract type + * 无效的合约类型 + +> -4114 INVALID_CLIENT_TRAN_ID_LEN + * clientTranId is not valid + * clientTranId不正确 + * Client tran id length should be less than 64 chars + * 客户的tranId长度应该小于64个字符 + +> -4115 DUPLICATED_CLIENT_TRAN_ID + * clientTranId is duplicated + * clientTranId重复 + * Client tran id should be unique within 7 days + * 客户的tranId应在7天内唯一 + +> -4118 REDUCE_ONLY_MARGIN_CHECK_FAILED + * ReduceOnly Order Failed. Please check your existing position and open orders + * 仅减仓订单失败。请检查现有的持仓和挂单 + +> -4131 MARKET_ORDER_REJECT + * The counterparty's best price does not meet the PERCENT_PRICE filter limit + * 交易对手的最高价格未达到PERCENT_PRICE过滤器限制 + +> -4135 INVALID_ACTIVATION_PRICE + * Invalid activation price + * 无效的激活价格 + +> -4137 QUANTITY_EXISTS_WITH_CLOSE_POSITION + * Quantity must be zero with closePosition equals true + * 数量必须为0,当closePosition为true时 + +> -4138 REDUCE_ONLY_MUST_BE_TRUE + * Reduce only must be true with closePosition equals true + * Reduce only 必须为true,当closePosition为true时 + +> -4139 ORDER_TYPE_CANNOT_BE_MKT + * Order type can not be market if it's unable to cancel + * 订单类型不能为市价单如果不能取消 + +> -4140 INVALID_OPENING_POSITION_STATUS + * Invalid symbol status for opening position + * 无效的交易对状态 + +> -4141 SYMBOL_ALREADY_CLOSED + * Symbol is closed + * 交易对已下架 + +> -4142 STRATEGY_INVALID_TRIGGER_PRICE + * REJECT: take profit or stop order will be triggered immediately + * 拒绝:止盈止损单将立即被触发 + +> -4144 INVALID_PAIR + * Invalid pair + * 无效的pair + +> -4161 ISOLATED_LEVERAGE_REJECT_WITH_POSITION + * Leverage reduction is not supported in Isolated Margin Mode with open positions + * 逐仓仓位模式下无法降低杠杆 + +> -4164 MIN_NOTIONAL + * Order's notional must be no smaller than 5.0 (unless you choose reduce only) + * 订单的名义价值不可以小于5,除了使用reduce only + * Order's notional must be no smaller than %s (unless you choose reduce only) + * 订单的名义价值不可以小于`%s`,除了使用reduce only + +> -4165 INVALID_TIME_INTERVAL + * Invalid time interval + * 无效的间隔 + * Maximum time interval is %s days + * 最大的时间间隔为 `%s` 天 + +> -4183 PRICE_HIGHTER_THAN_STOP_MULTIPLIER_UP + * Price is higher than stop price multiplier cap. + * 止盈止损订单价格不应高于触发价与报价乘数上限的乘积 + * Limit price can't be higher than %s. + * 止盈止损订单价格不应高于 `%s` + +> -4184 PRICE_LOWER_THAN_STOP_MULTIPLIER_DOWN + * Price is lower than stop price multiplier floor. + * 止盈止损订单价格不应低于触发价与报价乘数下限的乘积 + * Limit price can't be lower than %s. + * 止盈止损订单价格不应低于 `%s` + diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-spot-api-testnet_CN.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-spot-api-testnet_CN.md" new file mode 100644 index 0000000..f2e017e --- /dev/null +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-spot-api-testnet_CN.md" @@ -0,0 +1,2668 @@ +# 基本信息 +## API 基本信息 +* 本篇列出接口的baseurl: **https://sapi.asterdex-testnet.com** +* 所有接口的响应都是 JSON 格式。 +* 所有时间、时间戳均为UNIX时间,单位为**毫秒**。 + +## 访问限制 +### 访问限制基本信息 + +* 在 `/api/v3/exchangeInfo` `rateLimits` 数组中包含与交易的有关REQUEST_WEIGHT和ORDERS速率限制相关的对象。这些在 `限制种类 (rateLimitType)` 下的 `枚举定义` 部分中进一步定义。 +* 违反任何一个速率限制时,将返回429。 + +### IP 访问限制 +* 每个请求的回报中包含一个`X-MBX-USED-WEIGHT-(intervalNum)(intervalLetter)`的头,其中包含当前IP所有请求的已使用权重。 +* 每一个接口均有一个相应的权重(weight),有的接口根据参数不同可能拥有不同的权重。越消耗资源的接口权重就会越大。 +* 收到429时,您有责任停止发送请求,不得滥用API。 +* **收到429后仍然继续违反访问限制,会被封禁IP,并收到418错误码** +* 频繁违反限制,封禁时间会逐渐延长,**从最短2分钟到最长3天**。 +* `Retry-After`的头会与带有418或429的响应发送,并且会给出**以秒为单位**的等待时长(如果是429)以防止禁令,或者如果是418,直到禁令结束。 +* **访问限制是基于IP的,而不是API Key** + + + + +### 下单频率限制 +* 每个成功的下单回报将包含一个`X-MBX-ORDER-COUNT-(intervalNum)(intervalLetter)`的头,其中包含当前账户已用的下单限制数量。 +* 当下单数超过限制时,会收到带有429但不含`Retry-After`头的响应。请检查 `GET api/v3/exchangeInfo` 的下单频率限制 (rateLimitType = ORDERS) 并等待封禁时间结束。 +* 被拒绝或不成功的下单并不保证回报中包含以上头内容。 +* **下单频率限制是基于每个账户计数的。** + +### WEB SOCKET 连接限制 + +* Websocket服务器每秒最多接受5个消息。消息包括: + * PING帧 + * PONG帧 + * JSON格式的消息, 比如订阅, 断开订阅. +* 如果用户发送的消息超过限制,连接会被断开连接。反复被断开连接的IP有可能被服务器屏蔽。 +* 单个连接最多可以订阅 **1024** 个Streams。 + + +## 接口鉴权类型 +* 每个接口都有自己的鉴权类型,鉴权类型决定了访问时应当进行何种鉴权 +* 如果需要鉴权,应当在请求体中添加signer + +鉴权类型 | 描述 +------------ | ------------ +NONE | 不需要鉴权的接口 +TRADE | 需要有效的signer和签名 +USER_DATA | 需要有效的signer和签名 +USER_STREAM | 需要有效的signer和签名 +MARKET_DATA | 不需要鉴权的接口 + + +### POST /api/v3/order 的示例 + +#### 示例 : 以下参数为api注册信息,user,signer,privateKey仅供示范(privateKey为signer的私钥) + + +Key | Value | Desc +------------ | ------------ | ------------ +user | 0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e | 登陆钱包地址 +signer | 0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0 | [点击这里获取](https://www.asterdex-testnet.com/zh-CN/api-wallet) +privateKey | 0x4fd0a42218f3eae43a6ce26d22544e986139a01e5b34a62db53757ffca81bae1 | [点击这里获取](https://www.asterdex-testnet.com/zh-CN/api-wallet) + +#### 示例 : nonce参数为当前系统微秒值,超过系统时间,或者落后系统时间超过5s为非法请求 +```python +#python +nonce = math.trunc(time.time()*1000000) +print(nonce) +#1748310859508867 +``` +```java +//java +Instant now = Instant.now(); +long microsecond = now.getEpochSecond() * 1000000 + now.getNano() / 1000; +``` + +#### 示例 : 下单 (方法以python为例) + +```python +import time +import urllib +import threading + +import requests +from eth_account.messages import encode_structured_data +from eth_account import Account + +typed_data = { + "types": { + "EIP712Domain": [ + {"name": "name", "type": "string"}, + {"name": "version", "type": "string"}, + {"name": "chainId", "type": "uint256"}, + {"name": "verifyingContract", "type": "address"} + ], + "Message": [ + { "name": "msg", "type": "string" } + ] + }, + "primaryType": "Message", + "domain": { + "name": "AsterSignTransaction", + "version": "1", + "chainId": 714, + "verifyingContract": "0x0000000000000000000000000000000000000000" + }, + "message": { + "msg": "$msg" + } +} + +headers = { + 'Content-Type': 'application/x-www-form-urlencoded', + 'User-Agent': 'PythonApp/1.0' +} +host = 'https://sapi.asterdex-testnet.com' + +# config your user and agent info here +user = '*' +signer = '*' +private_key = "*" + +place_order = {"url":"/api/v3/order","method":"POST","params":{"symbol": "ASTERUSDT", "type": "LIMIT", "side": "BUY", + "timeInForce": "GTC", "quantity": "100", "price": "0.4"}} +_last_ms = 0 +_i = 0 +_nonce_lock = threading.Lock() + +def get_nonce(): + global _last_ms, _i + with _nonce_lock: + now_ms = int(time.time()) + + if now_ms == _last_ms: + _i += 1 + else: + _last_ms = now_ms + _i = 0 + + return now_ms * 1_000_000 + _i + +def send_by_url(api) : + my_dict = api['params'] + url = host + api['url'] + + my_dict['nonce'] = str(get_nonce()) + my_dict['user'] = user + my_dict['signer'] = signer + + param = urllib.parse.urlencode(my_dict) + print(param) + typed_data['message']['msg'] = param + message = encode_structured_data(typed_data) + signed = Account.sign_message(message, private_key=private_key) + + url = url + '?' + param + '&signature=' + signed.signature.hex() + print(url) + res = requests.post(url, headers=headers) + + print(res.text) + +def send_by_body(api) : + my_dict = api['params'] + url = host +api['url'] + my_dict['nonce'] = str(get_nonce()) + my_dict['user'] = user + my_dict['signer'] = signer + + param = urllib.parse.urlencode(my_dict) + typed_data['message']['msg'] = param + message = encode_structured_data(typed_data) + + signed = Account.sign_message(message, private_key=private_key) + print(signed.signature.hex()) + + my_dict['signature'] = signed.signature.hex() + + print(my_dict) + res = requests.post(url, data=my_dict, headers=headers) + + print(res.text) + +if __name__ == '__main__': + send_by_url(place_order) + # send_by_body(place_order) + +``` + +## 公开 API 参数 +### 术语 + +这里的术语适用于全部文档,建议特别是新手熟读,也便于理解。 + +* `base asset` 指一个交易对的交易对象,即写在靠前部分的资产名, 比如`BTCUSDT`, `BTC`是`base asset`。 +* `quote asset` 指一个交易对的定价资产,即写在靠后部分的资产名, 比如`BTCUSDT`, `USDT`是`quote asset`。 + +### 枚举定义 +**交易对状态 (状态 status):** + +* TRADING 交易中 + + +**交易对类型:** + +* SPOT 现货 + +**订单状态 (状态 status):** + +状态 | 描述 +-----------| -------------- +`NEW` | 订单被交易引擎接受 +`PARTIALLY_FILLED`| 部分订单被成交 +`FILLED` | 订单完全成交 +`CANCELED` | 用户撤销了订单 +`REJECTED` | 订单没有被交易引擎接受,也没被处理 +`EXPIRED` | 订单被交易引擎取消, 比如
LIMIT FOK 订单没有成交
市价单没有完全成交
交易所维护期间被取消的订单 + + +**订单类型 (orderTypes, type):** + +* LIMIT 限价单 +* MARKET 市价单 +* STOP 限价止损单 +* TAKE_PROFIT 限价止盈单 +* STOP_MARKET 市价止损单 +* TAKE_PROFIT_MARKET 市价止盈单 + +**订单返回类型 (newOrderRespType):** + +* ACK +* RESULT +* FULL + +**订单方向 (方向 side):** + +* BUY 买入 +* SELL 卖出 + +**有效方式 (timeInForce):** + +这里定义了订单多久能够失效 + +Status | Description +-----------| -------------- +`GTC` | 成交为止
订单会一直有效,直到被成交或者取消。 +`IOC` | 无法立即成交的部分就撤销
订单在失效前会尽量多的成交。 +`FOK` | 无法全部立即成交就撤销
如果无法全部成交,订单会失效。 +`GTX` | 直到挂单成交
限价只挂单。 + +**K线间隔:** + +m -> 分钟; h -> 小时; d -> 天; w -> 周; M -> 月 + +* 1m +* 3m +* 5m +* 15m +* 30m +* 1h +* 2h +* 4h +* 6h +* 8h +* 12h +* 1d +* 3d +* 1w +* 1M + +**限制种类 (rateLimitType)** + +> REQUEST_WEIGHT +```json + { + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200 + } +``` + +> ORDERS +```json + { + "rateLimitType": "ORDERS", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 100 + } +``` + + +* REQUEST_WEIGHT 单位时间请求权重之和上限 + +* ORDERS 单位时间下单次数限制 + + +**限制间隔 (interval)** + +* MINUTE 分 + +--- +## 过滤器 +过滤器,即Filter,定义了一系列交易规则。 +共有两类,分别是针对交易对的过滤器`symbol filters`,和针对整个交易所的过滤器`exchange filters`(暂不支持) + +### 交易对过滤器   + +#### PRICE_FILTER 价格过滤器 + +> **/exchangeInfo 响应中的格式:** +```javascript + { + "minPrice": "556.72", + "maxPrice": "4529764", + "filterType": "PRICE_FILTER", + "tickSize": "0.01"   + } +``` + +`价格过滤器` 用于检测订单中 `price` 参数的合法性。包含以下三个部分: + +* `minPrice` 定义了 `price`/`stopPrice` 允许的最小值。 +* `maxPrice` 定义了 `price`/`stopPrice` 允许的最大值。 +* `tickSize` 定义了 `price`/`stopPrice` 的步进间隔,即price必须等于minPrice+(tickSize的整数倍) + +以上每一项均可为0,为0时代表这一项不再做限制。 + +逻辑伪代码如下: + +* `price` >= `minPrice` +* `price` <= `maxPrice` +* (`price`-`minPrice`) % `tickSize` == 0 + + +#### PERCENT_PRICE 价格振幅过滤器 + +> **/exchangeInfo 响应中的格式:** +```javascript + { + "multiplierDown": "0.9500", + "multiplierUp": "1.0500", + "multiplierDecimal": "4", + "filterType": "PERCENT_PRICE" +  } +``` + +`PERCENT_PRICE`过滤器基于指数价格来定义价格的有效范围。 + +为了通过"价格百分比","价格"必须符合以下条件: + +* `price` <=`indexPrice` *`multiplierUp` +* `price`> =`indexPrice` *`multiplierDown` + + +#### LOT_SIZE 订单尺寸 + +> **/exchangeInfo 响应中的格式:** +```javascript + { + "stepSize": "0.00100000", +   "filterType": "LOT_SIZE", + "maxQty": "100000.00000000", +   "minQty": "0.00100000" + } +``` + +Lots是拍卖术语,`LOT_SIZE` 过滤器对订单中的 `quantity` 也就是数量参数进行合法性检查。包含三个部分: + +* `minQty` 表示 `quantity` 允许的最小值。 +* `maxQty` 表示 `quantity` 允许的最大值。 +* `stepSize` 表示 `quantity` 允许的步进值。 + +逻辑伪代码如下: + +* `quantity` >= `minQty` +* `quantity` <= `maxQty` +* (`quantity`-`minQty`) % `stepSize` == 0 + + + + +#### MARKET_LOT_SIZE 市价订单尺寸 + +> ***/exchangeInfo 响应中的格式:** +```javascript + { + "stepSize": "0.00100000", +   "filterType": "MARKET_LOT_SIZE" + "maxQty": "100000.00000000", + "minQty": "0.00100000" + } +``` + + +`MARKET_LOT_SIZE`过滤器为交易对上的`MARKET`订单定义了`数量`(即拍卖中的"手数")规则。 共有3部分: + +* `minQty`定义了允许的最小`quantity`。 +* `maxQty`定义了允许的最大数量。 +* `stepSize`定义了可以增加/减少数量的间隔。 + +为了通过`market lot size`,`quantity`必须满足以下条件: + +* `quantity` >= `minQty` +* `quantity` <= `maxQty` +* (`quantity`-`minQty`) % `stepSize` == 0 + + + + + + + + + + +# 行情接口 + +## Noop + +> **Response:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +``POST /api/v3/noop`` + +通过此请求,可以高效取消已发送但仍在队列中且尚未完成链上操作的交易(Nonce需与该请求一致,不保证成功) + +**Weight:** +1 + +## 测试服务器连通性 +> **响应** +```javascript +{} +``` +`` +GET /api/v3/ping +`` + +测试能否联通 Rest API。 + +**权重:** +1 + +**参数:** +NONE + + +## 获取服务器时间 +> **响应** +```javascript +{ + "serverTime": 1499827319559 +} +``` +`` +GET /api/v3/time +`` + +测试能否联通 Rest API 并获取服务器时间。 + +**权重:** +1 + +**参数:** +NONE + + +## 交易规范信息 + +> **响应** + +```javascript     +{ + "timezone": "UTC", + "serverTime": 1756197279679, + "rateLimits": [{ + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 6000 + }, + { + "rateLimitType": "ORDERS", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 6000 + }, + { + "rateLimitType": "ORDERS", + "interval": "SECOND", + "intervalNum": 10, + "limit": 300 + } + ], + "exchangeFilters": [], + "assets": [{ + "asset": "USD" + }, { + "asset": "USDT" + }, + { + "asset": "BNB" + } + ], + "symbols": [{ + "status": "TRADING", + "baseAsset": "BNB", + "quoteAsset": "USDT", + "pricePrecision": 8, + "quantityPrecision": 8, + "baseAssetPrecision": 8, + "quotePrecision": 8, + "filters": [{ + "minPrice": "0.01000000", + "maxPrice": "100000", + "filterType": "PRICE_FILTER", + "tickSize": "0.01000000" + }, + { + "stepSize": "0.00100000", + "filterType": "LOT_SIZE", + "maxQty": "1000", + "minQty": "1" + }, + { + "stepSize": "0.00100000", + "filterType": "MARKET_LOT_SIZE", + "maxQty": "900000", + "minQty": "0.00100000" + }, + { + "limit": 200, + "filterType": "MAX_NUM_ORDERS" + }, + { + "minNotional": "5", + "filterType": "MIN_NOTIONAL" + }, + { + "maxNotional": "100", + "filterType": "MAX_NOTIONAL" + }, + { + "maxNotional": "100", + "minNotional": "5", + "avgPriceMins": 5, + "applyMinToMarket": true, + "filterType": "NOTIONAL", + "applyMaxToMarket": true + }, + { + "multiplierDown": "0", + "multiplierUp": "5", + "multiplierDecimal": "0", + "filterType": "PERCENT_PRICE" + }, + { + "bidMultiplierUp": "5", + "askMultiplierUp": "5", + "bidMultiplierDown": "0", + "avgPriceMins": 5, + "multiplierDecimal": "0", + "filterType": "PERCENT_PRICE_BY_SIDE", + "askMultiplierDown": "0" + } + ], + "orderTypes": [ + "LIMIT", + "MARKET", + "STOP", + "STOP_MARKET", + "TAKE_PROFIT", + "TAKE_PROFIT_MARKET" + ], + "timeInForce": [ + "GTC", + "IOC", + "FOK", + "GTX", + "HIDDEN" + ], + "symbol": "BNBUSDT", + "ocoAllowed": false + }] +} +``` + +`` +GET /api/v3/exchangeInfo +`` + +获取交易规则和交易对信息。 + +**权重:** +1 + +**参数:** +无 + + +## 深度信息 + +> **响应** + +```javascript +{ + "lastUpdateId": 1027024, + "E":1589436922972, // 消息时间 + "T":1589436922959, // 撮合引擎时间 + "bids": [ + [ + "4.00000000", // 价位 + "431.00000000" // 挂单量 + ] + ], + "asks": [ + [ + "4.00000200", + "12.00000000" + ] + ] +} +``` +`` +GET /api/v3/depth +`` + +**权重:** + +基于限制调整: + +限制 | 权重 +------------ | ------------ +5, 10, 20, 50 | 2 +100 | 5 +500 | 10 +1000 | 20 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +limit | INT | NO | 默认 100. 可选值:[5, 10, 20, 50, 100, 500, 1000] + + +## 近期成交列表 + +> **响应** + +```javascript +[ + { + "id": 657, + "price": "1.01000000", + "qty": "5.00000000", + "baseQty": "4.95049505", + "time": 1755156533943, + "isBuyerMaker": false + } +] +``` +`` +GET /api/v3/trades +`` + +获取近期成交 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +limit | INT | NO | 默认 500;最大1000 + + +## 查询历史成交 (MARKET_DATA) + +> **响应** + +```javascript +[ + { + "id": 1140, + "price": "1.10000000", + "qty": "7.27200000", + "baseQty": "6.61090909", + "time": 1756094288700, + "isBuyerMaker": false + } +] +``` +`` +GET /api/v3/historicalTrades +`` + +获取历史成交。 + +**权重:** +20 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +limit | INT | NO | 默认 500; 最大值 1000. +fromId | LONG | NO | 从哪一条成交id开始返回. 缺省返回最近的成交记录。 + + +## 近期成交(归集) + +> **响应** + +```javascript +[ + { + "a": 26129, // 归集成交ID + "p": "0.01633102", // 成交价 + "q": "4.70443515", // 成交量 + "f": 27781, // 被归集的首个成交ID + "l": 27781, // 被归集的末个成交ID + "T": 1498793709153, // 成交时间 + "m": true, // 是否为主动卖出单 + } +] +``` +`` +GET /api/v3/aggTrades +`` + +归集交易与逐笔交易的区别在于,同一价格、同一方向、同一时间的trade会被聚合为一条 + +**权重:** +20 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +fromId | LONG | NO | 从包含fromId的成交id开始返回结果 +startTime | LONG | NO | 从该时刻之后的成交记录开始返回结果 +endTime | LONG | NO | 返回该时刻为止的成交记录 +limit | INT | NO | 默认 500; 最大 1000. +* 如果发送startTime和endTime,间隔必须小于一小时。 +* 如果没有发送任何筛选参数(fromId, startTime,endTime),默认返回最近的成交记录 + + +## K线数据 + +> **响应** +```javascript +[ + [ + 1499040000000, // 开盘时间 + "0.01634790", // 开盘价 + "0.80000000", // 最高价 + "0.01575800", // 最低价 + "0.01577100", // 收盘价(当前K线未结束的即为最新价) + "148976.11427815", // 成交量 + 1499644799999, // 收盘时间 + "2434.19055334", // 成交额 + 308, // 成交笔数 + "1756.87402397", // 主动买入成交量 + "28.46694368", // 主动买入成交额 + ] +] +``` +`` +GET /api/v3/klines +`` + +每根K线代表一个交易对。 +每根K线的开盘时间可视为唯一ID + + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +interval | ENUM | YES | 详见枚举定义:K线间隔 +startTime | LONG | NO | +endTime | LONG | NO | +limit | INT | NO | 默认 500; 最大 1500. +* 如果未发送 startTime 和 endTime ,默认返回最近的交易。 + + + +## 24hr 价格变动情况 + +> **响应** + +```javascript +{ + "symbol": "BTCUSDT", + "priceChange": "-94.99999800", //24小时价格变动 + "priceChangePercent": "-95.960", //24小时价格变动百分比 + "weightedAvgPrice": "0.29628482", //加权平均价 + "prevClosePrice": "3.89000000", //上一次结束价格 + "lastPrice": "4.00000200", //最近一次成交价 + "lastQty": "200.00000000", //最近一次成交额 + "bidPrice": "866.66000000", //最高的买入价格 + "bidQty": "72.05100000", //最高的买入价格的数量 + "askPrice": "866.73000000", //最低的卖出价 + "askQty": "1.21700000", //最低的卖出价格的数量 + "openPrice": "99.00000000", //24小时内第一次成交的价格 + "highPrice": "100.00000000", //24小时最高价 + "lowPrice": "0.10000000", //24小时最低价 + "volume": "8913.30000000", //24小时成交量 + "quoteVolume": "15.30000000", //24小时成交额 + "openTime": 1499783499040, //24小时内,第一笔交易的发生时间 + "closeTime": 1499869899040, //24小时内,最后一笔交易的发生时间 + "firstId": 28385, // 首笔成交id + "lastId": 28460, // 末笔成交id + "count": 76, // 成交笔数 + "baseAsset": "BTC", //基础代币 + "quoteAsset": "USDT" //报价代币 +} +``` + +`` +GET /api/v3/ticker/24hr +`` + +24 小时滚动窗口价格变动数据。 请注意,不携带symbol参数会返回全部交易对数据,此时返回的数据为示例相应的数组,不仅数据庞大,而且权重极高 + +**权重:** +1 单一交易对; +**40** 交易对参数缺失; + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | NO | +* 请注意,不携带symbol参数会返回全部交易对数据 + +## 最新价格 + +> **响应** + +```javascript +{ + "symbol": "ADAUSDT", + "price": "1.30000000", + "time": 1649666690902 +} +``` + +> OR + +```javascript +[ + { + "symbol": "ADAUSDT", + "price": "1.30000000", + "time": 1649666690902 + } +] +``` + +`` +GET /api/v3/ticker/price +`` + +获取交易对最新价格 + +**权重:** +1 单一交易对; +**2** 交易对参数缺失; + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | NO | +* 不发送交易对参数,则会返回所有交易对信息 + + +## 当前最优挂单 +> **响应** +```javascript +{ + "symbol": "LTCBTC", + "bidPrice": "4.00000000", + "bidQty": "431.00000000", + "askPrice": "4.00000200", + "askQty": "9.00000000" + "time": 1589437530011 // 交易时间 +} +``` +> OR +```javascript +[ + { + "symbol": "LTCBTC", + "bidPrice": "4.00000000", + "bidQty": "431.00000000", + "askPrice": "4.00000200", + "askQty": "9.00000000", + "time": 1589437530011 // 交易时间 + } +] +``` + +`` +GET /api/v3/ticker/bookTicker +`` + +返回当前最优的挂单(最高买单,最低卖单) + +**权重:** +1 单一交易对; +**2** 交易对参数缺失; + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | NO | +* 不发送交易对参数,则会返回所有交易对信息 + +## 获取Symbol手续费 + +> **响应** + +```javascript +{ + "symbol": "APXUSDT", + "makerCommissionRate": "0.000200",     + "takerCommissionRate": "0.000700" +} +``` +`` +GET /api/v3/commissionRate +`` + +获取Symbol手续费。 + +**权重:** +20 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | + + + + + +# 现货账户和交易接口 + + +## 下单 (TRADE) + +> **Response ACK:** + +```javascript +{ + "symbol": "BTCUSDT", // 交易对 + "orderId": 28, // 系统的订单ID + "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP", // 客户自己设置的ID + "updateTime": 1507725176595, // 交易的时间戳 + "price": "0.00000000", // 订单价格 + "avgPrice": "0.0000000000000000", //平均价格 + "origQty": "10.00000000", // 用户设置的原始订单数量 + "cumQty": "0", //累计数量 + "executedQty": "10.00000000", // 交易的订单数量 + "cumQuote": "10.00000000", // 累计交易的金额 + "status": "FILLED", // 订单状态 + "timeInForce": "GTC", // 订单的时效方式 + "stopPrice": "0", //触发价格 + "origType": "LIMIT", //触发前订单类型 + "type": "LIMIT", // 订单类型, 比如市价单,现价单等 + "side": "SELL", // 订单方向,买还是卖 +} +``` + +`` +POST /api/v3/order `` + +发送下单。 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +side | ENUM | YES | 详见枚举定义:订单方向 +type | ENUM | YES | 详见枚举定义:订单类型 +timeInForce | ENUM | NO | 详见枚举定义:有效方式 +quantity | DECIMAL | NO | +quoteOrderQty|DECIMAL|NO| +price | DECIMAL | NO | +newClientOrderId | STRING | NO | 客户自定义的唯一订单ID。 如果未发送,则自动生成 +stopPrice | DECIMAL | NO | 仅 `STOP`, `STOP_MARKET` , `TAKE_PROFIT`,`TAKE_PROFIT_MARKET` 需要此参数。 + +基于订单 `type`不同,强制要求某些参数: + +类型 | 强制要求的参数 +------------ | ------------ +`LIMIT` | `timeInForce`, `quantity`, `price` +`MARKET` | `quantity` 或 `quoteOrderQty` +`STOP`和`TAKE_PROFIT` | `quantity`, `price`, `stopPrice` +`STOP_MARKET`和`TAKE_PROFIT_MARKET` | `quantity`, `stopPrice` + +其他信息: + +* 下`MARKET` `SELL`市价单,用户通过`QUANTITY`控制想用市价单卖出的基础资产数量。 + * 比如在`BTCUSDT`交易对上下一个`MARKET` `SELL`市价单, 通过`QUANTITY`让用户指明想卖出多少BTC。 +* 下`MARKET` `BUY`的市价单,用户使用 `quoteOrderQty` 控制想用市价单买入的报价资产数量,`QUANTITY`将由系统根据市场流动性计算出来。 +  * 比如在`BTCUSDT`交易对上下一个`MARKET` `BUY`市价单, 通过`quoteOrderQty`让用户选择想使用多少USDT买入BTC。 +* 使用 `quoteOrderQty` 的市价单`MARKET`不会突破`LOT_SIZE`的限制规则; 报单会按给定的`quoteOrderQty`尽可能接近地被执行。 +* 除非之前的订单已经成交, 不然设置了相同的`newClientOrderId`订单会被拒绝。 + + + +## 撤销订单 (TRADE) + +> **响应** + +```javascript +{ + "symbol": "BTCUSDT", // 交易对 + "orderId": 28, // 系统的订单ID + "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP", // 客户自己设置的ID + "updateTime": 1507725176595, // 交易的时间戳 + "price": "0.00000000", // 订单价格 + "avgPrice": "0.0000000000000000", //平均价格 + "origQty": "10.00000000", // 用户设置的原始订单数量 + "cumQty": "0", //累计数量 + "executedQty": "10.00000000", // 交易的订单数量 + "cumQuote": "10.00000000", // 累计交易的金额 + "status": "CANCELED", // 订单状态 + "timeInForce": "GTC", // 订单的时效方式 + "stopPrice": "0", //触发价格 + "origType": "LIMIT", //触发前订单类型 + "type": "LIMIT", // 订单类型, 比如市价单,现价单等 + "side": "SELL", // 订单方向,买还是卖 +} +``` + +`` +DELETE /api/v3/order `` + +取消有效订单。 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +orderId | LONG | NO | +origClientOrderId | STRING | NO | + +`orderId` 或 `origClientOrderId` 必须至少发送一个 + +## 查询订单 (USER_DATA) + +> **响应** +```javascript +{ + "orderId": 38,   // 系统订单号 + "symbol": "ADA25SLP25",  // 交易对 + "status": "FILLED",  // 订单状态 + "clientOrderId": "afMd4GBQyHkHpGWdiy34Li",  // 用户自定义的订单号 + "price": "20",  // 委托价格 + "avgPrice": "12.0000000000000000",  // 平均成交价 + "origQty": "10",  // 原始委托数量 + "executedQty": "10",  // 成交量 + "cumQuote": "120",  // 成交金额 + "timeInForce": "GTC",  // 有效方法 + "type": "LIMIT",  // 订单类型 + "side": "BUY",  // 买卖方向 + "stopPrice": "0",  // 触发价 + "origType": "LIMIT",  // 触发前订单类型 + "time": 1649913186270,  // 订单时间 + "updateTime": 1649913186297  // 更新时间 +} +``` + +`` +GET /api/v3/order`` + +查询订单状态。 + +* 请注意,如果订单满足如下条件,不会被查询到: + * 订单的最终状态为 `CANCELED` 或者 `EXPIRED`, **并且** + * 订单没有任何的成交记录, **并且** + * 订单生成时间 + 7天 < 当前时间 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +orderId | LONG | NO | +origClientOrderId | STRING | NO | + +注意: + +* 至少需要发送 `orderId` 与 `origClientOrderId`中的一个 + + +## 查询当前挂单 (USER_DATA) + +> **响应** +```javascript +{ + "orderId": 38,   // 系统订单号 + "symbol": "ADA25SLP25",  // 交易对 + "status": "NEW",  // 订单状态 + "clientOrderId": "afMd4GBQyHkHpGWdiy34Li",  // 用户自定义的订单号 + "price": "20",  // 委托价格 + "avgPrice": "12.0000000000000000",  // 平均成交价 + "origQty": "10",  // 原始委托数量 + "executedQty": "10",  // 成交量 + "cumQuote": "120",  // 成交金额 + "timeInForce": "GTC",  // 有效方法 + "type": "LIMIT",  // 订单类型 + "side": "BUY",  // 买卖方向 + "stopPrice": "0",  // 触发价 + "origType": "LIMIT",  // 触发前订单类型 + "time": 1649913186270,  // 订单时间 + "updateTime": 1649913186297  // 更新时间 +} +``` + +`` +GET /api/v3/openOrder`` + +查询订单状态。 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +orderId | LONG | NO | +origClientOrderId | STRING | NO | + +注意: + +* 至少需要发送 `orderId` 与 `origClientOrderId`中的一个 + + +## 当前所有挂单 (USER_DATA) + +> **响应** + +```javascript +[ + { + "orderId": 349661, // 系统订单号 + "symbol": "BNBUSDT", // 交易对 + "status": "NEW", // 订单状态 + "clientOrderId": "LzypgiMwkf3TQ8wwvLo8RA", // 用户自定义的订单号 + "price": "1.10000000", // 委托价格 + "avgPrice": "0.0000000000000000", // 平均成交价 + "origQty": "5",  // 原始委托数量 + "executedQty": "0", // 成交量 + "cumQuote": "0", // 成交金额 + "timeInForce": "GTC", // 有效方法 + "type": "LIMIT", // 订单类型 + "side": "BUY", // 买卖方向 + "stopPrice": "0", // 触发价 + "origType": "LIMIT", // 触发前订单类型 + "time": 1756252940207, // 订单时间 + "updateTime": 1756252940207, // 更新时间 + } +] +``` + +`` +GET /api/v3/openOrders `` + +获取交易对的所有当前挂单, 请小心使用不带交易对参数的调用。 + +**权重:** +- 带symbol ***1*** +- 不带 ***40***   + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | NO | + +* 不带symbol参数,会返回所有交易对的挂单 + + + +## 取消当前所有挂单 (USER_DATA) + +> **响应** + +```javascript +{ + "code": 200, + "msg": "The operation of cancel all open order is done." +} +``` + +`` +DEL /api/v3/allOpenOrders `` + +**权重:** +- ***1*** + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +orderIdList | STRING | NO | id数组字符串 +origClientOrderIdList | STRING | NO | clientOrderId数组字符串 + + +## 查询所有订单 (USER_DATA) +> **响应** +```javascript +[ + { + "orderId": 349661, // 系统订单号 + "symbol": "BNBUSDT", // 交易对 + "status": "NEW", // 订单状态 + "clientOrderId": "LzypgiMwkf3TQ8wwvLo8RA", // 用户自定义的订单号 + "price": "1.10000000", // 委托价格 + "avgPrice": "0.0000000000000000", // 平均成交价 + "origQty": "5",  // 原始委托数量 + "executedQty": "0", // 成交量 + "cumQuote": "0", // 成交金额 + "timeInForce": "GTC", // 有效方法 + "type": "LIMIT", // 订单类型 + "side": "BUY", // 买卖方向 + "stopPrice": "0", // 触发价 + "origType": "LIMIT", // 触发前订单类型 + "time": 1756252940207, // 订单时间 + "updateTime": 1756252940207, // 更新时间 + } +] +``` + +`` +GET /api/v3/allOrders`` + +获取所有帐户订单; 有效,已取消或已完成。 + +* 请注意,如果订单满足如下条件,不会被查询到: + * 订单生成时间 + 7天 < 当前时间 + +**权重:** +5 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +orderId | LONG | NO | +startTime | LONG | NO | +endTime | LONG | NO | +limit | INT | NO | 默认 500; 最大 1000. + +* 查询时间范围最大不得超过7天 +* 默认查询最近7天内的数据 + + + +`` +GET /api/v3/transactionHistory`` +> **响应** + +```javascript +[ + { + "tranId": 1759115482304540227, //划转ID + "tradeId": null, //流水ID + "asset": "ASTER", //资产 + "symbol": "", //交易对 + "balanceDelta": "-500.00000000", //资金流数量,正数代表流入,负数代表流出 + "balanceInfo": "TRADE_SOURCE", //流水描述 + "time": 1759115482000, // 时间 + "type": "TRADE_SOURCE" //资金流类型 + } +] +``` + +查询交易流水 + +**权重:** +30 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +asset | STRING | NO | 资产 +type | STRING | NO | 类别 +startTime | LONG | NO | 开始时间 +endTime | LONG | NO | 结束时间 +limit | LONG | NO | 返回的结果集数量 默认值:100 最大值:1000 + +注意: + +* `type` 取值 `TRADE_TARGET`,`TRADE_SOURCE`,`TRANSFER_SPOT_TO_FUTURE`,`TRANSFER_FUTURE_TO_SPOT`,`TRANSFER_SPOT_TO_SPOT`,`AIRDROP`,`DIVIDEND`,`TRANSFER_REFUND`,`INTERNAL_TRANSFER`,`TRANSFER`,`SWAP`,`COMMISSION_REBATE`,`CASH_BACK` 中的一种 +* 如果`startTime` 和 `endTime` 均未发送, 只会返回最近7天的数据。 + +## 期货现货互转 (TRADE) + +> **响应:** + +```javascript +{ + "tranId": 21841, //交易id + "status": "SUCCESS" //状态 +} +``` + +`` +POST /api/v3/asset/wallet/transfer `` + +**权重:** +5 + +**参数:** + + +名称 | 类型 | 是否必需 | 描述 +---------------- | ------- | -------- | ---- +amount | DECIMAL | YES | 数量 +asset | STRING | YES | 资产 +clientTranId | STRING | YES | 交易id +kindType | STRING | YES | 交易类型 + +注意: +* kindType 取值为FUTURE_SPOT(期货转现货),SPOT_FUTURE(现货转期货) + +## 现货提现手续费 (NONe) +> **响应** +```javascript +{ + "tokenPrice": 1.00019000, + "gasCost": 0.5000, + "gasUsdValue": 0.5 +} +``` + +`` +GET /api/v3/aster/withdraw/estimateFee +`` + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +chainId | STRING | YES | +asset | STRING | YES | + +注意: +* chainId: 1(ETH),56(BSC),42161(Arbi) +* gasCost: 提现所需的最少数量的手续费 + +## 现货提现 (USER_DATA) +> **响应** +```javascript +{ + "withdrawId": "1014729574755487744", + "hash":"0xa6d1e617a3f69211df276fdd8097ac8f12b6ad9c7a49ba75bbb24f002df0ebb" +} +``` + +`` +POST /api/v3/aster/user-withdraw`` + +**权重:** +5 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +chainId | STRING | YES | +asset | STRING | YES | +amount | STRING | YES | +fee | STRING | YES | +receiver | STRING | YES | +nonce | STRING | YES | 当前时间的微秒值 +userSignature | STRING | YES | + +注意: +* chainId: 1(ETH),56(BSC),42161(Arbi) +* receiver : 当前账户的地址 +* 如果期货余额不足,会从spot账户划转到期货账户,进行提现 +* userSignature demo + +```shell +const domain = { + name: 'Aster', + version: '1', + chainId: 56, + verifyingContract: ethers.ZeroAddress, + } + +const currentTime = Date.now() * 1000 + +const types = { + Action: [ + {name: "type", type: "string"}, + {name: "destination", type: "address"}, + {name: "destination Chain", type: "string"}, + {name: "token", type: "string"}, + {name: "amount", type: "string"}, + {name: "fee", type: "string"}, + {name: "nonce", type: "uint256"}, + {name: "aster chain", type: "string"}, + ], + } + const value = { + 'type': 'Withdraw', + 'destination': '0xD9cA6952F1b1349d27f91E4fa6FB8ef67b89F02d', + 'destination Chain': 'BSC', + 'token': 'USDT', + 'amount': '10.123400', + 'fee': '1.234567891', + 'nonce': currentTime, + 'aster chain': 'Mainnet', + } + + +const signature = await signer.signTypedData(domain, types, value) +``` + +## 账户信息 (USER_DATA) +> **响应** +```javascript +{ + "feeTier": 0, + "canTrade": true, + "canDeposit": true, + "canWithdraw": true, + "canBurnAsset": true, + "updateTime": 0, +   "balances": [ + { + "asset": "BTC", + "free": "4723846.89208129", + "locked": "0.00000000" + }, + { + "asset": "LTC", + "free": "4763368.68006011", + "locked": "0.00000000" + } + ] +} +``` + +`` +GET /api/v3/account`` + +获取当前账户信息。 + +**权重:** +5 + +**参数:** + +名称 | 类型 | 是否必需| 描述 +------------ | ------------ | ------------ | ------------ + + +## 账户成交历史 (USER_DATA) +> **响应** +```javascript +[ + { + "symbol": "BNBUSDT", + "id": 1002, + "orderId": 266358, + "side": "BUY", + "price": "1", + "qty": "2", + "quoteQty": "2", + "commission": "0.00105000", + "commissionAsset": "BNB", + "time": 1755656788798, + "counterpartyId": 19, + "createUpdateId": null, + "maker": false, + "buyer": true + } +] +``` + +`` +GET /api/v3/userTrades `` + +获取账户指定交易对的成交历史 + +**权重:** +5 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | NO | +orderId|LONG|NO| 必须要和参数`symbol`一起使用. +startTime | LONG | NO | +endTime | LONG | NO | +fromId | LONG | NO | 起始Trade id。 默认获取最新交易。 +limit | INT | NO | 默认 500; 最大 1000. + +* 如果`startTime` 和 `endTime` 均未发送, 只会返回最近7天的数据。 +* startTime 和 endTime 的最大间隔为7天 +* 不能同时传`fromId`与`startTime` 或 `endTime` +       + + + + +--- +# Websocket 行情推送 + +* 本篇所列出的所有wss接口的baseurl为: **wss://sstream.asterdex-testnet.com** +* Streams有单一原始 stream 或组合 stream +* 单一原始 streams 格式为 **/ws/\** +* 组合streams的URL格式为 **/stream?streams=\/\/\** +* 订阅组合streams时,事件payload会以这样的格式封装: **{"stream":"\","data":\}** +* stream名称中所有交易对均为 **小写** +* 每个到 **sstream.asterdex-testnet.com** 的链接有效期不超过24小时,请妥善处理断线重连。 +* 每3分钟,服务端会发送ping帧,客户端应当在10分钟内回复pong帧,否则服务端会主动断开链接。允许客户端发送不成对的pong帧(即客户端可以以高于10分钟每次的频率发送pong帧保持链接)。 + +## 实时订阅/取消数据流 + +* 以下数据可以通过websocket发送以实现订阅或取消订阅数据流。示例如下。 +* 响应内容中的`id`是无符号整数,作为往来信息的唯一标识。 +* 如果相应内容中的 `result` 为 `null`,表示请求发送成功。 + + +### 订阅一个信息流 +> **响应** + ```javascript + { + "result": null, + "id": 1 + } + ``` +* **请求** + { + "method": "SUBSCRIBE", + "params": + [ + "btcusdt@aggTrade", + "btcusdt@depth" + ], + "id": 1 + } + + +### 取消订阅一个信息流 + +> **响应** + + ```javascript + { + "result": null, + "id": 312 + } + ``` + +* **请求** + { + "method": "UNSUBSCRIBE", + "params": + [ + "btcusdt@depth" + ], + "id": 312 + } + + +### 已订阅信息流 + +> **响应** + + ```javascript + { + "result": [ + "btcusdt@aggTrade" + ], + "id": 3 + } + ``` + +* **请求** + + { + "method": "LIST_SUBSCRIPTIONS", + "id": 3 + } + + +### 设定属性 +当前,唯一可以设置的属性是设置是否启用`combined`("组合")信息流。 +当使用`/ws/`("原始信息流")进行连接时,combined属性设置为`false`,而使用 `/stream/`进行连接时则将属性设置为`true`。 + +> **响应** + + ```javascript +{ + "result": null, + "id": 5 +} + ``` + +* **请求** + { + "method": "SET_PROPERTY", + "params": + [ + "combined", + true + ], + "id": 5 + } + + +### 检索属性 + +> **响应** + ```javascript + { + "result": true, // Indicates that combined is set to true. + "id": 2 + } + ``` + +* **请求** + + { + "method": "GET_PROPERTY", + "params": + [ + "combined" + ], + "id": 2 + } + + +###错误信息 + +错误信息 | 描述 +---|--- +{"code": 0, "msg": "Unknown property"} | `SET_PROPERTY` 或 `GET_PROPERTY`中应用的参数无效 +{"code": 1, "msg": "Invalid value type: expected Boolean", "id": '%s'} | 仅接受`true`或`false` +{"code": 2, "msg": "Invalid request: property name must be a string"}| 提供的属性名无效 +{"code": 2, "msg": "Invalid request: request ID must be an unsigned integer"}| 参数`id`未提供或`id`值是无效类型 +{"code": 2, "msg": "Invalid request: unknown variant %s, expected one of `SUBSCRIBE`, `UNSUBSCRIBE`, `LIST_SUBSCRIPTIONS`, `SET_PROPERTY`, `GET_PROPERTY` at line 1 column 28"} | 错字提醒,或提供的值不是预期类型 +{"code": 2, "msg": "Invalid request: too many parameters"}| 数据中提供了不必要参数 +{"code": 2, "msg": "Invalid request: property name must be a string"} | 未提供属性名 +{"code": 2, "msg": "Invalid request: missing field `method` at line 1 column 73"} | 数据未提供`method` +{"code":3,"msg":"Invalid JSON: expected value at line %s column %s"} | JSON 语法有误. + + +## 归集交易流 + + +> **Payload:** +```javascript +{ + "e": "aggTrade", // 事件类型 + "E": 123456789, // 事件时间 + "s": "BNBBTC", // 交易对 + "a": 12345, // 归集交易ID + "p": "0.001", // 成交价格 + "q": "100", // 成交数量 + "f": 100, // 被归集的首个交易ID + "l": 105, // 被归集的末次交易ID + "T": 123456785, // 成交时间 + "m": true, // 买方是否是做市方。如true,则此次成交是一个主动卖出单,否则是一个主动买入单。 +} +``` + +归集交易 stream 推送交易信息,是对单一订单的集合。 + +**Stream 名称:** `@aggTrade` + +**Update Speed:** 实时 + + +## 逐笔交易 + + +> **Payload:** +```javascript +{ + "e": "trade", // 事件类型 + "E": 123456789, // 事件时间 + "s": "BNBBTC", // 交易对 + "t": 12345, // 交易ID + "p": "0.001", // 成交价格 + "q": "100", // 成交数量 + "T": 123456785, // 成交时间 + "m": true, // 买方是否是做市方。如true,则此次成交是一个主动卖出单,否则是一个主动买入单。 +} +``` + +**Stream Name:** `@trade` + +逐笔交易推送每一笔成交的信息。**成交**,或者说交易的定义是仅有一个吃单者与一个挂单者相互交易 + + +## K线 Streams +> **Payload:** +```javascript +{ + "e": "kline", // 事件类型 + "E": 123456789, // 事件时间 + "s": "BNBBTC", // 交易对 + "k": { + "t": 123400000, // 这根K线的起始时间 + "T": 123460000, // 这根K线的结束时间 + "s": "BNBBTC", // 交易对 + "i": "1m", // K线间隔 + "f": 100, // 这根K线期间第一笔成交ID + "L": 200, // 这根K线期间末一笔成交ID + "o": "0.0010", // 这根K线期间第一笔成交价 + "c": "0.0020", // 这根K线期间末一笔成交价 + "h": "0.0025", // 这根K线期间最高成交价 + "l": "0.0015", // 这根K线期间最低成交价 + "v": "1000", // 这根K线期间成交量 + "n": 100, // 这根K线期间成交笔数 + "x": false, // 这根K线是否完结(是否已经开始下一根K线) + "q": "1.0000", // 这根K线期间成交额 + "V": "500", // 主动买入的成交量 + "Q": "0.500", // 主动买入的成交额 + "B": "123456" // 忽略此参数 + } +} +``` + +K线stream逐秒推送所请求的K线种类(最新一根K线)的更新。 + +**Stream Name:** `@kline_` + +**Update Speed:** 2000ms + +**K线图间隔参数:** + +m -> 分钟; h -> 小时; d -> 天; w -> 周; M -> 月 + +* 1m +* 3m +* 5m +* 15m +* 30m +* 1h +* 2h +* 4h +* 6h +* 8h +* 12h +* 1d +* 3d +* 1w +* 1M + + +## 按 Symbol 的精简Ticker + +> **Payload:** +```javascript + { + "e": "24hrMiniTicker", // 事件类型 + "E": 123456789, // 事件时间 + "s": "BNBBTC", // 交易对 + "c": "0.0025", // 最新成交价格 + "o": "0.0010", // 24小时前开始第一笔成交价格 + "h": "0.0025", // 24小时内最高成交价 + "l": "0.0010", // 24小时内最低成交价 + "v": "10000", // 成交量 + "q": "18" // 成交额 + } +``` + +按Symbol刷新的最近24小时精简ticker信息 + +**Stream 名称:** `@miniTicker` + +**Update Speed:** 1000ms + + +## 全市场所有Symbol的精简Ticker + +> **Payload:** +```javascript +[ + { + // 数组每一个元素对应一个交易对,内容与 \@miniTicker相同 + } +] +``` + +同上,只是推送所有交易对.需要注意的是,只有更新的ticker才会被推送. + +**Stream名称:** !miniTicker@arr + +**Update Speed:** 1000ms + +## 按Symbol的完整Ticker + +> **Payload:** +```javascript +{ + "e": "24hrTicker", // 事件类型 + "E": 123456789, // 事件时间 + "s": "BNBBTC", // 交易对 + "p": "0.0015", // 24小时价格变化 + "P": "250.00", // 24小时价格变化(百分比) + "w": "0.0018", // 平均价格 + "c": "0.0025", // 最新成交价格 + "Q": "10", // 最新成交交易的成交量 + "o": "0.0010", // 整整24小时前,向后数的第一次成交价格 + "h": "0.0025", // 24小时内最高成交价 + "l": "0.0010", // 24小时内最低成交价 + "v": "10000", // 24小时内成交量 + "q": "18", // 24小时内成交额 + "O": 0, // 统计开始时间 + "C": 86400000, // 统计结束时间 + "F": 0, // 24小时内第一笔成交交易ID + "L": 18150, // 24小时内最后一笔成交交易ID + "n": 18151 // 24小时内成交数 +} +``` + +每秒推送单个交易对的过去24小时滚动窗口标签统计信息。 + +**Stream 名称:** `@ticker` + +**Update Speed:** 1000ms + +## 全市场所有交易对的完整Ticker + +> **Payload:** +```javascript +[ + { + // Same as @ticker payload + } +] +``` + +推送全市场所有交易对刷新的24小时完整ticker信息。需要注意的是,没有更新的ticker不会被推送。 + +**Stream Name:** `!ticker@arr` + +**Update Speed:** 1000ms + + +## 按Symbol的最优挂单信息 + +> **Payload:** +```javascript +{ + "u":400900217, // order book updateId + "s":"BNBUSDT", // 交易对 + "b":"25.35190000", // 买单最优挂单价格 + "B":"31.21000000", // 买单最优挂单数量 + "a":"25.36520000", // 卖单最优挂单价格 + "A":"40.66000000" // 卖单最优挂单数量 +} +``` + +实时推送指定交易对最优挂单信息 + +**Stream Name:** `@bookTicker` + +**Update Speed:** 实时 + +## 全市场最优挂单信息 +> **Payload:** +```javascript +{ + // 同 @bookTicker payload +} +``` + +实时推送所有交易对最优挂单信息 + +**Stream Name:** `!bookTicker` + +**Update Speed:** 实时 + + +## 有限档深度信息 + +> **Payload:** +```javascript +{ + "e": "depthUpdate", // Event type + "E": 123456789, // Event time + "T": 123456788, // Transaction time + "s": "BTCUSDT", // Symbol + "U": 100, // First update ID in event + "u": 120, // Final update ID in event + "pu": 99, // Final update Id in last stream(ie `u` in last stream) +  "bids": [ // Bids to be updated + [ + "0.0024", // Price level to be updated + "10" // Quantity + ] + ], + "asks": [ // Asks to be updated + [ + "0.0026", // Price level to be updated + "100" // Quantity + ] + ] +} +``` + +每秒或每100毫秒推送有限档深度信息。levels表示几档买卖单信息, 可选 5/10/20档 + +**Stream Names:** `@depth` 或 `@depth@100ms`. + +**Update Speed:** 1000ms 或 100ms + + +## 增量深度信息 +> **Payload:** +```javascript +{ + "e": "depthUpdate", // Event type + "E": 123456789, // Event time + "T": 123456788, // Transaction time + "s": "BTCUSDT", // Symbol + "U": 100, // First update ID in event + "u": 120, // Final update ID in event + "pu": 99, // Final update Id in last stream(ie `u` in last stream) + "b": [ // Bids to be updated + [ + "5.4", // Price level to be updated + "10" // Quantity + ] + ], + "a": [ // Asks to be updated + [ + "5.6", // Price level to be updated + "100" // Quantity + ] + ] +} +``` + +每秒或每100毫秒推送orderbook的变化部分(如果有) + +**Stream Name:** `@depth` 或 `@depth@100ms` + +**Update Speed:** 1000ms 或 100ms + +## 如何正确在本地维护一个orderbook副本 +1. 订阅 **wss://sstream.asterdex-testnet.com/ws/bnbbtc@depth** +2. 开始缓存收到的更新。同一个价位,后收到的更新覆盖前面的。 +3. 访问Rest接口 **https://sapi.asterdex-testnet.com/api/v3/depth?symbol=BNBBTC&limit=1000** 获得一个1000档的深度快照 +4. 将目前缓存到的信息中`u` <= 步骤3中获取到的快照中的`lastUpdateId`的部分丢弃(丢弃更早的信息,已经过期)。 +5. 将深度快照中的内容更新到本地orderbook副本中,并从websocket接收到的第一个`U` <= `lastUpdateId`+1 **且** `u` >= `lastUpdateId`+1 的event开始继续更新本地副本。 +6. 每一个新event的`U`应该恰好等于上一个event的`u`+1,否则可能出现了丢包,请从step3重新进行初始化。 +7. 每一个event中的挂单量代表这个价格目前的挂单量**绝对值**,而不是相对变化。 +8. 如果某个价格对应的挂单量为0,表示该价位的挂单已经撤单或者被吃,应该移除这个价位。 + + + + + + +# Websocket账户信息推送 + +* 本篇所列出API接口的base url : **https://sapi.asterdex-testnet.com** +* 用于订阅账户数据的 `listenKey` 从创建时刻起有效期为60分钟 +* 可以通过 `PUT` 一个 `listenKey` 延长60分钟有效期 +* 可以通过`DELETE`一个 `listenKey` 立即关闭当前数据流,并使该`listenKey` 无效 +* 在具有有效`listenKey`的帐户上执行`POST`将返回当前有效的`listenKey`并将其有效期延长60分钟 +* websocket接口的baseurl: **wss://sstream.asterdex-testnet.com** +* U订阅账户数据流的stream名称为 **/ws/\** +* 每个链接有效期不超过24小时,请妥善处理断线重连。 + + +## Listen Key(现货账户) + +### 生成 Listen Key (USER_STREAM) + +> **响应** +```javascript +{ + "listenKey": "pqia91ma19a5s61cv6a81va65sdf19v8a65a1a5s61cv6a81va65sdf19v8a65a1" +} +``` + +`` +POST /api/v3/listenKey +`` + +开始一个新的数据流。除非发送 keepalive,否则数据流于60分钟后关闭。如果该帐户具有有效的`listenKey`,则将返回该`listenKey`并将其有效期延长60分钟。 + +**权重:** +1 + +**参数:** +NONE + +### 延长 Listen Key 有效期 (USER_STREAM) + +> **响应** +```javascript +{} +``` + +`` +PUT /api/v3/listenKey +`` + +有效期延长至本次调用后60分钟,建议每30分钟发送一个 ping 。 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +listenKey | STRING | YES + + +### 关闭 Listen Key (USER_STREAM) + +> **响应** +```javascript +{} +``` + +`` +DELETE /api/v3/listenKey +`` + +关闭用户数据流。 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +listenKey | STRING | YES + + +## Payload: 账户更新 + +每当帐户余额发生更改时,都会发送一个事件`outboundAccountPosition`,其中包含可能由生成余额变动的事件而变动的资产。 + +> **Payload** +```javascript +{ + "B":[// 余额 + { + "a":"SLP25",   // 资产名称 + "f":"10282.42029415",   // 可用余额 + "l":"653.00000001"   // 冻结余额 + }, + { + "a":"ADA25", + "f":"9916.96229880", + "l":"34.00510000" + } + ], + "e":"outboundAccountPosition",   // 事件类型 + "T":1649926447190,   // 账户末次更新时间戳 + "E":1649926447205   // 事件时间 + "m":"WITHDRAW" // 事件推出原因 +} +``` + + +## Payload: 订单更新 + +订单通过`executionReport`事件进行更新。 + +> **Payload** + +```javascript +{ + "s":"ADA25SLP25",   // 交易对 + "c":"Xzh0gnxT41PStbwqOtXnjD",  // 客户端自定订单ID + "S":"SELL",   // 订单方向 + "o":"LIMIT",   // 订单类型 + "f":"GTC",   // 有效方式 + "q":"10.001000",   // 订单原始数量 + "p":"19.1000000000",   // 订单原始价格 + "ap":"19.0999999955550656", //平均价格 + "P":"0",  // 条件订单触发价格 + "x":"TRADE",   // 本次事件的具体执行类型 + "X":"PARTIALLY_FILLED",   // 订单的当前状态 + "i":27,   // 订单ID + "l":"1",     // 订单末次成交量 + "z":"8.999000",   // 订单累计已成交量 + "L":"19.1000000000",   // 订单末次成交价格 + "n":"0.00382000",   // 手续费数量 + "N":"SLP25",   // 手续费资产类型 + "T":1649926447190,   // 成交时间 + "t":18,   // 成交ID + "m":true,   // 该成交是作为挂单成交吗? + "ot":"LIMIT", //初始订单类型 + "O":0,   // 订单时间 + "Z":"171.88089996",   // 累计报价资产交易数量 + "Y":"19.1000000000000000",   // 最近报价交易数量 + "Q":"0",   // 报价数量 + "e":"executionReport",   // 事件类型 + "E":1649926447209  // 事件时间 +} +``` + + +**执行类型:** +* NEW 新订单 +* CANCELED 订单被取消 +* REJECTED 新订单被拒绝 +* TRADE 订单有新成交 +* EXPIRED 订单失效(根据订单的Time In Force参数) + + + +#错误代码 + +> error JSON payload: + +```javascript +{ + "code":-1121, + "msg":"Invalid symbol." +} +``` + +错误由两部分组成:错误代码和消息。 代码是通用的,但是消息可能会有所不同。 + + +## 10xx - 常规服务器或网络问题 +### -1000 UNKNOWN + * An unknown error occured while processing the request. + * 处理请求时发生未知错误。 + +### -1001 DISCONNECTED + * Internal error; unable to process your request. Please try again. + * 内部错误; 无法处理您的请求。 请再试一次. + +### -1002 UNAUTHORIZED + * You are not authorized to execute this request. + * 您无权执行此请求。 + +### -1003 TOO_MANY_REQUESTS + * Too many requests queued. + * 排队的请求过多。 + * Too many requests; please use the websocket for live updates. + * 请求权重过多; 请使用websocket获取最新更新。 + * Too many requests; current limit is %s requests per minute. Please use the websocket for live updates to avoid polling the API. + * 请求权重过多; 当前限制为每分钟%s请求权重。 请使用websocket进行实时更新,以避免轮询API。 + * Way too many requests; IP banned until %s. Please use the websocket for live updates to avoid bans. + * 请求权重过多; IP被禁止,直到%s。 请使用websocket进行实时更新,以免被禁。 + +### -1004 DUPLICATE_IP + * This IP is already on the white list + * IP地址已经在白名单 + +### -1005 NO_SUCH_IP + * No such IP has been white listed + * 白名单上没有此IP地址 + +### -1006 UNEXPECTED_RESP + * An unexpected response was received from the message bus. Execution status unknown. + * 从消息总线收到意外的响应。执行状态未知。 + +### -1007 TIMEOUT + * Timeout waiting for response from backend server. Send status unknown; execution status unknown. + * 等待后端服务器响应超时。 发送状态未知; 执行状态未知。 + +### -1014 UNKNOWN_ORDER_COMPOSITION + * Unsupported order combination. + * 不支持当前的下单参数组合 + +### -1015 TOO_MANY_ORDERS + * Too many new orders. + * 新订单太多。 + * Too many new orders; current limit is %s orders per %s. + * 新订单太多; 当前限制为每%s %s个订单。 + +### -1016 SERVICE_SHUTTING_DOWN + * This service is no longer available. + * 该服务不可用。 + +### -1020 UNSUPPORTED_OPERATION + * This operation is not supported. + * 不支持此操作。 + +### -1022 INVALID_SIGNATURE + * Signature for this request is not valid. + * 此请求的签名无效。 + +### -1023 START_TIME_GREATER_THAN_END_TIME + * Start time is greater than end time. + * 参数里面的开始时间在结束时间之后 + + +## 11xx - Request issues +### -1100 ILLEGAL_CHARS + * Illegal characters found in a parameter. + * 在参数中发现非法字符。 + * Illegal characters found in parameter '%s'; legal range is '%s'. + * 在参数`%s`中发现非法字符; 合法范围是`%s`。 + +### -1101 TOO_MANY_PARAMETERS + * Too many parameters sent for this endpoint. + * 为此端点发送的参数太多。 + * Too many parameters; expected '%s' and received '%s'. + * 参数太多;预期为`%s`并收到了`%s`。 + * Duplicate values for a parameter detected. + * 检测到的参数值重复。 + +### -1102 MANDATORY_PARAM_EMPTY_OR_MALFORMED + * A mandatory parameter was not sent, was empty/null, or malformed. + * 未发送强制性参数,该参数为空/空或格式错误。 + * Mandatory parameter '%s' was not sent, was empty/null, or malformed. + * 强制参数`%s`未发送,为空/空或格式错误。 + * Param '%s' or '%s' must be sent, but both were empty/null! + * 必须发送参数`%s`或`%s`,但两者均为空! + +### -1103 UNKNOWN_PARAM + * An unknown parameter was sent. + * 发送了未知参数。 + +### -1104 UNREAD_PARAMETERS + * Not all sent parameters were read. + * 并非所有发送的参数都被读取。 + * Not all sent parameters were read; read '%s' parameter(s) but was sent '%s'. + * 并非所有发送的参数都被读取; 读取了`%s`参数,但被发送了`%s`。 + +### -1105 PARAM_EMPTY + * A parameter was empty. + * 参数为空。 + * Parameter '%s' was empty. + * 参数`%s`为空。 + +### -1106 PARAM_NOT_REQUIRED + * A parameter was sent when not required. + * 发送了不需要的参数。 + * Parameter '%s' sent when not required. + * 发送了不需要参数`%s`。 + +### -1111 BAD_PRECISION + * Precision is over the maximum defined for this asset. + * 精度超过为此资产定义的最大值。 + +### -1112 NO_DEPTH + * No orders on book for symbol. + * 交易对没有挂单。 + +### -1114 TIF_NOT_REQUIRED + * TimeInForce parameter sent when not required. + * 发送的`TimeInForce`参数不需要。 + +### -1115 INVALID_TIF + * Invalid timeInForce. + * 无效的`timeInForce` + +### -1116 INVALID_ORDER_TYPE + * Invalid orderType. + * 无效订单类型。 + +### -1117 INVALID_SIDE + * Invalid side. + * 无效买卖方向。 + +### -1118 EMPTY_NEW_CL_ORD_ID + * New client order ID was empty. + * 新的客户订单ID为空。 + +### -1119 EMPTY_ORG_CL_ORD_ID + * Original client order ID was empty. + * 客户自定义的订单ID为空。 + +### -1120 BAD_INTERVAL + * Invalid interval. + * 无效时间间隔。 + +### -1121 BAD_SYMBOL + * Invalid symbol. + * 无效的交易对。 + +### -1125 INVALID_LISTEN_KEY + * This listenKey does not exist. + * 此`listenKey`不存在。 + +### -1127 MORE_THAN_XX_HOURS + * Lookup interval is too big. + * 查询间隔太大。 + * More than %s hours between startTime and endTime. + * 从开始时间到结束时间之间超过`%s`小时。 + +### -1128 OPTIONAL_PARAMS_BAD_COMBO + * Combination of optional parameters invalid. + * 可选参数组合无效。 + +### -1130 INVALID_PARAMETER + * Invalid data sent for a parameter. + * 发送的参数为无效数据。 + * Data sent for parameter '%s' is not valid. + * 发送参数`%s`的数据无效。 + +### -1136 INVALID_NEW_ORDER_RESP_TYPE + * Invalid newOrderRespType. + * 无效的 newOrderRespType。 + + +## 20xx - Processing Issues +### -2010 NEW_ORDER_REJECTED + * NEW_ORDER_REJECTED + * 新订单被拒绝 + +### -2011 CANCEL_REJECTED + * CANCEL_REJECTED + * 取消订单被拒绝 + +### -2013 NO_SUCH_ORDER + * Order does not exist. + * 订单不存在。 + +### -2014 BAD_API_KEY_FMT + * API-key format invalid. + * API-key 格式无效。 + +### -2015 REJECTED_MBX_KEY + * Invalid API-key, IP, or permissions for action. + * 无效的API密钥,IP或操作权限。 + +### -2016 NO_TRADING_WINDOW + * No trading window could be found for the symbol. Try ticker/24hrs instead. + * 找不到该交易对的交易窗口。 尝试改为24小时自动报价。 + +### -2018 BALANCE_NOT_SUFFICIENT + * Balance is insufficient. + * 余额不足 + +### -2020 UNABLE_TO_FILL + * Unable to fill. + * 无法成交 + +### -2021 ORDER_WOULD_IMMEDIATELY_TRIGGER + * Order would immediately trigger. + * 订单可能被立刻触发 + +### -2022 REDUCE_ONLY_REJECT + * ReduceOnly Order is rejected. + * `ReduceOnly`订单被拒绝 + +### -2024 POSITION_NOT_SUFFICIENT + * Position is not sufficient. + * 持仓不足 + +### -2025 MAX_OPEN_ORDER_EXCEEDED + * Reach max open order limit. + * 挂单量达到上限 + +### -2026 REDUCE_ONLY_ORDER_TYPE_NOT_SUPPORTED + * This OrderType is not supported when reduceOnly. + * 当前订单类型不支持`reduceOnly` + +## 40xx - Filters and other Issues +### -4000 INVALID_ORDER_STATUS + * Invalid order status. + * 订单状态不正确 + +### -4001 PRICE_LESS_THAN_ZERO + * Price less than 0. + * 价格小于0 + +### -4002 PRICE_GREATER_THAN_MAX_PRICE + * Price greater than max price. + * 价格超过最大值 + +### -4003 QTY_LESS_THAN_ZERO + * Quantity less than zero. + * 数量小于0 + +### -4004 QTY_LESS_THAN_MIN_QTY + * Quantity less than min quantity. + * 数量小于最小值 + +### -4005 QTY_GREATER_THAN_MAX_QTY + * Quantity greater than max quantity. + * 数量大于最大值 + +### -4006 STOP_PRICE_LESS_THAN_ZERO + * Stop price less than zero. + * 触发价小于最小值 + +### -4007 STOP_PRICE_GREATER_THAN_MAX_PRICE + * Stop price greater than max price. + * 触发价大于最大值 + +### -4008 TICK_SIZE_LESS_THAN_ZERO + * Tick size less than zero. + * 价格精度小于0 + +### -4009 MAX_PRICE_LESS_THAN_MIN_PRICE + * Max price less than min price. + * 最大价格小于最小价格 + +### -4010 MAX_QTY_LESS_THAN_MIN_QTY + * Max qty less than min qty. + * 最大数量小于最小数量 + +### -4011 STEP_SIZE_LESS_THAN_ZERO + * Step size less than zero. + * 步进值小于0 + +### -4012 MAX_NUM_ORDERS_LESS_THAN_ZERO + * Max num orders less than zero. + * 最大订单量小于0 + +### -4013 PRICE_LESS_THAN_MIN_PRICE + * Price less than min price. + * 价格小于最小价格 + +### -4014 PRICE_NOT_INCREASED_BY_TICK_SIZE + * Price not increased by tick size. + * 价格增量不是价格精度的倍数。 + +### -4015 INVALID_CL_ORD_ID_LEN + * Client order id is not valid. + * 客户订单ID有误。 + * Client order id length should not be more than 36 chars + * 客户订单ID长度应该不多于36字符 + +### -4016 PRICE_HIGHTER_THAN_MULTIPLIER_UP + * Price is higher than mark price multiplier cap. + +### -4017 MULTIPLIER_UP_LESS_THAN_ZERO + * Multiplier up less than zero. + * 价格上限小于0 + +### -4018 MULTIPLIER_DOWN_LESS_THAN_ZERO + * Multiplier down less than zero. + * 价格下限小于0 + +### -4019 COMPOSITE_SCALE_OVERFLOW + * Composite scale too large. + +### -4020 TARGET_STRATEGY_INVALID + * Target strategy invalid for orderType '%s',reduceOnly '%b'. + * 目标策略值不适合`%s`订单状态, 只减仓`%b`。 + +### -4021 INVALID_DEPTH_LIMIT + * Invalid depth limit. + * 深度信息的`limit`值不正确。 + * '%s' is not valid depth limit. + * `%s`不是合理的深度信息的`limit`值。 + +### -4022 WRONG_MARKET_STATUS + * market status sent is not valid. + * 发送的市场状态不正确。 + +### -4023 QTY_NOT_INCREASED_BY_STEP_SIZE + * Qty not increased by step size. + * 数量的递增值不是步进值的倍数。 + +### -4024 PRICE_LOWER_THAN_MULTIPLIER_DOWN + * Price is lower than mark price multiplier floor. + +### -4025 MULTIPLIER_DECIMAL_LESS_THAN_ZERO + * Multiplier decimal less than zero. + +### -4026 COMMISSION_INVALID + * Commission invalid. + * 收益值不正确 + * `%s` less than zero. + * `%s`少于0 + * `%s` absolute value greater than `%s` + * `%s`绝对值大于`%s` + +### -4027 INVALID_ACCOUNT_TYPE + * Invalid account type. + * 账户类型不正确。 + +### -4029 INVALID_TICK_SIZE_PRECISION + * Tick size precision is invalid. + * 价格精度小数点位数不正确。 + +### -4030 INVALID_STEP_SIZE_PRECISION + * Step size precision is invalid. + * 步进值小数点位数不正确。 + +### -4031 INVALID_WORKING_TYPE + * Invalid parameter working type + * 不正确的参数类型 + * Invalid parameter working type: `%s` + * 不正确的参数类型: `%s` + +### -4032 EXCEED_MAX_CANCEL_ORDER_SIZE + * Exceed maximum cancel order size. + * 超过可以取消的最大订单量。 + * Invalid parameter working type: `%s` + * 不正确的参数类型: `%s` + +### -4044 INVALID_BALANCE_TYPE + * Balance Type is invalid. + * 余额类型不正确。 + +### -4045 MAX_STOP_ORDER_EXCEEDED + * Reach max stop order limit. + * 达到止损单的上限。 + +### -4055 AMOUNT_MUST_BE_POSITIVE + * Amount must be positive. + * 数量必须是正整数 + +### -4056 INVALID_API_KEY_TYPE + * Invalid api key type. + * API key的类型不正确 + +### -4057 INVALID_RSA_PUBLIC_KEY + * Invalid api public key + * API key不正确 + +### -4058 MAX_PRICE_TOO_LARGE + * maxPrice and priceDecimal too large,please check. + * maxPrice和priceDecimal太大,请检查。 + +### -4060 INVALID_POSITION_SIDE + * Invalid position side. + * 仓位方向不正确。 + +### -4061 POSITION_SIDE_NOT_MATCH + * Order's position side does not match user's setting. + * 订单的持仓方向和用户设置不一致。 + +### -4062 REDUCE_ONLY_CONFLICT + * Invalid or improper reduceOnly value. + * 仅减仓的设置不正确。 + +### -4084 UPCOMING_METHOD + * Method is not allowed currently. Upcoming soon. + * 方法不支持 + +### -4086 INVALID_PRICE_SPREAD_THRESHOLD + * Invalid price spread threshold + * 无效的价差阀值 + +### -4087 REDUCE_ONLY_ORDER_PERMISSION + * User can only place reduce only order + * 用户只能下仅减仓订单 + +### -4088 NO_PLACE_ORDER_PERMISSION + * User can not place order currently + * 用户当前不能下单 + +### -4114 INVALID_CLIENT_TRAN_ID_LEN + * clientTranId is not valid + * clientTranId不正确 + * Client tran id length should be less than 64 chars + * 客户的tranId长度应该小于64个字符 + +### -4115 DUPLICATED_CLIENT_TRAN_ID + * clientTranId is duplicated + * clientTranId重复 + * Client tran id should be unique within 7 days + * 客户的tranId应在7天内唯一 + +### -4118 REDUCE_ONLY_MARGIN_CHECK_FAILED + * ReduceOnly Order Failed. Please check your existing position and open orders + * 仅减仓订单失败。请检查现有的持仓和挂单 + +### -4131 MARKET_ORDER_REJECT + * The counterparty's best price does not meet the PERCENT_PRICE filter limit + * 交易对手的最高价格未达到PERCENT_PRICE过滤器限制 + +### -4135 INVALID_ACTIVATION_PRICE + * Invalid activation price + * 无效的激活价格 + +### -4137 QUANTITY_EXISTS_WITH_CLOSE_POSITION + * Quantity must be zero with closePosition equals true + * 数量必须为0,当closePosition为true时 + +### -4138 REDUCE_ONLY_MUST_BE_TRUE + * Reduce only must be true with closePosition equals true + * Reduce only 必须为true,当closePosition为true时 + +### -4139 ORDER_TYPE_CANNOT_BE_MKT + * Order type can not be market if it's unable to cancel + * 订单类型不能为市价单如果不能取消 + +### -4140 INVALID_OPENING_POSITION_STATUS + * Invalid symbol status for opening position + * 无效的交易对状态 + +### -4141 SYMBOL_ALREADY_CLOSED + * Symbol is closed + * 交易对已下架 + +### -4142 STRATEGY_INVALID_TRIGGER_PRICE + * REJECT: take profit or stop order will be triggered immediately + * 拒绝:止盈止损单将立即被触发 + +### -4164 MIN_NOTIONAL + * Order's notional must be no smaller than 5.0 (unless you choose reduce only) + * 订单的名义价值不可以小于5,除了使用reduce only + * Order's notional must be no smaller than %s (unless you choose reduce only) + * 订单的名义价值不可以小于`%s`,除了使用reduce only + +### -4165 INVALID_TIME_INTERVAL + * Invalid time interval + * 无效的间隔 + * Maximum time interval is %s days + * 最大的时间间隔为 `%s` 天 + +### -4183 PRICE_HIGHTER_THAN_STOP_MULTIPLIER_UP + * Price is higher than stop price multiplier cap. + * 止盈止损订单价格不应高于触发价与报价乘数上限的乘积 + * Limit price can't be higher than %s. + * 止盈止损订单价格不应高于 `%s` + +### -4184 PRICE_LOWER_THAN_STOP_MULTIPLIER_DOWN + * Price is lower than stop price multiplier floor. + * 止盈止损订单价格不应低于触发价与报价乘数下限的乘积 + * Limit price can't be lower than %s. + * 止盈止损订单价格不应低于 `%s`f From 558cee440c18138d80a403cb3c996a44b4764577 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Tue, 7 Apr 2026 18:30:24 +0800 Subject: [PATCH 089/131] fix: fix Demo directory links to lowercase demo Co-Authored-By: Claude Sonnet 4.6 --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 9e58763..0d73996 100644 --- a/README.md +++ b/README.md @@ -32,19 +32,19 @@ # Aster Finance Spot Asset Consolidation -[Aster Finance Spot Asset Consolidation](./Demo/consolidation.js) +[Aster Finance Spot Asset Consolidation](./demo/consolidation.js) # Aster Api Key -[Aster Api Key](./Demo/aster-api-key-registration.md) +[Aster Api Key](./demo/aster-api-key-registration.md) # Aster 现货资产归集脚本示例 -[Aster 现货资产归集脚本示例](./Demo/consolidation.js) +[Aster 现货资产归集脚本示例](./demo/consolidation.js) # Aster 充值提现 -[Aster Deposit and Withdrawal](./Demo/aster-deposit-withdrawal.md) +[Aster Deposit and Withdrawal](./demo/aster-deposit-withdrawal.md) # Aster Chain RPC From 8c2c5ddc8d844a6062b9f344e2dac607fe6f168c Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Tue, 7 Apr 2026 18:42:39 +0800 Subject: [PATCH 090/131] docs: rewrite README with structure, quick start, and full doc links Co-Authored-By: Claude Sonnet 4.6 --- README.md | 85 +++++++++++++++++++++++++++++++++++++------------------ 1 file changed, 57 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index 0d73996..3b3c8d7 100644 --- a/README.md +++ b/README.md @@ -1,51 +1,80 @@ -# API Documentation for Aster Finance Futures +# Aster API Docs -[Aster Finance Futures API Document](./V1(Legacy)/EN/aster-finance-futures-api.md) +Official API documentation for Aster. -# Aster Finance Futures API 文档 +## 📂 Structure -[Aster Finance Futures API 文档](./V1(Legacy)/中文/aster-finance-futures-api_CN.md) +``` +RPC/ +├── aster-chain-rpc.md +└── aster-chain-rpc_CN.md -# API V3 Documentation for Aster Finance Futures +V1(Legacy)/ +├── EN/ +│ ├── aster-finance-futures-api.md +│ └── aster-finance-spot-api.md +└── 中文/ + ├── aster-finance-futures-api_CN.md + └── aster-finance-spot-api_CN.md -[Aster Finance Futures API V3 Document](./V3(Recommended)/EN/aster-finance-futures-api-v3.md) +V3(Recommended)/ +├── EN/ +│ ├── aster-finance-futures-api-testnet.md +│ ├── aster-finance-futures-api-v3.md +│ ├── aster-finance-spot-api-testnet.md +│ └── aster-finance-spot-api-v3.md +└── 中文/ + ├── aster-finance-futures-api-testnet_CN.md + ├── aster-finance-futures-api-v3_CN.md + ├── aster-finance-spot-api-testnet_CN.md + └── aster-finance-spot-api_CN-v3.md -# Aster Finance Futures API V3 文档 +demo/ +``` -[Aster Finance Futures API V3 文档](./V3(Recommended)/中文/aster-finance-futures-api-v3_CN.md) +## 🚀 Quick Start -# Aster Finance Futures Testnet API V3 文档 +- Use **V3 (Recommended)** for all new integrations +- Starting from **March 25, 2026**, V1 new API Key creation is no longer supported. Existing API Keys will continue to work. +- Choose **EN** / **中文** based on your preference -[Aster Finance Futures Testnet API V3 文档](./V3(Recommended)/EN/aster-finance-futures-api-testnet.md) +## 📖 Docs -# API Documentation for Aster Finance Spot +### API Overview -[Aster Finance Spot API Document](./V1(Legacy)/EN/aster-finance-spot-api.md) +- [Aster API Overview](./Aster%20API%20Overview.md) -# Aster Finance Spot API 文档 +### RPC -[Aster Finance Spot API 文档](./V1(Legacy)/中文/aster-finance-spot-api_CN.md) +- [Aster Chain RPC](./RPC/aster-chain-rpc.md) +- [Aster Chain RPC 文档](./RPC/aster-chain-rpc_CN.md) -# Aster Finance Spot Testnet API V3 文档 +### V3 Futures API (Recommended) -[Aster Finance Spot Testnet API V3 文档](./V3(Recommended)/EN/aster-finance-spot-api-testnet.md) +- [Futures API V3 (EN)](./V3(Recommended)/EN/aster-finance-futures-api-v3.md) +- [Futures API V3 (中文)](./V3(Recommended)/中文/aster-finance-futures-api-v3_CN.md) +- [Futures Testnet API V3 (EN)](./V3(Recommended)/EN/aster-finance-futures-api-testnet.md) +- [Futures Testnet API V3 (中文)](./V3(Recommended)/中文/aster-finance-futures-api-testnet_CN.md) -# Aster Finance Spot Asset Consolidation +### V3 Spot API (Recommended) -[Aster Finance Spot Asset Consolidation](./demo/consolidation.js) +- [Spot API V3 (EN)](./V3(Recommended)/EN/aster-finance-spot-api-v3.md) +- [Spot API V3 (中文)](./V3(Recommended)/中文/aster-finance-spot-api_CN-v3.md) +- [Spot Testnet API V3 (EN)](./V3(Recommended)/EN/aster-finance-spot-api-testnet.md) +- [Spot Testnet API V3 (中文)](./V3(Recommended)/中文/aster-finance-spot-api-testnet_CN.md) -# Aster Api Key +### V1 Futures API (Legacy) -[Aster Api Key](./demo/aster-api-key-registration.md) +- [Futures API V1 (EN)](./V1(Legacy)/EN/aster-finance-futures-api.md) +- [Futures API V1 (中文)](./V1(Legacy)/中文/aster-finance-futures-api_CN.md) -# Aster 现货资产归集脚本示例 +### V1 Spot API (Legacy) -[Aster 现货资产归集脚本示例](./demo/consolidation.js) +- [Spot API V1 (EN)](./V1(Legacy)/EN/aster-finance-spot-api.md) +- [Spot API V1 (中文)](./V1(Legacy)/中文/aster-finance-spot-api_CN.md) -# Aster 充值提现 +### Demo -[Aster Deposit and Withdrawal](./demo/aster-deposit-withdrawal.md) - -# Aster Chain RPC - -[Aster Chain RPC](./RPC/aster-chain-rpc.md) +- [API Key Registration](./demo/aster-api-key-registration.md) +- [Spot Asset Consolidation](./demo/consolidation.js) +- [Deposit & Withdrawal](./demo/aster-deposit-withdrawal.md) From 0b3b56ccd1dc237c51c7073af6dc9441618c1470 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Tue, 7 Apr 2026 18:46:27 +0800 Subject: [PATCH 091/131] docs: update README structure and doc links order Co-Authored-By: Claude Sonnet 4.6 --- README.md | 40 +++++----------------------------------- 1 file changed, 5 insertions(+), 35 deletions(-) diff --git a/README.md b/README.md index 3b3c8d7..c80d3d4 100644 --- a/README.md +++ b/README.md @@ -2,36 +2,6 @@ Official API documentation for Aster. -## 📂 Structure - -``` -RPC/ -├── aster-chain-rpc.md -└── aster-chain-rpc_CN.md - -V1(Legacy)/ -├── EN/ -│ ├── aster-finance-futures-api.md -│ └── aster-finance-spot-api.md -└── 中文/ - ├── aster-finance-futures-api_CN.md - └── aster-finance-spot-api_CN.md - -V3(Recommended)/ -├── EN/ -│ ├── aster-finance-futures-api-testnet.md -│ ├── aster-finance-futures-api-v3.md -│ ├── aster-finance-spot-api-testnet.md -│ └── aster-finance-spot-api-v3.md -└── 中文/ - ├── aster-finance-futures-api-testnet_CN.md - ├── aster-finance-futures-api-v3_CN.md - ├── aster-finance-spot-api-testnet_CN.md - └── aster-finance-spot-api_CN-v3.md - -demo/ -``` - ## 🚀 Quick Start - Use **V3 (Recommended)** for all new integrations @@ -44,11 +14,6 @@ demo/ - [Aster API Overview](./Aster%20API%20Overview.md) -### RPC - -- [Aster Chain RPC](./RPC/aster-chain-rpc.md) -- [Aster Chain RPC 文档](./RPC/aster-chain-rpc_CN.md) - ### V3 Futures API (Recommended) - [Futures API V3 (EN)](./V3(Recommended)/EN/aster-finance-futures-api-v3.md) @@ -73,6 +38,11 @@ demo/ - [Spot API V1 (EN)](./V1(Legacy)/EN/aster-finance-spot-api.md) - [Spot API V1 (中文)](./V1(Legacy)/中文/aster-finance-spot-api_CN.md) +### RPC + +- [Aster Chain RPC](./RPC/aster-chain-rpc.md) +- [Aster Chain RPC 文档](./RPC/aster-chain-rpc_CN.md) + ### Demo - [API Key Registration](./demo/aster-api-key-registration.md) From b78278fe766073535b5dc0d52d49f2051aedb7b0 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Thu, 9 Apr 2026 14:36:33 +0800 Subject: [PATCH 092/131] docs: rewrite V3 Nonce Mechanism section across all docs (CN & EN) Replace prose paragraphs with structured bullet-point format: - Add 10-second server time tolerance requirement - Add numbered request processing flow - Clarify 100-nonce per-user limit with min-value rejection rule - Add section to testnet files (futures & spot, CN & EN) Co-Authored-By: Claude Sonnet 4.6 --- .../EN/aster-finance-futures-api-testnet.md | 18 +++++++++++++++++- .../EN/aster-finance-futures-api-v3.md | 16 +++++++++++----- .../EN/aster-finance-spot-api-testnet.md | 18 +++++++++++++++++- .../EN/aster-finance-spot-api-v3.md | 14 ++++++++++---- .../aster-finance-futures-api-testnet_CN.md" | 18 +++++++++++++++++- .../aster-finance-futures-api-v3_CN.md" | 16 +++++++++++----- .../aster-finance-spot-api-testnet_CN.md" | 18 +++++++++++++++++- .../aster-finance-spot-api_CN-v3.md" | 15 +++++++++++---- 8 files changed, 111 insertions(+), 22 deletions(-) diff --git a/V3(Recommended)/EN/aster-finance-futures-api-testnet.md b/V3(Recommended)/EN/aster-finance-futures-api-testnet.md index 0b24e21..112a3de 100644 --- a/V3(Recommended)/EN/aster-finance-futures-api-testnet.md +++ b/V3(Recommended)/EN/aster-finance-futures-api-testnet.md @@ -156,6 +156,22 @@ * For POST, PUT, and DELETE method APIs, send data in the request body (content type application/x-www-form-urlencoded) * Parameters may be sent in any order. +### V3 Nonce Mechanism + +* **Nonce** is used to validate the **validity, uniqueness, and replay-protection** of requests. Clients should use the **current timestamp (microsecond precision)** as the nonce, and the difference from server time must not exceed **10 seconds**. + +* Request processing flow: + + 1. If the nonce **has already been used** → rejected as a **duplicate request** + 2. Otherwise, the system checks whether it is **too old** + +* To improve performance, each user maintains only the **most recent 100 nonces**: + + * If the list is full and the new nonce is **smaller than the current minimum** → rejected as **expired** + * Otherwise, the **oldest nonce is removed** and the new one is added + +* Overall effect: **prevents duplicates and stale requests, retaining only recent valid requests** + ## LIMITS * The `/fapi/v3/exchangeInfo` `rateLimits` array contains objects related to the exchange's `RAW_REQUEST`, `REQUEST_WEIGHT`, and `ORDER` rate limits. These are further defined in the `ENUM definitions` section under `Rate limiters (rateLimitType)`. @@ -231,7 +247,7 @@ It is recommended to use a small recvWindow of 5000 or less! | signer | 0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0 |[Click Here](https://www.asterdex-testnet.com/en/api-wallet) | | privateKey | 0x4fd0a42218f3eae43a6ce26d22544e986139a01e5b34a62db53757ffca81bae1 |[Click Here](https://www.asterdex-testnet.com/en/api-wallet) | -#### The nonce parameter is the current system time in microseconds. If it exceeds the system time or lags behind it by more than 5 seconds, the request is considered invalid. +#### The nonce parameter is the current system time in microseconds. If it exceeds the system time or lags behind it by more than 10 seconds, the request is considered invalid. ```python #python diff --git a/V3(Recommended)/EN/aster-finance-futures-api-v3.md b/V3(Recommended)/EN/aster-finance-futures-api-v3.md index 81fc299..55690cb 100644 --- a/V3(Recommended)/EN/aster-finance-futures-api-v3.md +++ b/V3(Recommended)/EN/aster-finance-futures-api-v3.md @@ -161,13 +161,19 @@ ### V3 Nonce Mechanism -* A nonce is essentially a number used to validate that a user request is valid, not duplicated, and not outdated. It is generally recommended to use the current timestamp as the nonce, preferably with microsecond precision, to ensure uniqueness and monotonicity. +* **Nonce** is used to validate the **validity, uniqueness, and replay-protection** of requests. Clients should use the **current timestamp (microsecond precision)** as the nonce, and the difference from server time must not exceed **10 seconds**. -* When a new action comes in, the system first checks if that number has already been used—if it has, the action is rejected as a duplicate. If it’s new, the system then checks whether it’s too old compared to the recent ones it has already seen. +* Request processing flow: -* To do this efficiently, it only keeps a limited number of the most recent nonces for each user. If the list is already full and the new number is smaller than the oldest one in the list, it gets rejected because it’s considered outdated. Otherwise, the system removes the oldest number and adds the new one. + 1. If the nonce **has already been used** → rejected as a **duplicate request** + 2. Otherwise, the system checks whether it is **too old** -* In simple terms, this mechanism ensures that user actions are processed in a clean and reliable way—preventing repeated requests, ignoring stale ones, and only keeping track of the most relevant recent activity. +* To improve performance, each user maintains only the **most recent 100 nonces**: + + * If the list is full and the new nonce is **smaller than the current minimum** → rejected as **expired** + * Otherwise, the **oldest nonce is removed** and the new one is added + +* Overall effect: **prevents duplicates and stale requests, retaining only recent valid requests** ## LIMITS @@ -234,7 +240,7 @@ It is strongly recommended to use websocket stream for getting data as much as p | signer | 0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0 |[Click Here](https://www.asterdex.com/en/api-wallet) | | privateKey | 0x4fd0a42218f3eae43a6ce26d22544e986139a01e5b34a62db53757ffca81bae1 |[Click Here](https://www.asterdex.com/en/api-wallet) | -#### The nonce parameter is the current system time in microseconds. If it exceeds the system time or lags behind it by more than 5 seconds, the request is considered invalid. +#### The nonce parameter is the current system time in microseconds. If it exceeds the system time or lags behind it by more than 10 seconds, the request is considered invalid. ```python #python nonce = math.trunc(time.time()*1000000) diff --git a/V3(Recommended)/EN/aster-finance-spot-api-testnet.md b/V3(Recommended)/EN/aster-finance-spot-api-testnet.md index fcce260..2001e38 100644 --- a/V3(Recommended)/EN/aster-finance-spot-api-testnet.md +++ b/V3(Recommended)/EN/aster-finance-spot-api-testnet.md @@ -6,6 +6,22 @@ ### Attention * TESTUSDT or any other symbols starting with TEST are symbols used for Aster’s INTERNAL TESTING ONLY. Please DO NOT trade on these symbols starting with TEST. Aster does not hold any accountability for loss of funds due to trading on these symbols. However, if you run into issues, you may contact support about this any time, we will try to help you recover your funds. +### V3 Nonce Mechanism + +* **Nonce** is used to validate the **validity, uniqueness, and replay-protection** of requests. Clients should use the **current timestamp (microsecond precision)** as the nonce, and the difference from server time must not exceed **10 seconds**. + +* Request processing flow: + + 1. If the nonce **has already been used** → rejected as a **duplicate request** + 2. Otherwise, the system checks whether it is **too old** + +* To improve performance, each user maintains only the **most recent 100 nonces**: + + * If the list is full and the new nonce is **smaller than the current minimum** → rejected as **expired** + * Otherwise, the **oldest nonce is removed** and the new one is added + +* Overall effect: **prevents duplicates and stale requests, retaining only recent valid requests** + ### HTTP return codes * HTTP `4XX` status codes are used to indicate errors in the request content, behavior, or format. The problem lies with the requester. @@ -114,7 +130,7 @@ You are advised to use WebSocket messages to obtain the corresponding data as mu | signer | 0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0 |[Click Here](https://www.asterdex-testnet.com/en/api-wallet) | | privateKey | 0x4fd0a42218f3eae43a6ce26d22544e986139a01e5b34a62db53757ffca81bae1 |[Click Here](https://www.asterdex-testnet.com/en/api-wallet) | -#### The nonce parameter is the current system time in microseconds. If it exceeds the system time or lags behind it by more than 5 seconds, the request is considered invalid. +#### The nonce parameter is the current system time in microseconds. If it exceeds the system time or lags behind it by more than 10 seconds, the request is considered invalid. ```python #python diff --git a/V3(Recommended)/EN/aster-finance-spot-api-v3.md b/V3(Recommended)/EN/aster-finance-spot-api-v3.md index da350fa..a9bdcea 100644 --- a/V3(Recommended)/EN/aster-finance-spot-api-v3.md +++ b/V3(Recommended)/EN/aster-finance-spot-api-v3.md @@ -16,13 +16,19 @@ If an API Key is accidentally exposed, immediately delete that Key and generate ### V3 Nonce Mechanism -* A nonce is essentially a number used to validate that a user request is valid, not duplicated, and not outdated. It is generally recommended to use the current timestamp as the nonce, preferably with microsecond precision, to ensure uniqueness and monotonicity. +* **Nonce** is used to validate the **validity, uniqueness, and replay-protection** of requests. Clients should use the **current timestamp (microsecond precision)** as the nonce, and the difference from server time must not exceed **10 seconds**. -* When a new action comes in, the system first checks if that number has already been used—if it has, the action is rejected as a duplicate. If it’s new, the system then checks whether it’s too old compared to the recent ones it has already seen. +* Request processing flow: -* To do this efficiently, it only keeps a limited number of the most recent nonces for each user. If the list is already full and the new number is smaller than the oldest one in the list, it gets rejected because it’s considered outdated. Otherwise, the system removes the oldest number and adds the new one. + 1. If the nonce **has already been used** → rejected as a **duplicate request** + 2. Otherwise, the system checks whether it is **too old** -* In simple terms, this mechanism ensures that user actions are processed in a clean and reliable way—preventing repeated requests, ignoring stale ones, and only keeping track of the most relevant recent activity. +* To improve performance, each user maintains only the **most recent 100 nonces**: + + * If the list is full and the new nonce is **smaller than the current minimum** → rejected as **expired** + * Otherwise, the **oldest nonce is removed** and the new one is added + +* Overall effect: **prevents duplicates and stale requests, retaining only recent valid requests** ### HTTP return codes diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" index 430e102..25b16b7 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" @@ -145,6 +145,22 @@ * `POST`, `PUT`, 和 `DELETE` 方法的接口, 在 `request body`中发送(content type `application/x-www-form-urlencoded`) * 对参数的顺序不做要求。 +### V3 Nonce 机制 + +* **Nonce** 用于校验请求的**有效性、唯一性和防重放**。客户端应使用**当前时间戳(微秒级)****作为 nonce**,且与服务端时间误差不超过 **10 秒**。 + +* 请求处理流程: + + 1. 若 nonce **已使用过** → 判定为**重复请求并拒绝** + 2. 否则判断是否**过旧** + +* 为提升性能,每个用户仅维护**最近 100 个 nonce**: + + * 若已满且新 nonce **小于当前最小值** → 判定为**过期并拒绝** + * 否则**移除最旧的 nonce**,加入新的 + +* 总体效果:**防重复、防过期,仅保留近期有效请求** + ## 访问限制 * 在 `/fapi/v3/exchangeInfo`接口中`rateLimits`数组里包含有REST接口(不限于本篇的REST接口)的访问限制。包括带权重的访问频次限制、下单速率限制。本篇`枚举定义`章节有限制类型的进一步说明。 * 违反上述任何一个访问限制都会收到HTTP 429,这是一个警告. @@ -204,7 +220,7 @@ user | 0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e | 登陆钱包地址 signer | 0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0 | [点击这里获取](https://www.asterdex-testnet.com/zh-CN/api-wallet) privateKey | 0x4fd0a42218f3eae43a6ce26d22544e986139a01e5b34a62db53757ffca81bae1 | [点击这里获取](https://www.asterdex-testnet.com/zh-CN/api-wallet) -#### 示例 : nonce参数为当前系统微秒值,超过系统时间,或者落后系统时间超过5s为非法请求 +#### 示例 : nonce参数为当前系统微秒值,超过系统时间,或者落后系统时间超过10s为非法请求 ```python #python nonce = math.trunc(time.time()*1000000) diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" index a4833a9..4883670 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" @@ -155,13 +155,19 @@ ### V3 Nonce 机制 -* nonce 本质上是一个用于校验用户请求是否有效、是否重复以及是否过期的数字。通常建议用户直接使用当前时间戳(timestamp)作为 nonce,并使用微秒级(microsecond)精度,以确保其唯一性和递增性。 -* 当一个新的请求到来时,系统会先检查这个 nonce 是否已经被使用过——如果是,就会将该请求判定为重复请求并拒绝。如果是新的 nonce,系统会进一步判断它是否相对于当前已记录的那些 nonce 来说过旧。 +* **Nonce** 用于校验请求的**有效性、唯一性和防重放**。客户端应使用**当前时间戳(微秒级)****作为 nonce**,且与服务端时间误差不超过 **10 秒**。 -* 为了提高效率,系统只会为每个用户保存有限数量的最近 nonce。如果这个列表已经满了,而新的 nonce 又比列表中最旧的那个还小,那么该请求就会被拒绝,因为它被认为是过期的。否则,系统会移除最旧的 nonce,并将新的 nonce 加入列表。 +* 请求处理流程: -* 简单来说,这种机制可以确保用户请求以一种干净、可靠的方式被处理——既能防止重复请求,又能忽略过期请求,同时只保留最相关的近期操作记录。 + 1. 若 nonce **已使用过** → 判定为**重复请求并拒绝** + 2. 否则判断是否**过旧** +* 为提升性能,每个用户仅维护**最近 100 个 nonce**: + + * 若已满且新 nonce **小于当前最小值** → 判定为**过期并拒绝** + * 否则**移除最旧的 nonce**,加入新的 + +* 总体效果:**防重复、防过期,仅保留近期有效请求** ## 访问限制 * 在 `/fapi/v3/exchangeInfo`接口中`rateLimits`数组里包含有REST接口(不限于本篇的REST接口)的访问限制。包括带权重的访问频次限制、下单速率限制。本篇`枚举定义`章节有限制类型的进一步说明。 @@ -222,7 +228,7 @@ user | 0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e | 登陆钱包地址 signer | 0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0 | [点击这里获取](https://www.asterdex.com/zh-CN/api-wallet) privateKey | 0x4fd0a42218f3eae43a6ce26d22544e986139a01e5b34a62db53757ffca81bae1 | [点击这里获取](https://www.asterdex.com/zh-CN/api-wallet) -#### 示例 : nonce参数为当前系统微秒值,超过系统时间,或者落后系统时间超过5s为非法请求 +#### 示例 : nonce参数为当前系统微秒值,超过系统时间,或者落后系统时间超过10s为非法请求 ```python #python nonce = math.trunc(time.time()*1000000) diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-spot-api-testnet_CN.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-spot-api-testnet_CN.md" index f2e017e..4063835 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-spot-api-testnet_CN.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-spot-api-testnet_CN.md" @@ -40,6 +40,22 @@ * 单个连接最多可以订阅 **1024** 个Streams。 +### V3 Nonce 机制 + +* **Nonce** 用于校验请求的**有效性、唯一性和防重放**。客户端应使用**当前时间戳(微秒级)****作为 nonce**,且与服务端时间误差不超过 **10 秒**。 + +* 请求处理流程: + + 1. 若 nonce **已使用过** → 判定为**重复请求并拒绝** + 2. 否则判断是否**过旧** + +* 为提升性能,每个用户仅维护**最近 100 个 nonce**: + + * 若已满且新 nonce **小于当前最小值** → 判定为**过期并拒绝** + * 否则**移除最旧的 nonce**,加入新的 + +* 总体效果:**防重复、防过期,仅保留近期有效请求** + ## 接口鉴权类型 * 每个接口都有自己的鉴权类型,鉴权类型决定了访问时应当进行何种鉴权 * 如果需要鉴权,应当在请求体中添加signer @@ -64,7 +80,7 @@ user | 0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e | 登陆钱包地址 signer | 0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0 | [点击这里获取](https://www.asterdex-testnet.com/zh-CN/api-wallet) privateKey | 0x4fd0a42218f3eae43a6ce26d22544e986139a01e5b34a62db53757ffca81bae1 | [点击这里获取](https://www.asterdex-testnet.com/zh-CN/api-wallet) -#### 示例 : nonce参数为当前系统微秒值,超过系统时间,或者落后系统时间超过5s为非法请求 +#### 示例 : nonce参数为当前系统微秒值,超过系统时间,或者落后系统时间超过10s为非法请求 ```python #python nonce = math.trunc(time.time()*1000000) diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-spot-api_CN-v3.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-spot-api_CN-v3.md" index 958a25c..1d144c4 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-spot-api_CN-v3.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-spot-api_CN-v3.md" @@ -42,12 +42,19 @@ ### V3 Nonce 机制 -* nonce 本质上是一个用于校验用户请求是否有效、是否重复以及是否过期的数字。通常建议用户直接使用当前时间戳(timestamp)作为 nonce,并使用微秒级(microsecond)精度,以确保其唯一性和递增性。 -* 当一个新的请求到来时,系统会先检查这个 nonce 是否已经被使用过——如果是,就会将该请求判定为重复请求并拒绝。如果是新的 nonce,系统会进一步判断它是否相对于当前已记录的那些 nonce 来说过旧。 +* **Nonce** 用于校验请求的**有效性、唯一性和防重放**。客户端应使用**当前时间戳(微秒级)****作为 nonce**,且与服务端时间误差不超过 **10 秒**。 -* 为了提高效率,系统只会为每个用户保存有限数量的最近 nonce。如果这个列表已经满了,而新的 nonce 又比列表中最旧的那个还小,那么该请求就会被拒绝,因为它被认为是过期的。否则,系统会移除最旧的 nonce,并将新的 nonce 加入列表。 +* 请求处理流程: -* 简单来说,这种机制可以确保用户请求以一种干净、可靠的方式被处理——既能防止重复请求,又能忽略过期请求,同时只保留最相关的近期操作记录。 + 1. 若 nonce **已使用过** → 判定为**重复请求并拒绝** + 2. 否则判断是否**过旧** + +* 为提升性能,每个用户仅维护**最近 100 个 nonce**: + + * 若已满且新 nonce **小于当前最小值** → 判定为**过期并拒绝** + * 否则**移除最旧的 nonce**,加入新的 + +* 总体效果:**防重复、防过期,仅保留近期有效请求** --- ## 访问限制 From 44f4974af8f83509a323efc444d71d3e8a6ba8e1 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Fri, 10 Apr 2026 11:14:13 +0800 Subject: [PATCH 093/131] docs: add Bind Sub-Account API endpoint (EN & CN) Co-Authored-By: Claude Sonnet 4.6 --- .../EN/aster-finance-futures-api-testnet.md | 71 ++++++++++++++++++ .../EN/aster-finance-futures-api-v3.md | 71 ++++++++++++++++++ .../aster-finance-futures-api-testnet_CN.md" | 73 ++++++++++++++++++- .../aster-finance-futures-api-v3_CN.md" | 67 +++++++++++++++++ 4 files changed, 281 insertions(+), 1 deletion(-) diff --git a/V3(Recommended)/EN/aster-finance-futures-api-testnet.md b/V3(Recommended)/EN/aster-finance-futures-api-testnet.md index 112a3de..81a50ee 100644 --- a/V3(Recommended)/EN/aster-finance-futures-api-testnet.md +++ b/V3(Recommended)/EN/aster-finance-futures-api-testnet.md @@ -95,6 +95,7 @@ - [Position ADL Quantile Estimation (USER_DATA)](#position-adl-quantile-estimation-user_data) - [User's Force Orders (USER_DATA)](#users-force-orders-user_data) - [User Commission Rate (USER_DATA)](#user-commission-rate-user_data) + - [Bind Sub-Account (USER_DATA)](#bind-sub-account-user_data) - [User Data Streams](#user-data-streams) - [Start User Data Stream (USER_STREAM)](#start-user-data-stream-user_stream) - [Keepalive User Data Stream (USER_STREAM)](#keepalive-user-data-stream-user_stream) @@ -3353,6 +3354,76 @@ Get trades for a specific account and symbol. | recvWindow | LONG | NO | | | timestamp | LONG | YES | | + +# Bind Sub-Account (USER_DATA) + +> **Response:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +`POST /fapi/v3/sub-accounts/bind` + +**Weight:** 5 + +**Parameters:** + +Name | Type | Required | Description +------------------ | ------- | -------- | --- +childAddress | STRING | YES | Sub-account wallet address +name | STRING | YES | Sub-account name +nonce | LONG | YES | Microsecond-level timestamp, used for replay attack prevention +user | STRING | YES | Master account wallet address +childSignature | STRING | YES | Sub-account's signature over the message body (see Signature Instructions below) +signature | STRING | YES | Master account's signature over the message body,**must be signed using the master account's wallet private key**(see Signature Instructions below) + +--- + +### Signature Instructions + +This endpoint requires**two independent signatures**,The message body differs between the two: + +#### Step 1:Sub-Account Signature(childSignature) + +The sub-account signs the following message body using**its own wallet private key:**: + +``` +childAddress={childAddress}&name={name}&nonce={nonce}&user={user} +``` + +#### Step 2:Master Account Signature(signature) + +The master account signs the following message body using**its own wallet private key**(not the API Key),The message body**appends `childSignature`** to the one used in Step 1: + +``` +childAddress={childAddress}&name={name}&nonce={nonce}&user={user}&childSignature={childSignature} +``` + +> The key difference between the two message bodies: the master account's message body**includes** `childSignature`, while the sub-account's does not. + +#### Supported Signing Algorithms + +| Account Type | Signing Algorithm | Encoding Format | +|---------|---------|---------| +| EVM Address | EIP-712 Typed Data(chainId=1666,message.msg=message body) | Hex | +| Solana Address | Ed25519 | Base58 | + +> The address types of the master account and sub-account must match (EVM with EVM, Solana with Solana). + +--- + +### Important Notes + +* `signature` must be signed using the**master account's wallet private key**— the signer private key must not be used as a substitute +* `childSignature` and `signature` are not interchangeable +* The `user` field must match the authenticated master account address and cannot be forged +* Only **whitelisted addresses** are supported for creation. Please contact the **project team** for configuration. + + # User Data Streams * The base API endpoint is: **https://fapi.asterdex-testnet.com** diff --git a/V3(Recommended)/EN/aster-finance-futures-api-v3.md b/V3(Recommended)/EN/aster-finance-futures-api-v3.md index 55690cb..9380f93 100644 --- a/V3(Recommended)/EN/aster-finance-futures-api-v3.md +++ b/V3(Recommended)/EN/aster-finance-futures-api-v3.md @@ -98,6 +98,7 @@ - [Get User MMP (USER_DATA)](#get-user-mmp-user_data) - [Delete User MMP (USER_DATA)](#delete-user-mmp-user_data) - [Reset User MMP (USER_DATA)](#reset-user-mmp-user_data) + - [Bind Sub-Account (USER_DATA)](#bind-sub-account-user_data) - [User Data Streams](#user-data-streams) - [Start User Data Stream (USER_STREAM)](#start-user-data-stream-user_stream) - [Keepalive User Data Stream (USER_STREAM)](#keepalive-user-data-stream-user_stream) @@ -3615,6 +3616,76 @@ true | symbol | STRING | YES | | +# Bind Sub-Account (USER_DATA) + +> **Response:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +`POST /fapi/v3/sub-accounts/bind` + +**Weight:** 5 + +**Parameters:** + +Name | Type | Required | Description +------------------ | ------- | -------- | --- +childAddress | STRING | YES | Sub-account wallet address +name | STRING | YES | Sub-account name +nonce | LONG | YES | Microsecond-level timestamp, used for replay attack prevention +user | STRING | YES | Master account wallet address +childSignature | STRING | YES | Sub-account's signature over the message body (see Signature Instructions below) +signature | STRING | YES | Master account's signature over the message body,**must be signed using the master account's wallet private key**(see Signature Instructions below) + +--- + +### Signature Instructions + +This endpoint requires**two independent signatures**,The message body differs between the two: + +#### Step 1:Sub-Account Signature(childSignature) + +The sub-account signs the following message body using**its own wallet private key:**: + +``` +childAddress={childAddress}&name={name}&nonce={nonce}&user={user} +``` + +#### Step 2:Master Account Signature(signature) + +The master account signs the following message body using**its own wallet private key**(not the API Key),The message body**appends `childSignature`** to the one used in Step 1: + +``` +childAddress={childAddress}&name={name}&nonce={nonce}&user={user}&childSignature={childSignature} +``` + +> The key difference between the two message bodies: the master account's message body**includes** `childSignature`, while the sub-account's does not. + +#### Supported Signing Algorithms + +| Account Type | Signing Algorithm | Encoding Format | +|---------|---------|---------| +| EVM Address | EIP-712 Typed Data(chainId=1666,message.msg=message body) | Hex | +| Solana Address | Ed25519 | Base58 | + +> The address types of the master account and sub-account must match (EVM with EVM, Solana with Solana). + +--- + +### Important Notes + +* `signature` must be signed using the**master account's wallet private key**— the signer private key must not be used as a substitute +* `childSignature` and `signature` are not interchangeable +* The `user` field must match the authenticated master account address and cannot be forged +* Only **whitelisted addresses** are supported for creation. Please contact the **project team** for configuration. + + + # User Data Streams * The base API endpoint is: **https://fapi.asterdex.com** diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" index 25b16b7..93882a3 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" @@ -88,7 +88,9 @@ - [杠杆分层标准 (USER_DATA)](#杠杆分层标准-user_data) - [持仓ADL队列估算 (USER_DATA)](#持仓adl队列估算-user_data) - [用户强平单历史 (USER_DATA)](#用户强平单历史-user_data) - - [用户手续费率 (USER_DATA)](#用户手续费率-user_data)- [Websocket 账户信息推送](#websocket-账户信息推送) + - [用户手续费率 (USER_DATA)](#用户手续费率-user_data) + - [绑定子账户 (USER_DATA)](#绑定子账户-user_data) +- [Websocket 账户信息推送](#websocket-账户信息推送) - [生成listenKey (USER_STREAM)](#生成listenkey-user_stream) - [延长listenKey有效期 (USER_STREAM)](#延长listenkey有效期-user_stream) - [关闭listenKey (USER_STREAM)](#关闭listenkey-user_stream) @@ -3577,6 +3579,75 @@ GET /fapi/v3/commissionRate`` symbol | STRING | YES +# 绑定子账户 (USER_DATA) + +> **响应:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +`POST /fapi/v3/sub-accounts/bind` + +**权重:** 5 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------------ | ------- | -------- | --- +childAddress | STRING | YES | 子账户钱包地址 +name | STRING | YES | 子账户名称 +nonce | LONG | YES | 微秒级时间戳,用于防重放 +user | STRING | YES | 母账户钱包地址 +childSignature | STRING | YES | 子账户对消息体的签名(见下方签名说明) +signature | STRING | YES | 母账户对消息体的签名,**必须使用母账户钱包私钥签名**(见下方签名说明) + +--- + +### 签名说明 + +本接口需要**两次独立签名**,两次签名的消息体不同: + +#### 第一步:子账户签名(childSignature) + +子账户使用**自己的钱包私钥**对以下消息体签名: + +``` +childAddress={childAddress}&name={name}&nonce={nonce}&user={user} +``` + +#### 第二步:母账户签名(signature) + +母账户使用**自己的钱包私钥**(非 API Key)对以下消息体签名,消息体在第一步基础上**追加了 `childSignature`**: + +``` +childAddress={childAddress}&name={name}&nonce={nonce}&user={user}&childSignature={childSignature} +``` + +> 两次签名消息体的关键区别:母账户的签名消息体**包含** `childSignature`,子账户的不包含。 + +#### 支持的签名算法 + +| 账户类型 | 签名算法 | 编码格式 | +|---------|---------|---------| +| EVM 地址 | EIP-712 Typed Data(chainId=1666,message.msg=消息体) | Hex | +| Solana 地址 | Ed25519 | Base58 | + +> 母账户与子账户的地址类型必须一致(EVM 对 EVM,Solana 对 Solana)。 + +--- + +### 注意事项 + +* `signature` 必须使用**母账户钱包私钥**签名,不可使用signer私钥替代 +* `childSignature` 与 `signature` 不可互换 +* `user` 字段必须与已认证的母账户地址一致,不可伪造 +* 只支持**白名单地址**创建,需要联系**项目方**配置 + + # Websocket 账户信息推送 diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" index 4883670..f67504e 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" @@ -96,6 +96,7 @@ - [获取用户MMP (USER_DATA)](#获取用户mmp-user_data) - [删除用户MMP (USER_DATA)](#删除用户mmp-user_data) - [重置用户MMP (USER_DATA)](#重置用户mmp-user_data) + - [绑定子账户 (USER_DATA)](#绑定子账户-user_data) - [Websocket 账户信息推送](#websocket-账户信息推送) - [生成listenKey (USER_STREAM)](#生成listenkey-user_stream) - [延长listenKey有效期 (USER_STREAM)](#延长listenkey有效期-user_stream) @@ -3767,7 +3768,73 @@ POST /fapi/v3/mmpReset`` ------------ | ------------ | ------------ | ------------ symbol | STRING | YES +# 绑定子账户 (USER_DATA) +> **响应:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +`POST /fapi/v3/sub-accounts/bind` + +**权重:** 5 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------------ | ------- | -------- | --- +childAddress | STRING | YES | 子账户钱包地址 +name | STRING | YES | 子账户名称 +nonce | LONG | YES | 微秒级时间戳,用于防重放 +user | STRING | YES | 母账户钱包地址 +childSignature | STRING | YES | 子账户对消息体的签名(见下方签名说明) +signature | STRING | YES | 母账户对消息体的签名,**必须使用母账户钱包私钥签名**(见下方签名说明) + +--- + +### 签名说明 + +本接口需要**两次独立签名**,两次签名的消息体不同: + +#### 第一步:子账户签名(childSignature) + +子账户使用**自己的钱包私钥**对以下消息体签名: + +``` +childAddress={childAddress}&name={name}&nonce={nonce}&user={user} +``` + +#### 第二步:母账户签名(signature) + +母账户使用**自己的钱包私钥**(非 API Key)对以下消息体签名,消息体在第一步基础上**追加了 `childSignature`**: + +``` +childAddress={childAddress}&name={name}&nonce={nonce}&user={user}&childSignature={childSignature} +``` + +> 两次签名消息体的关键区别:母账户的签名消息体**包含** `childSignature`,子账户的不包含。 + +#### 支持的签名算法 + +| 账户类型 | 签名算法 | 编码格式 | +|---------|---------|---------| +| EVM 地址 | EIP-712 Typed Data(chainId=1666,message.msg=消息体) | Hex | +| Solana 地址 | Ed25519 | Base58 | + +> 母账户与子账户的地址类型必须一致(EVM 对 EVM,Solana 对 Solana)。 + +--- + +### 注意事项 + +* `signature` 必须使用**母账户钱包私钥**签名,不可使用signer私钥替代 +* `childSignature` 与 `signature` 不可互换 +* `user` 字段必须与已认证的母账户地址一致,不可伪造 +* 只支持**白名单地址**创建,需要联系**项目方**配置 # Websocket 账户信息推送 From 8c94a2e8f6432a9d533d366bc97fe758ea9ae10b Mon Sep 17 00:00:00 2001 From: Vanessa Date: Mon, 13 Apr 2026 16:59:56 +0800 Subject: [PATCH 094/131] doc update --- V1(Legacy)/EN/aster-finance-futures-api.md | 2 +- .../\344\270\255\346\226\207/aster-finance-futures-api_CN.md" | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/V1(Legacy)/EN/aster-finance-futures-api.md b/V1(Legacy)/EN/aster-finance-futures-api.md index 6c08fad..2c44830 100644 --- a/V1(Legacy)/EN/aster-finance-futures-api.md +++ b/V1(Legacy)/EN/aster-finance-futures-api.md @@ -243,7 +243,7 @@ processed within a certain number of milliseconds or be rejected by the server. ### SIGNED Endpoint Examples for POST /fapi/v1/order diff --git "a/V1(Legacy)/\344\270\255\346\226\207/aster-finance-futures-api_CN.md" "b/V1(Legacy)/\344\270\255\346\226\207/aster-finance-futures-api_CN.md" index 4275449..be0e15b 100644 --- "a/V1(Legacy)/\344\270\255\346\226\207/aster-finance-futures-api_CN.md" +++ "b/V1(Legacy)/\344\270\255\346\226\207/aster-finance-futures-api_CN.md" @@ -219,7 +219,7 @@ MARKET_DATA | 需要有效的API-KEY 这是我们设置`recvWindow`的目的所在,如果你从事高频交易,对交易时效性有较高的要求,可以灵活设置recvWindow以达到你的要求。 ### POST /fapi/v1/order 的示例 From 8d4e1a800e9a19181d84a53530a7e56c642eaa75 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Thu, 16 Apr 2026 14:08:57 +0800 Subject: [PATCH 095/131] docs: add Modify Order API endpoint (EN, EN testnet & CN testnet) Co-Authored-By: Claude Sonnet 4.6 --- .../EN/aster-finance-futures-api-testnet.md | 52 ++++++++++++++++++ .../EN/aster-finance-futures-api-v3.md | 54 +++++++++++++++++++ .../aster-finance-futures-api-testnet_CN.md" | 51 ++++++++++++++++++ .../aster-finance-futures-api-v3_CN.md" | 52 ++++++++++++++++++ 4 files changed, 209 insertions(+) diff --git a/V3(Recommended)/EN/aster-finance-futures-api-testnet.md b/V3(Recommended)/EN/aster-finance-futures-api-testnet.md index 81a50ee..1156be5 100644 --- a/V3(Recommended)/EN/aster-finance-futures-api-testnet.md +++ b/V3(Recommended)/EN/aster-finance-futures-api-testnet.md @@ -2233,6 +2233,58 @@ Additional mandatory parameters based on `type`: * Cannot be used with `reduceOnly` parameter * In Hedge Mode,cannot be used with `BUY` orders in `LONG` position side. and cannot be used with `SELL` orders in `SHORT` position side +## Modify Order (TRADE) + +> **Response:** + +```javascript +{ + 'orderId': 405, // Order ID + 'symbol': 'GOOGLUSDT', // Trading pair + 'status': 'NEW', // Order status + 'clientOrderId': 'uOLCC3aiCou3z2YL0sxWIX', // User-defined order ID + 'price': '295.50', // Order price + 'avgPrice': '0.00000', // Average fill price + 'origQty': '0.150', // Original order quantity + 'executedQty': '0', // Filled quantity + 'cumQty': '0', + 'cumQuote': '0', // Filled amount + 'timeInForce': 'GTC', // Time in force + 'type': 'LIMIT', // Order type + 'reduceOnly': False, // Reduce only + 'closePosition': False, // Close all positions on trigger + 'side': 'BUY', // Order side + 'positionSide': 'BOTH', // Position side + 'stopPrice': '0', // Trigger price, invalid for `TRAILING_STOP_MARKET` + 'workingType': 'CONTRACT_PRICE', // Condition price trigger type + 'priceProtect': False, // Conditional order trigger protection enabled + 'origType': 'LIMIT', // Original order type before trigger + 'updateTime': 1776311274450 // Update time +} +``` + +`` +PUT /fapi/v3/order `` + +**Weight:** +1 + +**Parameters:** +Name | Type | Mandatory | Description +---------------- | ------- | -------- | ---- +orderId | LONG | NO | Order ID +origClientOrderId | STRING | NO | User-defined order ID +symbol | STRING | YES| Trading pair +quantity | DECIMAL| YES | Order quantity +price | DECIMAL | YES | Order price + + +* Either `orderId` or `origClientOrderId` must be sent. If both are sent, `orderId` takes precedence. +* At least one of `quantity` or `price` must be sent. +* If the new `quantity` or `price` does not meet `PRICE_FILTER` / `PERCENT_FILTER` / `LOT_SIZE` restrictions, the modification will be rejected and the original order will remain. +* Only `LIMIT` order type is supported. +* Maximum 10000 modifications per order. + ## Place Multiple Orders (TRADE) > **Response:** diff --git a/V3(Recommended)/EN/aster-finance-futures-api-v3.md b/V3(Recommended)/EN/aster-finance-futures-api-v3.md index 9380f93..00892be 100644 --- a/V3(Recommended)/EN/aster-finance-futures-api-v3.md +++ b/V3(Recommended)/EN/aster-finance-futures-api-v3.md @@ -71,6 +71,7 @@ - [Change Multi-Assets Mode (TRADE)](#change-multi-assets-mode-trade) - [Get Current Multi-Assets Mode (USER_DATA)](#get-current-multi-assets-mode-user_data) - [New Order (TRADE)](#new-order--trade) + - [Modify Order (TRADE)](#modify-order-trade) - [Place Multiple Orders (TRADE)](#place-multiple-orders--trade) - [Transfer Between Futures And Spot (USER_DATA)](#transfer-between-futures-and-spot-user_data) - [Query Order (USER_DATA)](#query-order-user_data) @@ -2445,6 +2446,59 @@ Additional mandatory parameters based on `type`: * Cannot be used with `reduceOnly` parameter * In Hedge Mode,cannot be used with `BUY` orders in `LONG` position side. and cannot be used with `SELL` orders in `SHORT` position side +## Modify Order (TRADE) + +> **Response:** + +```javascript +{ + 'orderId': 405, // Order ID + 'symbol': 'GOOGLUSDT', // Trading pair + 'status': 'NEW', // Order status + 'clientOrderId': 'uOLCC3aiCou3z2YL0sxWIX', // User-defined order ID + 'price': '295.50', // Order price + 'avgPrice': '0.00000', // Average fill price + 'origQty': '0.150', // Original order quantity + 'executedQty': '0', // Filled quantity + 'cumQty': '0', + 'cumQuote': '0', // Filled amount + 'timeInForce': 'GTC', // Time in force + 'type': 'LIMIT', // Order type + 'reduceOnly': False, // Reduce only + 'closePosition': False, // Close all positions on trigger + 'side': 'BUY', // Order side + 'positionSide': 'BOTH', // Position side + 'stopPrice': '0', // Trigger price, invalid for `TRAILING_STOP_MARKET` + 'workingType': 'CONTRACT_PRICE', // Condition price trigger type + 'priceProtect': False, // Conditional order trigger protection enabled + 'origType': 'LIMIT', // Original order type before trigger + 'updateTime': 1776311274450 // Update time +} +``` + +`` +PUT /fapi/v3/order `` + +**Weight:** +1 + +**Parameters:** + +Name | Type | Mandatory | Description +---------------- | ------- | -------- | ---- +orderId | LONG | NO | Order ID +origClientOrderId | STRING | NO | User-defined order ID +symbol | STRING | YES| Trading pair +quantity | DECIMAL| YES | Order quantity +price | DECIMAL | YES | Order price + + +* Either `orderId` or `origClientOrderId` must be sent. If both are sent, `orderId` takes precedence. +* At least one of `quantity` or `price` must be sent. +* If the new `quantity` or `price` does not meet `PRICE_FILTER` / `PERCENT_FILTER` / `LOT_SIZE` restrictions, the modification will be rejected and the original order will remain. +* Only `LIMIT` order type is supported. +* Maximum 10000 modifications per order. + ## Place Multiple Orders (TRADE) > **Response:** diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" index 93882a3..4a93dfa 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" @@ -2422,7 +2422,58 @@ POST /fapi/v3/order/test`` 参考 `POST /fapi/v3/order` +## 修改订单 (TRADE) +> **响应:** + +```javascript +{ + 'orderId': 405, //订单号 + 'symbol': 'GOOGLUSDT', //交易对 + 'status': 'NEW', //订单状态 + 'clientOrderId': 'uOLCC3aiCou3z2YL0sxWIX', //用户自定义的订单号 + 'price': '295.50', //委托价格 + 'avgPrice': '0.00000', // 平均成交价 + 'origQty': '0.150', // 原始委托数量 + 'executedQty': '0', // 成交量 + 'cumQty': '0', + 'cumQuote': '0', // 成交金额 + 'timeInForce': 'GTC', // 有效方法 + 'type': 'LIMIT', // 订单类型 + 'reduceOnly': False, // 仅减仓 + 'closePosition': False, // 是否条件全平仓 + 'side': 'BUY', //买卖方向 + 'positionSide': 'BOTH', // 持仓方向 + 'stopPrice': '0', // 触发价,对`TRAILING_STOP_MARKET`无效 + 'workingType': 'CONTRACT_PRICE', // 条件价格触发类型 + 'priceProtect': False, // 是否开启条件单触发保护 + 'origType': 'LIMIT', // 触发前订单类型 + 'updateTime': 1776311274450 //更新时间 +} +``` + +`` +PUT /fapi/v3/order `` + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +---------------- | ------- | -------- | ---- +orderId | LONG | NO |系统订单号 +origClientOrderId | STRING | NO | 用户自定义的订单号 +symbol | STRING | YES| 交易对 +quantity | DECIMAL| YES | 下单数量 +price | DECIMAL | YES | 委托价格 + + +* orderId 与 origClientOrderId 必须至少发送一个,同时发送则以 order id为准 +* quantity 与 price 必须至少发送一个 +* 当新订单的quantity 或 price不满足PRICE_FILTER / PERCENT_FILTER / LOT_SIZE限制,修改会被拒绝,原订单依旧被保留 +订单只支持limit类型 +* 同一订单修改次数最多10000次 ## 批量下单 (TRADE) diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" index f67504e..aa60fb5 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" @@ -70,6 +70,7 @@ - [查询联合保证金模式(USER_DATA)](#查询联合保证金模式user_data) - [下单 (TRADE)](#下单-trade) - [测试下单接口 (TRADE)](#测试下单接口-trade) + - [修改订单 (TRADE)](#修改订单-trade) - [批量下单 (TRADE)](#批量下单-trade) - [查询订单 (USER_DATA)](#查询订单-user_data) - [撤销订单 (TRADE)](#撤销订单-trade) @@ -2506,7 +2507,58 @@ POST /fapi/v3/order/test`` 参考 `POST /fapi/v3/order` +## 修改订单 (TRADE) +> **响应:** + +```javascript +{ + 'orderId': 405, //订单号 + 'symbol': 'GOOGLUSDT', //交易对 + 'status': 'NEW', //订单状态 + 'clientOrderId': 'uOLCC3aiCou3z2YL0sxWIX', //用户自定义的订单号 + 'price': '295.50', //委托价格 + 'avgPrice': '0.00000', // 平均成交价 + 'origQty': '0.150', // 原始委托数量 + 'executedQty': '0', // 成交量 + 'cumQty': '0', + 'cumQuote': '0', // 成交金额 + 'timeInForce': 'GTC', // 有效方法 + 'type': 'LIMIT', // 订单类型 + 'reduceOnly': False, // 仅减仓 + 'closePosition': False, // 是否条件全平仓 + 'side': 'BUY', //买卖方向 + 'positionSide': 'BOTH', // 持仓方向 + 'stopPrice': '0', // 触发价,对`TRAILING_STOP_MARKET`无效 + 'workingType': 'CONTRACT_PRICE', // 条件价格触发类型 + 'priceProtect': False, // 是否开启条件单触发保护 + 'origType': 'LIMIT', // 触发前订单类型 + 'updateTime': 1776311274450 //更新时间 +} +``` + +`` +PUT /fapi/v3/order `` + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +---------------- | ------- | -------- | ---- +orderId | LONG | NO |系统订单号 +origClientOrderId | STRING | NO | 用户自定义的订单号 +symbol | STRING | YES| 交易对 +quantity | DECIMAL| YES | 下单数量 +price | DECIMAL | YES | 委托价格 + + +* orderId 与 origClientOrderId 必须至少发送一个,同时发送则以 order id为准 +* quantity 与 price 必须至少发送一个 +* 当新订单的quantity 或 price不满足PRICE_FILTER / PERCENT_FILTER / LOT_SIZE限制,修改会被拒绝,原订单依旧被保留 +订单只支持limit类型 +* 同一订单修改次数最多10000次 ## 批量下单 (TRADE) From 8ed09587e9b27345722115524cefb8554620268b Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Thu, 16 Apr 2026 14:13:48 +0800 Subject: [PATCH 096/131] docs: fix Modify Order quantity/price as optional (NO) across all docs Co-Authored-By: Claude Sonnet 4.6 --- V3(Recommended)/EN/aster-finance-futures-api-testnet.md | 4 ++-- V3(Recommended)/EN/aster-finance-futures-api-v3.md | 4 ++-- .../aster-finance-futures-api-testnet_CN.md" | 4 ++-- .../aster-finance-futures-api-v3_CN.md" | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/V3(Recommended)/EN/aster-finance-futures-api-testnet.md b/V3(Recommended)/EN/aster-finance-futures-api-testnet.md index 1156be5..4847971 100644 --- a/V3(Recommended)/EN/aster-finance-futures-api-testnet.md +++ b/V3(Recommended)/EN/aster-finance-futures-api-testnet.md @@ -2275,8 +2275,8 @@ Name | Type | Mandatory | Description orderId | LONG | NO | Order ID origClientOrderId | STRING | NO | User-defined order ID symbol | STRING | YES| Trading pair -quantity | DECIMAL| YES | Order quantity -price | DECIMAL | YES | Order price +quantity | DECIMAL| NO | Order quantity +price | DECIMAL | NO | Order price * Either `orderId` or `origClientOrderId` must be sent. If both are sent, `orderId` takes precedence. diff --git a/V3(Recommended)/EN/aster-finance-futures-api-v3.md b/V3(Recommended)/EN/aster-finance-futures-api-v3.md index 00892be..f7b391b 100644 --- a/V3(Recommended)/EN/aster-finance-futures-api-v3.md +++ b/V3(Recommended)/EN/aster-finance-futures-api-v3.md @@ -2489,8 +2489,8 @@ Name | Type | Mandatory | Description orderId | LONG | NO | Order ID origClientOrderId | STRING | NO | User-defined order ID symbol | STRING | YES| Trading pair -quantity | DECIMAL| YES | Order quantity -price | DECIMAL | YES | Order price +quantity | DECIMAL| NO | Order quantity +price | DECIMAL | NO | Order price * Either `orderId` or `origClientOrderId` must be sent. If both are sent, `orderId` takes precedence. diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" index 4a93dfa..613d418 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" @@ -2465,8 +2465,8 @@ PUT /fapi/v3/order `` orderId | LONG | NO |系统订单号 origClientOrderId | STRING | NO | 用户自定义的订单号 symbol | STRING | YES| 交易对 -quantity | DECIMAL| YES | 下单数量 -price | DECIMAL | YES | 委托价格 +quantity | DECIMAL| NO | 下单数量 +price | DECIMAL | NO | 委托价格 * orderId 与 origClientOrderId 必须至少发送一个,同时发送则以 order id为准 diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" index aa60fb5..294fa83 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" @@ -2550,8 +2550,8 @@ PUT /fapi/v3/order `` orderId | LONG | NO |系统订单号 origClientOrderId | STRING | NO | 用户自定义的订单号 symbol | STRING | YES| 交易对 -quantity | DECIMAL| YES | 下单数量 -price | DECIMAL | YES | 委托价格 +quantity | DECIMAL| NO | 下单数量 +price | DECIMAL | NO | 委托价格 * orderId 与 origClientOrderId 必须至少发送一个,同时发送则以 order id为准 From 93e0a74c9b4b8cc194a75b87e0c54f6425012946 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Mon, 20 Apr 2026 13:58:55 +0800 Subject: [PATCH 097/131] docs: remove HMAC SHA256 labels from V3 API endpoint headings Co-Authored-By: Claude Sonnet 4.6 --- .../EN/aster-finance-futures-api-testnet.md | 50 +++++++++---------- .../EN/aster-finance-spot-api-testnet.md | 20 ++++---- .../EN/aster-finance-spot-api-v3.md | 18 +++---- 3 files changed, 44 insertions(+), 44 deletions(-) diff --git a/V3(Recommended)/EN/aster-finance-futures-api-testnet.md b/V3(Recommended)/EN/aster-finance-futures-api-testnet.md index 4847971..31cd2b7 100644 --- a/V3(Recommended)/EN/aster-finance-futures-api-testnet.md +++ b/V3(Recommended)/EN/aster-finance-futures-api-testnet.md @@ -2036,7 +2036,7 @@ Considering the possible data latency from RESTful endpoints during an extremely } ``` -``POST /fapi/v3/positionSide/dual (HMAC SHA256)`` +``POST /fapi/v3/positionSide/dual`` Change user's position mode (Hedge Mode or One-way Mode ) on ***EVERY symbol*** @@ -2061,7 +2061,7 @@ Change user's position mode (Hedge Mode or One-way Mode ) on ***EVERY symbol*** } ``` -``GET /fapi/v3/positionSide/dual (HMAC SHA256)`` +``GET /fapi/v3/positionSide/dual`` Get user's position mode (Hedge Mode or One-way Mode ) on ***EVERY symbol*** @@ -2086,7 +2086,7 @@ Get user's position mode (Hedge Mode or One-way Mode ) on ***EVERY symbol*** } ``` -``POST /fapi/v3/multiAssetsMargin (HMAC SHA256)`` +``POST /fapi/v3/multiAssetsMargin`` Change user's Multi-Assets mode (Multi-Assets Mode or Single-Asset Mode) on ***Every symbol*** @@ -2111,7 +2111,7 @@ Change user's Multi-Assets mode (Multi-Assets Mode or Single-Asset Mode) on ***E } ``` -``GET /fapi/v3/multiAssetsMargin (HMAC SHA256)`` +``GET /fapi/v3/multiAssetsMargin`` Get user's Multi-Assets mode (Multi-Assets Mode or Single-Asset Mode) on ***Every symbol*** @@ -2157,7 +2157,7 @@ Get user's Multi-Assets mode (Multi-Assets Mode or Single-Asset Mode) on ***Ever } ``` -``POST /fapi/v3/order (HMAC SHA256)`` +``POST /fapi/v3/order `` Send in a new order. @@ -2322,7 +2322,7 @@ price | DECIMAL | NO | Order price ] ``` -``POST /fapi/v3/batchOrders (HMAC SHA256)`` +``POST /fapi/v3/batchOrders `` **Weight:** 5 @@ -2372,7 +2372,7 @@ price | DECIMAL | NO | Order price ``` `` -POST /fapi/v3/asset/wallet/transfer (HMAC SHA256) +POST /fapi/v3/asset/wallet/transfer `` **Weight:** @@ -2427,7 +2427,7 @@ Notes: } ``` -``GET /fapi/v3/order (HMAC SHA256)`` +``GET /fapi/v3/order`` Check an order's status. @@ -2484,7 +2484,7 @@ Notes: } ``` -``DELETE /fapi/v3/order (HMAC SHA256)`` +``DELETE /fapi/v3/order `` Cancel an active order. @@ -2514,7 +2514,7 @@ Either `orderId` or `origClientOrderId` must be sent. } ``` -``DELETE /fapi/v3/allOpenOrders (HMAC SHA256)`` +``DELETE /fapi/v3/allOpenOrders `` **Weight:** 1 @@ -2564,7 +2564,7 @@ Either `orderId` or `origClientOrderId` must be sent. ] ``` -``DELETE /fapi/v3/batchOrders (HMAC SHA256)`` +``DELETE /fapi/v3/batchOrders `` **Weight:** 1 @@ -2594,7 +2594,7 @@ Either `orderIdList` or `origClientOrderIdList ` must be sent. Cancel all open orders of the specified symbol at the end of the specified countdown. -``POST /fapi/v3/countdownCancelAll (HMAC SHA256)`` +``POST /fapi/v3/countdownCancelAll `` **Weight:** 10 @@ -2647,7 +2647,7 @@ Cancel all open orders of the specified symbol at the end of the specified count } ``` -``GET /fapi/v3/openOrder (HMAC SHA256)`` +``GET /fapi/v3/openOrder `` **Weight:** 1 @@ -2698,7 +2698,7 @@ Cancel all open orders of the specified symbol at the end of the specified count ] ``` -``GET /fapi/v3/openOrders (HMAC SHA256)`` +``GET /fapi/v3/openOrders `` Get all open orders on a symbol. **Careful** when accessing this with no symbol. @@ -2749,7 +2749,7 @@ Get all open orders on a symbol. **Careful** when accessing this with no symbol. ] ``` -``GET /fapi/v3/allOrders (HMAC SHA256)`` +``GET /fapi/v3/allOrders`` Get all account orders; active, canceled, or filled. @@ -2798,7 +2798,7 @@ Get all account orders; active, canceled, or filled. ] ``` -``GET /fapi/v3/balance (HMAC SHA256)`` +``GET /fapi/v3/balance`` **Weight:** 5 @@ -2888,7 +2888,7 @@ Get all account orders; active, canceled, or filled. } ``` -``GET /fapi/v3/accountWithJoinMargin (HMAC SHA256)`` +``GET /fapi/v3/accountWithJoinMargin`` Get current account information. @@ -2914,7 +2914,7 @@ Get current account information. } ``` -``POST /fapi/v3/leverage (HMAC SHA256)`` +``POST /fapi/v3/leverage`` Change user's initial leverage of specific symbol market. @@ -2941,7 +2941,7 @@ Change user's initial leverage of specific symbol market. } ``` -``POST /fapi/v3/marginType (HMAC SHA256)`` +``POST /fapi/v3/marginType`` **Weight:** 1 @@ -2968,7 +2968,7 @@ Change user's initial leverage of specific symbol market. } ``` -``POST /fapi/v3/positionMargin (HMAC SHA256)`` +``POST /fapi/v3/positionMargin`` **Weight:** 1 @@ -3011,7 +3011,7 @@ Change user's initial leverage of specific symbol market. ] ``` -``GET /fapi/v3/positionMargin/history (HMAC SHA256)`` +``GET /fapi/v3/positionMargin/history`` **Weight:** 1 @@ -3091,7 +3091,7 @@ Change user's initial leverage of specific symbol market. ] ``` -``GET /fapi/v3/positionRisk (HMAC SHA256)`` +``GET /fapi/v3/positionRisk`` Get current position information. @@ -3134,7 +3134,7 @@ Please use with user data stream `ACCOUNT_UPDATE` to meet your timeliness and ac ] ``` -``GET /fapi/v3/userTrades (HMAC SHA256)`` +``GET /fapi/v3/userTrades `` Get trades for a specific account and symbol. @@ -3186,7 +3186,7 @@ Get trades for a specific account and symbol. ] ``` -``GET /fapi/v3/income (HMAC SHA256)`` +``GET /fapi/v3/income`` **Weight:** 30 @@ -3393,7 +3393,7 @@ Get trades for a specific account and symbol. } ``` -``GET /fapi/v3/commissionRate (HMAC SHA256)`` +``GET /fapi/v3/commissionRate`` **Weight:** 20 diff --git a/V3(Recommended)/EN/aster-finance-spot-api-testnet.md b/V3(Recommended)/EN/aster-finance-spot-api-testnet.md index 2001e38..7d09dd4 100644 --- a/V3(Recommended)/EN/aster-finance-spot-api-testnet.md +++ b/V3(Recommended)/EN/aster-finance-spot-api-testnet.md @@ -1032,7 +1032,7 @@ Get symbol fees } ``` -`POST /api/v3/order (HMAC SHA256)` +`POST /api/v3/order` Send order @@ -1096,7 +1096,7 @@ Other information: } ``` -`DELETE /api/v3/order (HMAC SHA256)` +`DELETE /api/v3/order` Cancel active orders @@ -1139,7 +1139,7 @@ At least one of `orderId` or `origClientOrderId` must be sent. } ``` -`GET /api/v3/order (HMAC SHA256)` +`GET /api/v3/order` Query order status @@ -1191,7 +1191,7 @@ Note: ] ``` -`GET /api/v3/openOrders (HMAC SHA256)` +`GET /api/v3/openOrders` Retrieve all current open orders for trading pairs. Use calls without a trading pair parameter with caution. @@ -1222,7 +1222,7 @@ Retrieve all current open orders for trading pairs. Use calls without a trading ``` `` -DEL /api/v3/allOpenOrders (HMAC SHA256) +DEL /api/v3/allOpenOrders `` **Weight:** @@ -1266,7 +1266,7 @@ timestamp | LONG | YES | ] ``` -`GET /api/v3/allOrders (HMAC SHA256)` +`GET /api/v3/allOrders` Retrieve all account orders; active, canceled, or completed. @@ -1342,7 +1342,7 @@ limit | LONG | NO | default:100 max:1000 } ``` -`POST /api/v3/asset/wallet/transfer (HMAC SHA256)` +`POST /api/v3/asset/wallet/transfer ` **Weight:** 5 @@ -1396,7 +1396,7 @@ asset | STRING | YES | ``` `` -POST /api/v3/aster/user-withdraw (HMAC SHA256) +POST /api/v3/aster/user-withdraw `` **Weight:** @@ -1487,7 +1487,7 @@ const signature = await signer.signTypedData(domain, types, value) } ``` -`GET /api/v3/account (HMAC SHA256)` +`GET /api/v3/account` Retrieve current account information @@ -1525,7 +1525,7 @@ Retrieve current account information ] ``` -`GET /api/v3/userTrades (HMAC SHA256)` +`GET /api/v3/userTrades` Retrieve the trade history for a specified trading pair of an account diff --git a/V3(Recommended)/EN/aster-finance-spot-api-v3.md b/V3(Recommended)/EN/aster-finance-spot-api-v3.md index a9bdcea..bba7cbe 100644 --- a/V3(Recommended)/EN/aster-finance-spot-api-v3.md +++ b/V3(Recommended)/EN/aster-finance-spot-api-v3.md @@ -1013,7 +1013,7 @@ Get symbol fees } ``` -`POST /api/v3/order (HMAC SHA256)` +`POST /api/v3/order` Send order @@ -1075,7 +1075,7 @@ Other information: } ``` -`DELETE /api/v3/order (HMAC SHA256)` +`DELETE /api/v3/order` Cancel active orders @@ -1116,7 +1116,7 @@ At least one of `orderId` or `origClientOrderId` must be sent. } ``` -`GET /api/v3/order (HMAC SHA256)` +`GET /api/v3/order` Query order status @@ -1164,7 +1164,7 @@ Note: } ``` -`GET /api/v3/openOrder (HMAC SHA256)` +`GET /api/v3/openOrder` Query current open order status. @@ -1209,7 +1209,7 @@ Note: ] ``` -`GET /api/v3/openOrders (HMAC SHA256)` +`GET /api/v3/openOrders` Retrieve all current open orders for trading pairs. Use calls without a trading pair parameter with caution. @@ -1279,7 +1279,7 @@ origClientOrderIdList | STRING | NO | clientOrderId array string ] ``` -`GET /api/v3/allOrders (HMAC SHA256)` +`GET /api/v3/allOrders` Retrieve all account orders; active, canceled, or completed. @@ -1352,7 +1352,7 @@ limit | LONG | NO | default:100 max:1000 } ``` -`POST /api/v3/asset/wallet/transfer (HMAC SHA256)` +`POST /api/v3/asset/wallet/transfer ` **Weight:** 5 @@ -1493,7 +1493,7 @@ const signature = await signer.signTypedData(domain, types, value) } ``` -`GET /api/v3/account (HMAC SHA256)` +`GET /api/v3/account` Retrieve current account information @@ -1529,7 +1529,7 @@ Retrieve current account information ] ``` -`GET /api/v3/userTrades (HMAC SHA256)` +`GET /api/v3/userTrades` Retrieve the trade history for a specified trading pair of an account From 3033e6a153b41a336aee26d9be398e6a8a86aea9 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Fri, 24 Apr 2026 15:52:55 +0800 Subject: [PATCH 098/131] docs: add STAKING_WITHDRAW/CLAIM/DELEGATE types to transactionHistory across all docs Co-Authored-By: Claude Sonnet 4.6 --- V1(Legacy)/EN/aster-finance-spot-api.md | 2 +- .../\344\270\255\346\226\207/aster-finance-spot-api_CN.md" | 2 +- V3(Recommended)/EN/aster-finance-spot-api-testnet.md | 2 +- V3(Recommended)/EN/aster-finance-spot-api-v3.md | 2 +- .../aster-finance-spot-api-testnet_CN.md" | 2 +- .../\344\270\255\346\226\207/aster-finance-spot-api_CN-v3.md" | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/V1(Legacy)/EN/aster-finance-spot-api.md b/V1(Legacy)/EN/aster-finance-spot-api.md index cd759d4..2b4f56b 100644 --- a/V1(Legacy)/EN/aster-finance-spot-api.md +++ b/V1(Legacy)/EN/aster-finance-spot-api.md @@ -1273,7 +1273,7 @@ limit | LONG | NO | default:100 max:1000 **Note:** -* `type`: `TRADE_TARGET`,`TRADE_SOURCE`,`TRANSFER_SPOT_TO_FUTURE`,`TRANSFER_FUTURE_TO_SPOT`,`TRANSFER_SPOT_TO_SPOT`,`AIRDROP`,`DIVIDEND`,`TRANSFER_REFUND`,`INTERNAL_TRANSFER`,`TRANSFER`,`SWAP`,`COMMISSION_REBATE`,`CASH_BACK` +* `type`: `TRADE_TARGET`,`TRADE_SOURCE`,`TRANSFER_SPOT_TO_FUTURE`,`TRANSFER_FUTURE_TO_SPOT`,`TRANSFER_SPOT_TO_SPOT`,`AIRDROP`,`DIVIDEND`,`TRANSFER_REFUND`,`INTERNAL_TRANSFER`,`TRANSFER`,`SWAP`,`COMMISSION_REBATE`,`CASH_BACK`,`STAKING_WITHDRAW`, `STAKING_CLAIM`, `STAKING_DELEGATE` * If startTime and endTime are not provided, only data from the most recent 7 days will be returned. diff --git "a/V1(Legacy)/\344\270\255\346\226\207/aster-finance-spot-api_CN.md" "b/V1(Legacy)/\344\270\255\346\226\207/aster-finance-spot-api_CN.md" index 5a4419f..4acbe11 100644 --- "a/V1(Legacy)/\344\270\255\346\226\207/aster-finance-spot-api_CN.md" +++ "b/V1(Legacy)/\344\270\255\346\226\207/aster-finance-spot-api_CN.md" @@ -1349,7 +1349,7 @@ timestamp | LONG | YES | 注意: -* `type` 取值 `TRADE_TARGET`,`TRADE_SOURCE`,`TRANSFER_SPOT_TO_FUTURE`,`TRANSFER_FUTURE_TO_SPOT`,`TRANSFER_SPOT_TO_SPOT`,`AIRDROP`,`DIVIDEND`,`TRANSFER_REFUND`,`INTERNAL_TRANSFER`,`TRANSFER`,`SWAP`,`COMMISSION_REBATE`,`CASH_BACK` 中的一种 +* `type` 取值 `TRADE_TARGET`,`TRADE_SOURCE`,`TRANSFER_SPOT_TO_FUTURE`,`TRANSFER_FUTURE_TO_SPOT`,`TRANSFER_SPOT_TO_SPOT`,`AIRDROP`,`DIVIDEND`,`TRANSFER_REFUND`,`INTERNAL_TRANSFER`,`TRANSFER`,`SWAP`,`COMMISSION_REBATE`,`CASH_BACK`,`STAKING_WITHDRAW`, `STAKING_CLAIM`, `STAKING_DELEGATE` 中的一种 * 如果`startTime` 和 `endTime` 均未发送, 只会返回最近7天的数据。 ## 期货现货互转 (TRADE) diff --git a/V3(Recommended)/EN/aster-finance-spot-api-testnet.md b/V3(Recommended)/EN/aster-finance-spot-api-testnet.md index 7d09dd4..23cb93d 100644 --- a/V3(Recommended)/EN/aster-finance-spot-api-testnet.md +++ b/V3(Recommended)/EN/aster-finance-spot-api-testnet.md @@ -1327,7 +1327,7 @@ limit | LONG | NO | default:100 max:1000 **Note:** -* `type`: `TRADE_TARGET`,`TRADE_SOURCE`,`TRANSFER_SPOT_TO_FUTURE`,`TRANSFER_FUTURE_TO_SPOT`,`TRANSFER_SPOT_TO_SPOT`,`AIRDROP`,`DIVIDEND`,`TRANSFER_REFUND`,`INTERNAL_TRANSFER`,`TRANSFER`,`SWAP`,`COMMISSION_REBATE`,`CASH_BACK` +* `type`: `TRADE_TARGET`,`TRADE_SOURCE`,`TRANSFER_SPOT_TO_FUTURE`,`TRANSFER_FUTURE_TO_SPOT`,`TRANSFER_SPOT_TO_SPOT`,`AIRDROP`,`DIVIDEND`,`TRANSFER_REFUND`,`INTERNAL_TRANSFER`,`TRANSFER`,`SWAP`,`COMMISSION_REBATE`,`CASH_BACK`,`STAKING_WITHDRAW`, `STAKING_CLAIM`, `STAKING_DELEGATE` * If startTime and endTime are not provided, only data from the most recent 7 days will be returned. diff --git a/V3(Recommended)/EN/aster-finance-spot-api-v3.md b/V3(Recommended)/EN/aster-finance-spot-api-v3.md index bba7cbe..ab523e5 100644 --- a/V3(Recommended)/EN/aster-finance-spot-api-v3.md +++ b/V3(Recommended)/EN/aster-finance-spot-api-v3.md @@ -1338,7 +1338,7 @@ limit | LONG | NO | default:100 max:1000 **Note:** -* `type`: `TRADE_TARGET`,`TRADE_SOURCE`,`TRANSFER_SPOT_TO_FUTURE`,`TRANSFER_FUTURE_TO_SPOT`,`TRANSFER_SPOT_TO_SPOT`,`AIRDROP`,`DIVIDEND`,`TRANSFER_REFUND`,`INTERNAL_TRANSFER`,`TRANSFER`,`SWAP`,`COMMISSION_REBATE`,`CASH_BACK` +* `type`: `TRADE_TARGET`,`TRADE_SOURCE`,`TRANSFER_SPOT_TO_FUTURE`,`TRANSFER_FUTURE_TO_SPOT`,`TRANSFER_SPOT_TO_SPOT`,`AIRDROP`,`DIVIDEND`,`TRANSFER_REFUND`,`INTERNAL_TRANSFER`,`TRANSFER`,`SWAP`,`COMMISSION_REBATE`,`CASH_BACK`,`STAKING_WITHDRAW`, `STAKING_CLAIM`, `STAKING_DELEGATE` * If startTime and endTime are not provided, only data from the most recent 7 days will be returned. ## Perp-spot transfer (TRADE) diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-spot-api-testnet_CN.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-spot-api-testnet_CN.md" index 4063835..7a81ae1 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-spot-api-testnet_CN.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-spot-api-testnet_CN.md" @@ -1348,7 +1348,7 @@ limit | LONG | NO | 返回的结果集数量 默认值:100 最大值:1000 注意: -* `type` 取值 `TRADE_TARGET`,`TRADE_SOURCE`,`TRANSFER_SPOT_TO_FUTURE`,`TRANSFER_FUTURE_TO_SPOT`,`TRANSFER_SPOT_TO_SPOT`,`AIRDROP`,`DIVIDEND`,`TRANSFER_REFUND`,`INTERNAL_TRANSFER`,`TRANSFER`,`SWAP`,`COMMISSION_REBATE`,`CASH_BACK` 中的一种 +* `type` 取值 `TRADE_TARGET`,`TRADE_SOURCE`,`TRANSFER_SPOT_TO_FUTURE`,`TRANSFER_FUTURE_TO_SPOT`,`TRANSFER_SPOT_TO_SPOT`,`AIRDROP`,`DIVIDEND`,`TRANSFER_REFUND`,`INTERNAL_TRANSFER`,`TRANSFER`,`SWAP`,`COMMISSION_REBATE`,`CASH_BACK`,`STAKING_WITHDRAW`, `STAKING_CLAIM`, `STAKING_DELEGATE` 中的一种 * 如果`startTime` 和 `endTime` 均未发送, 只会返回最近7天的数据。 ## 期货现货互转 (TRADE) diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-spot-api_CN-v3.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-spot-api_CN-v3.md" index 1d144c4..1506fb7 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-spot-api_CN-v3.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-spot-api_CN-v3.md" @@ -1385,7 +1385,7 @@ limit | LONG | NO | 返回的结果集数量 默认值:100 最大值:1000 注意: -* `type` 取值 `TRADE_TARGET`,`TRADE_SOURCE`,`TRANSFER_SPOT_TO_FUTURE`,`TRANSFER_FUTURE_TO_SPOT`,`TRANSFER_SPOT_TO_SPOT`,`AIRDROP`,`DIVIDEND`,`TRANSFER_REFUND`,`INTERNAL_TRANSFER`,`TRANSFER`,`SWAP`,`COMMISSION_REBATE`,`CASH_BACK` 中的一种 +* `type` 取值 `TRADE_TARGET`,`TRADE_SOURCE`,`TRANSFER_SPOT_TO_FUTURE`,`TRANSFER_FUTURE_TO_SPOT`,`TRANSFER_SPOT_TO_SPOT`,`AIRDROP`,`DIVIDEND`,`TRANSFER_REFUND`,`INTERNAL_TRANSFER`,`TRANSFER`,`SWAP`,`COMMISSION_REBATE`,`CASH_BACK`,`STAKING_WITHDRAW`, `STAKING_CLAIM`, `STAKING_DELEGATE` 中的一种 * 如果`startTime` 和 `endTime` 均未发送, 只会返回最近7天的数据。 ## 期货现货互转 (TRADE) From 642b92359721e57c6a97ffffad5db41c5b496a2a Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Tue, 28 Apr 2026 13:37:37 +0800 Subject: [PATCH 099/131] docs: add sub-account API endpoints to V3 docs (EN & CN) Add createSubAccount, getSubAccountList, updateSubAccount, and subAccountTransfer endpoint documentation including full parameter tables, signature instructions, and transfer scenario tables. Co-Authored-By: Claude Sonnet 4.6 --- .../EN/aster-finance-futures-api-testnet.md | 274 +++++++++++++++++ .../EN/aster-finance-futures-api-v3.md | 274 +++++++++++++++++ .../aster-finance-futures-api-testnet_CN.md" | 278 ++++++++++++++++++ .../aster-finance-futures-api-v3_CN.md" | 278 ++++++++++++++++++ .../aster-finance-spot-api_CN-v3.md" | 3 +- 5 files changed, 1106 insertions(+), 1 deletion(-) diff --git a/V3(Recommended)/EN/aster-finance-futures-api-testnet.md b/V3(Recommended)/EN/aster-finance-futures-api-testnet.md index 31cd2b7..dae004a 100644 --- a/V3(Recommended)/EN/aster-finance-futures-api-testnet.md +++ b/V3(Recommended)/EN/aster-finance-futures-api-testnet.md @@ -96,6 +96,10 @@ - [User's Force Orders (USER_DATA)](#users-force-orders-user_data) - [User Commission Rate (USER_DATA)](#user-commission-rate-user_data) - [Bind Sub-Account (USER_DATA)](#bind-sub-account-user_data) + - [Create Sub-Account (TRADE)](#create-sub-account-trade) + - [Get Sub-Account List (USER_DATA)](#get-sub-account-list-user_data) + - [Update Sub-Account (TRADE)](#update-sub-account-trade) + - [Sub-Account Transfer (TRADE)](#sub-account-transfer-trade) - [User Data Streams](#user-data-streams) - [Start User Data Stream (USER_STREAM)](#start-user-data-stream-user_stream) - [Keepalive User Data Stream (USER_STREAM)](#keepalive-user-data-stream-user_stream) @@ -3476,6 +3480,276 @@ childAddress={childAddress}&name={name}&nonce={nonce}&user={user}&childSignature * Only **whitelisted addresses** are supported for creation. Please contact the **project team** for configuration. +# Create Sub-Account (TRADE) + +> **Response:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +`POST /fapi/v3/createSubAccount` + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Required | Description | +|------|------|----------|-------------| +| subSourceAddr | STRING | YES | Sub-account wallet address | +| subAccountName | STRING | YES | Sub-account name | +| nonce | LONG | YES | Microsecond-level timestamp, used for replay attack prevention | +| user | STRING | YES | Master account wallet address | +| signer | STRING | YES | Signer address associated with the master account | +| childSignature | STRING | YES | Sub-account's signature over the message body (see Signature Instructions below) | +| signature | STRING | YES | Master account's signature over the message body, **must be signed using the master account's wallet private key** (see Signature Instructions below) | + +--- + +### Signature Instructions + +This endpoint requires **two independent signatures**. The message body differs between the two: + +#### Step 1: Sub-Account Signature (childSignature) + +The sub-account signs the following message body using **its own wallet private key:** + +``` +subAccountName={subAccountName}&subSourceAddr={subSourceAddr}&nonce={nonce}&user={user}&signer={signer} +``` + +#### Step 2: Master Account Signature (signature) + +The master account signs the following message body using **its own wallet private key** (not the signer private key). The message body **appends `childSignature`** to the one used in Step 1: + +``` +subAccountName={subAccountName}&subSourceAddr={subSourceAddr}&nonce={nonce}&user={user}&signer={signer}&childSignature={childSignature} +``` + +> The key difference between the two message bodies: the master account's message body **includes** `childSignature`, while the sub-account's does not. + +#### Supported Signing Algorithms + +| Account Type | Signing Algorithm | Encoding Format | +|---|---|---| +| EVM Address | EIP-712 Typed Data (chainId=1666, message.msg=message body) | Hex | +| Solana Address | Ed25519 | Base58 | + +> The address types of the master account and sub-account must match (EVM with EVM, Solana with Solana). + +--- + +### Important Notes + +* `signature` **must be signed using the master account's wallet private key** — the signer private key must not be used as a substitute. +* `childSignature` and `signature` are not interchangeable. +* The `user` field must match the authenticated master account address and cannot be forged. + + + +# Get Sub-Account List (USER_DATA) + +> **Response:** + +```javascript +[ + { + "accountId": 123456, + "subAccountName": "trading-desk-1", + "parentAccount": false + }, + { + "accountId": 100000, + "subAccountName": "", + "parentAccount": true + } +] +``` + +`GET /fapi/v3/getSubAccountList` + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Required | Description | +|------|------|----------|-------------| +| nonce | LONG | YES | Microsecond-level timestamp, used for replay attack prevention | +| user | STRING | YES | Master account wallet address | +| signer | STRING | YES | Signer address associated with the master account | +| signature | STRING | YES | Signature over the message body (see Signature Instructions below) | + +**Response fields:** + +| Name | Type | Description | +|------|------|-------------| +| accountId | LONG | Account ID | +| subAccountName | STRING | Sub-account name | +| parentAccount | BOOLEAN | Whether this entry is the master account (`true`) or a sub-account (`false`) | + +--- + +### Signature Instructions + +Sign the following message body using the **signer's private key** (EIP-712, always used regardless of whether the parent account is EVM or Solana): + +``` +nonce={nonce}&user={user}&signer={signer} +``` + +#### Signing Algorithm + +| Algorithm | Encoding Format | +|---|---| +| EIP-712 Typed Data (chainId=1666, message.msg=message body) | Hex | + +> Unlike other sub-account endpoints, `getSubAccountList` always uses the **signer private key** (EIP-712) for signing, even when the master account is a Solana address. + + + +# Update Sub-Account (TRADE) + +> **Response:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +`POST /fapi/v3/updateSubAccount` + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Required | Description | +|------|------|----------|-------------| +| subSourceAddr | STRING | YES | Sub-account wallet address to update | +| nonce | LONG | YES | Microsecond-level timestamp, used for replay attack prevention | +| user | STRING | YES | Master account wallet address | +| signer | STRING | YES | Signer address associated with the master account | +| subAccountName | STRING | NO | New sub-account name (at least one of `subAccountName` or `status` must be provided) | +| status | STRING | NO | Sub-account status: `NORMAL` (active) or `FROZEN` (frozen) | +| signature | STRING | YES | Master account's signature over the message body, **must be signed using the master account's wallet private key** (see Signature Instructions below) | + +--- + +### Signature Instructions + +The master account signs the following message body using **its own wallet private key** (not the signer private key): + +``` +subSourceAddr={subSourceAddr}&nonce={nonce}&user={user}&signer={signer}[&subAccountName={subAccountName}][&status={status}] +``` + +> Only include optional fields (`subAccountName`, `status`) in the message body if they are included in the request. + +#### Supported Signing Algorithms + +| Account Type | Signing Algorithm | Encoding Format | +|---|---|---| +| EVM Address | EIP-712 Typed Data (chainId=1666, message.msg=message body) | Hex | +| Solana Address | Ed25519 | Base58 | + +--- + +### Important Notes + +* `signature` **must be signed using the master account's wallet private key** — the signer private key must not be used as a substitute. +* At least one of `subAccountName` or `status` must be provided. +* `status` accepted values: `NORMAL` (unfreeze / active), `FROZEN` (freeze). +* A frozen sub-account cannot initiate transfers. + + + +# Sub-Account Transfer (TRADE) + +> **Response:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +`POST /fapi/v3/subAccountTransfer` + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Required | Description | +|------|------|----------|-------------| +| toAccountAddress | STRING | YES | Destination wallet address | +| asset | STRING | YES | Asset name (e.g., `USDT`) | +| amount | STRING | YES | Transfer amount | +| kindType | ENUM | YES | Transfer direction (see table below) | +| nonce | LONG | YES | Microsecond-level timestamp, used for replay attack prevention | +| user | STRING | YES | Signing account wallet address (master account address in most cases; sub-account address when the sub-account initiates a transfer to the master account) | +| signer | STRING | YES | Signer address associated with `user` | +| fromAccountAddress | STRING | NO | Source wallet address. Required when the source account differs from `user` (e.g., sub→sub transfers or master→sub transfers initiated by a third party) | +| signature | STRING | YES | Signature over the message body, **must be signed using the `user` account's wallet private key** (see Signature Instructions below) | + +**`kindType` values:** + +| Value | Description | +|-------|-------------| +| `FUTURE_FUTURE` | Perpetual account → Perpetual account | +| `FUTURE_SPOT` | Perpetual account → Spot account | +| `SPOT_FUTURE` | Spot account → Perpetual account | +| `SPOT_SPOT` | Spot account → Spot account | + +--- + +### Signature Instructions + +Sign the following message body using the **`user` account's wallet private key** (not the signer private key): + +**Without `fromAccountAddress`:** +``` +toAccountAddress={toAccountAddress}&asset={asset}&amount={amount}&kindType={kindType}&nonce={nonce}&user={user}&signer={signer} +``` + +**With `fromAccountAddress`:** +``` +toAccountAddress={toAccountAddress}&asset={asset}&amount={amount}&kindType={kindType}&nonce={nonce}&user={user}&signer={signer}&fromAccountAddress={fromAccountAddress} +``` + +#### Supported Signing Algorithms + +| Account Type | Signing Algorithm | Encoding Format | +|---|---|---| +| EVM Address | EIP-712 Typed Data (chainId=1666, message.msg=message body) | Hex | +| Solana Address | Ed25519 | Base58 | + +--- + +### Transfer Scenarios + +| Scenario | `user` | `fromAccountAddress` | Signing Key | +|----------|--------|----------------------|-------------| +| Master → Sub | Master account address | *(not required)* | Master account wallet private key | +| Sub → Master | Sub-account address | *(not required)* | Sub-account wallet private key | +| Sub A → Sub B | Master account address | Sub A address | Master account wallet private key | + +--- + +### Important Notes + +* `signature` **must be signed using the `user` account's wallet private key** — the signer private key must not be used as a substitute. +* The `user` field must match the address corresponding to the private key used for signing. +* When signing with a **sub-account's private key**, only transfers **to the master account** are supported. Sub→Sub transfers must be signed by the master account. +* Transfers to or from a **frozen sub-account** will fail. +* Transfers to **external addresses** (addresses not within the sub-account relationship) are not supported. + + + # User Data Streams * The base API endpoint is: **https://fapi.asterdex-testnet.com** diff --git a/V3(Recommended)/EN/aster-finance-futures-api-v3.md b/V3(Recommended)/EN/aster-finance-futures-api-v3.md index f7b391b..eba95f5 100644 --- a/V3(Recommended)/EN/aster-finance-futures-api-v3.md +++ b/V3(Recommended)/EN/aster-finance-futures-api-v3.md @@ -100,6 +100,10 @@ - [Delete User MMP (USER_DATA)](#delete-user-mmp-user_data) - [Reset User MMP (USER_DATA)](#reset-user-mmp-user_data) - [Bind Sub-Account (USER_DATA)](#bind-sub-account-user_data) + - [Create Sub-Account (TRADE)](#create-sub-account-trade) + - [Get Sub-Account List (USER_DATA)](#get-sub-account-list-user_data) + - [Update Sub-Account (TRADE)](#update-sub-account-trade) + - [Sub-Account Transfer (TRADE)](#sub-account-transfer-trade) - [User Data Streams](#user-data-streams) - [Start User Data Stream (USER_STREAM)](#start-user-data-stream-user_stream) - [Keepalive User Data Stream (USER_STREAM)](#keepalive-user-data-stream-user_stream) @@ -3740,6 +3744,276 @@ childAddress={childAddress}&name={name}&nonce={nonce}&user={user}&childSignature +# Create Sub-Account (TRADE) + +> **Response:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +`POST /fapi/v3/createSubAccount` + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Required | Description | +|------|------|----------|-------------| +| subSourceAddr | STRING | YES | Sub-account wallet address | +| subAccountName | STRING | YES | Sub-account name | +| nonce | LONG | YES | Microsecond-level timestamp, used for replay attack prevention | +| user | STRING | YES | Master account wallet address | +| signer | STRING | YES | Signer address associated with the master account | +| childSignature | STRING | YES | Sub-account's signature over the message body (see Signature Instructions below) | +| signature | STRING | YES | Master account's signature over the message body, **must be signed using the master account's wallet private key** (see Signature Instructions below) | + +--- + +### Signature Instructions + +This endpoint requires **two independent signatures**. The message body differs between the two: + +#### Step 1: Sub-Account Signature (childSignature) + +The sub-account signs the following message body using **its own wallet private key:** + +``` +subAccountName={subAccountName}&subSourceAddr={subSourceAddr}&nonce={nonce}&user={user}&signer={signer} +``` + +#### Step 2: Master Account Signature (signature) + +The master account signs the following message body using **its own wallet private key** (not the signer private key). The message body **appends `childSignature`** to the one used in Step 1: + +``` +subAccountName={subAccountName}&subSourceAddr={subSourceAddr}&nonce={nonce}&user={user}&signer={signer}&childSignature={childSignature} +``` + +> The key difference between the two message bodies: the master account's message body **includes** `childSignature`, while the sub-account's does not. + +#### Supported Signing Algorithms + +| Account Type | Signing Algorithm | Encoding Format | +|---|---|---| +| EVM Address | EIP-712 Typed Data (chainId=1666, message.msg=message body) | Hex | +| Solana Address | Ed25519 | Base58 | + +> The address types of the master account and sub-account must match (EVM with EVM, Solana with Solana). + +--- + +### Important Notes + +* `signature` **must be signed using the master account's wallet private key** — the signer private key must not be used as a substitute. +* `childSignature` and `signature` are not interchangeable. +* The `user` field must match the authenticated master account address and cannot be forged. + + + +# Get Sub-Account List (USER_DATA) + +> **Response:** + +```javascript +[ + { + "accountId": 123456, + "subAccountName": "trading-desk-1", + "parentAccount": false + }, + { + "accountId": 100000, + "subAccountName": "", + "parentAccount": true + } +] +``` + +`GET /fapi/v3/getSubAccountList` + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Required | Description | +|------|------|----------|-------------| +| nonce | LONG | YES | Microsecond-level timestamp, used for replay attack prevention | +| user | STRING | YES | Master account wallet address | +| signer | STRING | YES | Signer address associated with the master account | +| signature | STRING | YES | Signature over the message body (see Signature Instructions below) | + +**Response fields:** + +| Name | Type | Description | +|------|------|-------------| +| accountId | LONG | Account ID | +| subAccountName | STRING | Sub-account name | +| parentAccount | BOOLEAN | Whether this entry is the master account (`true`) or a sub-account (`false`) | + +--- + +### Signature Instructions + +Sign the following message body using the **signer's private key** (EIP-712, always used regardless of whether the parent account is EVM or Solana): + +``` +nonce={nonce}&user={user}&signer={signer} +``` + +#### Signing Algorithm + +| Algorithm | Encoding Format | +|---|---| +| EIP-712 Typed Data (chainId=1666, message.msg=message body) | Hex | + +> Unlike other sub-account endpoints, `getSubAccountList` always uses the **signer private key** (EIP-712) for signing, even when the master account is a Solana address. + + + +# Update Sub-Account (TRADE) + +> **Response:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +`POST /fapi/v3/updateSubAccount` + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Required | Description | +|------|------|----------|-------------| +| subSourceAddr | STRING | YES | Sub-account wallet address to update | +| nonce | LONG | YES | Microsecond-level timestamp, used for replay attack prevention | +| user | STRING | YES | Master account wallet address | +| signer | STRING | YES | Signer address associated with the master account | +| subAccountName | STRING | NO | New sub-account name (at least one of `subAccountName` or `status` must be provided) | +| status | STRING | NO | Sub-account status: `NORMAL` (active) or `FROZEN` (frozen) | +| signature | STRING | YES | Master account's signature over the message body, **must be signed using the master account's wallet private key** (see Signature Instructions below) | + +--- + +### Signature Instructions + +The master account signs the following message body using **its own wallet private key** (not the signer private key): + +``` +subSourceAddr={subSourceAddr}&nonce={nonce}&user={user}&signer={signer}[&subAccountName={subAccountName}][&status={status}] +``` + +> Only include optional fields (`subAccountName`, `status`) in the message body if they are included in the request. + +#### Supported Signing Algorithms + +| Account Type | Signing Algorithm | Encoding Format | +|---|---|---| +| EVM Address | EIP-712 Typed Data (chainId=1666, message.msg=message body) | Hex | +| Solana Address | Ed25519 | Base58 | + +--- + +### Important Notes + +* `signature` **must be signed using the master account's wallet private key** — the signer private key must not be used as a substitute. +* At least one of `subAccountName` or `status` must be provided. +* `status` accepted values: `NORMAL` (unfreeze / active), `FROZEN` (freeze). +* A frozen sub-account cannot initiate transfers. + + + +# Sub-Account Transfer (TRADE) + +> **Response:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +`POST /fapi/v3/subAccountTransfer` + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Required | Description | +|------|------|----------|-------------| +| toAccountAddress | STRING | YES | Destination wallet address | +| asset | STRING | YES | Asset name (e.g., `USDT`) | +| amount | STRING | YES | Transfer amount | +| kindType | ENUM | YES | Transfer direction (see table below) | +| nonce | LONG | YES | Microsecond-level timestamp, used for replay attack prevention | +| user | STRING | YES | Signing account wallet address (master account address in most cases; sub-account address when the sub-account initiates a transfer to the master account) | +| signer | STRING | YES | Signer address associated with `user` | +| fromAccountAddress | STRING | NO | Source wallet address. Required when the source account differs from `user` (e.g., sub→sub transfers or master→sub transfers initiated by a third party) | +| signature | STRING | YES | Signature over the message body, **must be signed using the `user` account's wallet private key** (see Signature Instructions below) | + +**`kindType` values:** + +| Value | Description | +|-------|-------------| +| `FUTURE_FUTURE` | Perpetual account → Perpetual account | +| `FUTURE_SPOT` | Perpetual account → Spot account | +| `SPOT_FUTURE` | Spot account → Perpetual account | +| `SPOT_SPOT` | Spot account → Spot account | + +--- + +### Signature Instructions + +Sign the following message body using the **`user` account's wallet private key** (not the signer private key): + +**Without `fromAccountAddress`:** +``` +toAccountAddress={toAccountAddress}&asset={asset}&amount={amount}&kindType={kindType}&nonce={nonce}&user={user}&signer={signer} +``` + +**With `fromAccountAddress`:** +``` +toAccountAddress={toAccountAddress}&asset={asset}&amount={amount}&kindType={kindType}&nonce={nonce}&user={user}&signer={signer}&fromAccountAddress={fromAccountAddress} +``` + +#### Supported Signing Algorithms + +| Account Type | Signing Algorithm | Encoding Format | +|---|---|---| +| EVM Address | EIP-712 Typed Data (chainId=1666, message.msg=message body) | Hex | +| Solana Address | Ed25519 | Base58 | + +--- + +### Transfer Scenarios + +| Scenario | `user` | `fromAccountAddress` | Signing Key | +|----------|--------|----------------------|-------------| +| Master → Sub | Master account address | *(not required)* | Master account wallet private key | +| Sub → Master | Sub-account address | *(not required)* | Sub-account wallet private key | +| Sub A → Sub B | Master account address | Sub A address | Master account wallet private key | + +--- + +### Important Notes + +* `signature` **must be signed using the `user` account's wallet private key** — the signer private key must not be used as a substitute. +* The `user` field must match the address corresponding to the private key used for signing. +* When signing with a **sub-account's private key**, only transfers **to the master account** are supported. Sub→Sub transfers must be signed by the master account. +* Transfers to or from a **frozen sub-account** will fail. +* Transfers to **external addresses** (addresses not within the sub-account relationship) are not supported. + + + # User Data Streams * The base API endpoint is: **https://fapi.asterdex.com** diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" index 613d418..c4c679e 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" @@ -90,6 +90,10 @@ - [用户强平单历史 (USER_DATA)](#用户强平单历史-user_data) - [用户手续费率 (USER_DATA)](#用户手续费率-user_data) - [绑定子账户 (USER_DATA)](#绑定子账户-user_data) + - [创建子账户 (TRADE)](#创建子账户-trade) + - [查询子账户列表 (USER_DATA)](#查询子账户列表-user_data) + - [更新子账户 (TRADE)](#更新子账户-trade) + - [子账户划转 (TRADE)](#子账户划转-trade) - [Websocket 账户信息推送](#websocket-账户信息推送) - [生成listenKey (USER_STREAM)](#生成listenkey-user_stream) - [延长listenKey有效期 (USER_STREAM)](#延长listenkey有效期-user_stream) @@ -3699,6 +3703,280 @@ childAddress={childAddress}&name={name}&nonce={nonce}&user={user}&childSignature * 只支持**白名单地址**创建,需要联系**项目方**配置 +# 创建子账户 (TRADE) + +> **响应:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +`POST /fapi/v3/createSubAccount` + +**权重:** 5 + +**所需权限:** TRADE + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| subSourceAddr | STRING | YES | 子账户钱包地址 | +| subAccountName | STRING | YES | 子账户名称 | +| nonce | LONG | YES | 微秒级时间戳,用于防重放攻击 | +| user | STRING | YES | 母账户钱包地址 | +| signer | STRING | YES | 与母账户关联的 signer 地址 | +| childSignature | STRING | YES | 子账户对消息体的签名(见下方签名说明) | +| signature | STRING | YES | 母账户对消息体的签名,**必须使用母账户钱包私钥签名**(见下方签名说明) | + +--- + +### 签名说明 + +本接口需要**两次独立签名**,两次签名的消息体不同: + +#### 第一步:子账户签名(childSignature) + +子账户使用**自己的钱包私钥**对以下消息体签名: + +``` +subAccountName={subAccountName}&subSourceAddr={subSourceAddr}&nonce={nonce}&user={user}&signer={signer} +``` + +#### 第二步:母账户签名(signature) + +母账户使用**自己的钱包私钥**(非 signer 私钥)对以下消息体签名,消息体在第一步基础上**追加了 `childSignature`**: + +``` +subAccountName={subAccountName}&subSourceAddr={subSourceAddr}&nonce={nonce}&user={user}&signer={signer}&childSignature={childSignature} +``` + +> 两次签名消息体的关键区别:母账户的签名消息体**包含** `childSignature`,子账户的不包含。 + +#### 支持的签名算法 + +| 账户类型 | 签名算法 | 编码格式 | +|---|---|---| +| EVM 地址 | EIP-712 Typed Data(chainId=1666,message.msg=消息体) | Hex | +| Solana 地址 | Ed25519 | Base58 | + +> 母账户与子账户的地址类型必须一致(EVM 对 EVM,Solana 对 Solana)。 + +--- + +### 注意事项 + +* `signature` **必须使用母账户钱包私钥签名**,不可使用 signer 私钥替代。 +* `childSignature` 与 `signature` 不可互换。 +* `user` 字段必须与已认证的母账户地址一致,不可伪造。 + + +# 查询子账户列表 (USER_DATA) + +> **响应:** + +```javascript +[ + { + "accountId": 123456, + "subAccountName": "trading-desk-1", + "parentAccount": false + }, + { + "accountId": 100000, + "subAccountName": "", + "parentAccount": true + } +] +``` + +`GET /fapi/v3/getSubAccountList` + +**权重:** 5 + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| nonce | LONG | YES | 微秒级时间戳,用于防重放攻击 | +| user | STRING | YES | 母账户钱包地址 | +| signer | STRING | YES | 与母账户关联的 signer 地址 | +| signature | STRING | YES | 对消息体的签名(见下方签名说明) | + +**响应字段:** + +| 名称 | 类型 | 描述 | +|------|------|------| +| accountId | LONG | 账户 ID | +| subAccountName | STRING | 子账户名称 | +| parentAccount | BOOLEAN | 是否为母账户(`true` 表示母账户,`false` 表示子账户) | + +--- + +### 签名说明 + +使用 **signer 私钥**(EIP-712)对以下消息体签名(无论母账户是 EVM 还是 Solana 地址,均使用 EIP-712): + +``` +nonce={nonce}&user={user}&signer={signer} +``` + +#### 签名算法 + +| 算法 | 编码格式 | +|---|---| +| EIP-712 Typed Data(chainId=1666,message.msg=消息体) | Hex | + +> 与其他子账户接口不同,`getSubAccountList` 始终使用 **signer 私钥**(EIP-712)签名,即使母账户为 Solana 地址也不例外。 + + + +# 更新子账户 (TRADE) + +> **响应:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +`POST /fapi/v3/updateSubAccount` + +**权重:** 5 + +**所需权限:** TRADE + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| subSourceAddr | STRING | YES | 待更新的子账户钱包地址 | +| nonce | LONG | YES | 微秒级时间戳,用于防重放攻击 | +| user | STRING | YES | 母账户钱包地址 | +| signer | STRING | YES | 与母账户关联的 signer 地址 | +| subAccountName | STRING | NO | 新的子账户名称(`subAccountName` 与 `status` 至少需传其一) | +| status | STRING | NO | 子账户状态:`NORMAL`(正常)或 `FROZEN`(冻结) | +| signature | STRING | YES | 母账户对消息体的签名,**必须使用母账户钱包私钥签名**(见下方签名说明) | + +--- + +### 签名说明 + +母账户使用**自己的钱包私钥**(非 signer 私钥)对以下消息体签名: + +``` +subSourceAddr={subSourceAddr}&nonce={nonce}&user={user}&signer={signer}[&subAccountName={subAccountName}][&status={status}] +``` + +> 可选字段(`subAccountName`、`status`)仅在请求中包含时才加入消息体。 + +#### 支持的签名算法 + +| 账户类型 | 签名算法 | 编码格式 | +|---|---|---| +| EVM 地址 | EIP-712 Typed Data(chainId=1666,message.msg=消息体) | Hex | +| Solana 地址 | Ed25519 | Base58 | + +--- + +### 注意事项 + +* `signature` **必须使用母账户钱包私钥签名**,不可使用 signer 私钥替代。 +* `subAccountName` 与 `status` 至少需传其一。 +* `status` 取值:`NORMAL`(解冻 / 正常),`FROZEN`(冻结)。 +* 已冻结的子账户无法发起划转。 + + + +# 子账户划转 (TRADE) + +> **响应:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +`POST /fapi/v3/subAccountTransfer` + +**权重:** 5 + +**所需权限:** TRADE + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| toAccountAddress | STRING | YES | 目标钱包地址 | +| asset | STRING | YES | 资产名称(如 `USDT`) | +| amount | STRING | YES | 划转金额 | +| kindType | ENUM | YES | 划转方向(见下表) | +| nonce | LONG | YES | 微秒级时间戳,用于防重放攻击 | +| user | STRING | YES | 签名账户的钱包地址(通常为母账户地址;子账户向母账户划转时为子账户地址) | +| signer | STRING | YES | 与 `user` 关联的 signer 地址 | +| fromAccountAddress | STRING | NO | 转出钱包地址。当转出账户与 `user` 不一致时必传(如子→子划转,或以第三方身份发起的母→子划转) | +| signature | STRING | YES | 对消息体的签名,**必须使用 `user` 账户的钱包私钥签名**(见下方签名说明) | + +**`kindType` 取值:** + +| 取值 | 说明 | +|------|------| +| `FUTURE_FUTURE` | 合约账户 → 合约账户 | +| `FUTURE_SPOT` | 合约账户 → 现货账户 | +| `SPOT_FUTURE` | 现货账户 → 合约账户 | +| `SPOT_SPOT` | 现货账户 → 现货账户 | + +--- + +### 签名说明 + +使用 **`user` 账户的钱包私钥**(非 signer 私钥)对以下消息体签名: + +**不含 `fromAccountAddress`:** +``` +toAccountAddress={toAccountAddress}&asset={asset}&amount={amount}&kindType={kindType}&nonce={nonce}&user={user}&signer={signer} +``` + +**含 `fromAccountAddress`:** +``` +toAccountAddress={toAccountAddress}&asset={asset}&amount={amount}&kindType={kindType}&nonce={nonce}&user={user}&signer={signer}&fromAccountAddress={fromAccountAddress} +``` + +#### 支持的签名算法 + +| 账户类型 | 签名算法 | 编码格式 | +|---|---|---| +| EVM 地址 | EIP-712 Typed Data(chainId=1666,message.msg=消息体) | Hex | +| Solana 地址 | Ed25519 | Base58 | + +--- + +### 划转场景说明 + +| 场景 | `user` | `fromAccountAddress` | 签名私钥 | +|------|--------|----------------------|---------| +| 母账户 → 子账户 | 母账户地址 | *(无需传入)* | 母账户钱包私钥 | +| 子账户 → 母账户 | 子账户地址 | *(无需传入)* | 子账户钱包私钥 | +| 子账户 A → 子账户 B | 母账户地址 | 子账户 A 地址 | 母账户钱包私钥 | + +--- + +### 注意事项 + +* `signature` **必须使用 `user` 账户的钱包私钥签名**,不可使用 signer 私钥替代。 +* `user` 字段必须与签名所用私钥对应的地址一致。 +* 使用**子账户私钥**签名时,仅支持向**母账户**划转;子→子划转必须由母账户签名。 +* 向**已冻结的子账户**划转或从**已冻结的子账户**划出均会失败。 +* 不支持向**非子账户关系内的外部地址**划转。 + + # Websocket 账户信息推送 diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" index 294fa83..b9f62fe 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" @@ -98,6 +98,10 @@ - [删除用户MMP (USER_DATA)](#删除用户mmp-user_data) - [重置用户MMP (USER_DATA)](#重置用户mmp-user_data) - [绑定子账户 (USER_DATA)](#绑定子账户-user_data) + - [创建子账户 (TRADE)](#创建子账户-trade) + - [查询子账户列表 (USER_DATA)](#查询子账户列表-user_data) + - [更新子账户 (TRADE)](#更新子账户-trade) + - [子账户划转 (TRADE)](#子账户划转-trade) - [Websocket 账户信息推送](#websocket-账户信息推送) - [生成listenKey (USER_STREAM)](#生成listenkey-user_stream) - [延长listenKey有效期 (USER_STREAM)](#延长listenkey有效期-user_stream) @@ -3889,6 +3893,280 @@ childAddress={childAddress}&name={name}&nonce={nonce}&user={user}&childSignature * 只支持**白名单地址**创建,需要联系**项目方**配置 +# 创建子账户 (TRADE) + +> **响应:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +`POST /fapi/v3/createSubAccount` + +**权重:** 5 + +**所需权限:** TRADE + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| subSourceAddr | STRING | YES | 子账户钱包地址 | +| subAccountName | STRING | YES | 子账户名称 | +| nonce | LONG | YES | 微秒级时间戳,用于防重放攻击 | +| user | STRING | YES | 母账户钱包地址 | +| signer | STRING | YES | 与母账户关联的 signer 地址 | +| childSignature | STRING | YES | 子账户对消息体的签名(见下方签名说明) | +| signature | STRING | YES | 母账户对消息体的签名,**必须使用母账户钱包私钥签名**(见下方签名说明) | + +--- + +### 签名说明 + +本接口需要**两次独立签名**,两次签名的消息体不同: + +#### 第一步:子账户签名(childSignature) + +子账户使用**自己的钱包私钥**对以下消息体签名: + +``` +subAccountName={subAccountName}&subSourceAddr={subSourceAddr}&nonce={nonce}&user={user}&signer={signer} +``` + +#### 第二步:母账户签名(signature) + +母账户使用**自己的钱包私钥**(非 signer 私钥)对以下消息体签名,消息体在第一步基础上**追加了 `childSignature`**: + +``` +subAccountName={subAccountName}&subSourceAddr={subSourceAddr}&nonce={nonce}&user={user}&signer={signer}&childSignature={childSignature} +``` + +> 两次签名消息体的关键区别:母账户的签名消息体**包含** `childSignature`,子账户的不包含。 + +#### 支持的签名算法 + +| 账户类型 | 签名算法 | 编码格式 | +|---|---|---| +| EVM 地址 | EIP-712 Typed Data(chainId=1666,message.msg=消息体) | Hex | +| Solana 地址 | Ed25519 | Base58 | + +> 母账户与子账户的地址类型必须一致(EVM 对 EVM,Solana 对 Solana)。 + +--- + +### 注意事项 + +* `signature` **必须使用母账户钱包私钥签名**,不可使用 signer 私钥替代。 +* `childSignature` 与 `signature` 不可互换。 +* `user` 字段必须与已认证的母账户地址一致,不可伪造。 + + +# 查询子账户列表 (USER_DATA) + +> **响应:** + +```javascript +[ + { + "accountId": 123456, + "subAccountName": "trading-desk-1", + "parentAccount": false + }, + { + "accountId": 100000, + "subAccountName": "", + "parentAccount": true + } +] +``` + +`GET /fapi/v3/getSubAccountList` + +**权重:** 5 + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| nonce | LONG | YES | 微秒级时间戳,用于防重放攻击 | +| user | STRING | YES | 母账户钱包地址 | +| signer | STRING | YES | 与母账户关联的 signer 地址 | +| signature | STRING | YES | 对消息体的签名(见下方签名说明) | + +**响应字段:** + +| 名称 | 类型 | 描述 | +|------|------|------| +| accountId | LONG | 账户 ID | +| subAccountName | STRING | 子账户名称 | +| parentAccount | BOOLEAN | 是否为母账户(`true` 表示母账户,`false` 表示子账户) | + +--- + +### 签名说明 + +使用 **signer 私钥**(EIP-712)对以下消息体签名(无论母账户是 EVM 还是 Solana 地址,均使用 EIP-712): + +``` +nonce={nonce}&user={user}&signer={signer} +``` + +#### 签名算法 + +| 算法 | 编码格式 | +|---|---| +| EIP-712 Typed Data(chainId=1666,message.msg=消息体) | Hex | + +> 与其他子账户接口不同,`getSubAccountList` 始终使用 **signer 私钥**(EIP-712)签名,即使母账户为 Solana 地址也不例外。 + + + +# 更新子账户 (TRADE) + +> **响应:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +`POST /fapi/v3/updateSubAccount` + +**权重:** 5 + +**所需权限:** TRADE + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| subSourceAddr | STRING | YES | 待更新的子账户钱包地址 | +| nonce | LONG | YES | 微秒级时间戳,用于防重放攻击 | +| user | STRING | YES | 母账户钱包地址 | +| signer | STRING | YES | 与母账户关联的 signer 地址 | +| subAccountName | STRING | NO | 新的子账户名称(`subAccountName` 与 `status` 至少需传其一) | +| status | STRING | NO | 子账户状态:`NORMAL`(正常)或 `FROZEN`(冻结) | +| signature | STRING | YES | 母账户对消息体的签名,**必须使用母账户钱包私钥签名**(见下方签名说明) | + +--- + +### 签名说明 + +母账户使用**自己的钱包私钥**(非 signer 私钥)对以下消息体签名: + +``` +subSourceAddr={subSourceAddr}&nonce={nonce}&user={user}&signer={signer}[&subAccountName={subAccountName}][&status={status}] +``` + +> 可选字段(`subAccountName`、`status`)仅在请求中包含时才加入消息体。 + +#### 支持的签名算法 + +| 账户类型 | 签名算法 | 编码格式 | +|---|---|---| +| EVM 地址 | EIP-712 Typed Data(chainId=1666,message.msg=消息体) | Hex | +| Solana 地址 | Ed25519 | Base58 | + +--- + +### 注意事项 + +* `signature` **必须使用母账户钱包私钥签名**,不可使用 signer 私钥替代。 +* `subAccountName` 与 `status` 至少需传其一。 +* `status` 取值:`NORMAL`(解冻 / 正常),`FROZEN`(冻结)。 +* 已冻结的子账户无法发起划转。 + + + +# 子账户划转 (TRADE) + +> **响应:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +`POST /fapi/v3/subAccountTransfer` + +**权重:** 5 + +**所需权限:** TRADE + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| toAccountAddress | STRING | YES | 目标钱包地址 | +| asset | STRING | YES | 资产名称(如 `USDT`) | +| amount | STRING | YES | 划转金额 | +| kindType | ENUM | YES | 划转方向(见下表) | +| nonce | LONG | YES | 微秒级时间戳,用于防重放攻击 | +| user | STRING | YES | 签名账户的钱包地址(通常为母账户地址;子账户向母账户划转时为子账户地址) | +| signer | STRING | YES | 与 `user` 关联的 signer 地址 | +| fromAccountAddress | STRING | NO | 转出钱包地址。当转出账户与 `user` 不一致时必传(如子→子划转,或以第三方身份发起的母→子划转) | +| signature | STRING | YES | 对消息体的签名,**必须使用 `user` 账户的钱包私钥签名**(见下方签名说明) | + +**`kindType` 取值:** + +| 取值 | 说明 | +|------|------| +| `FUTURE_FUTURE` | 合约账户 → 合约账户 | +| `FUTURE_SPOT` | 合约账户 → 现货账户 | +| `SPOT_FUTURE` | 现货账户 → 合约账户 | +| `SPOT_SPOT` | 现货账户 → 现货账户 | + +--- + +### 签名说明 + +使用 **`user` 账户的钱包私钥**(非 signer 私钥)对以下消息体签名: + +**不含 `fromAccountAddress`:** +``` +toAccountAddress={toAccountAddress}&asset={asset}&amount={amount}&kindType={kindType}&nonce={nonce}&user={user}&signer={signer} +``` + +**含 `fromAccountAddress`:** +``` +toAccountAddress={toAccountAddress}&asset={asset}&amount={amount}&kindType={kindType}&nonce={nonce}&user={user}&signer={signer}&fromAccountAddress={fromAccountAddress} +``` + +#### 支持的签名算法 + +| 账户类型 | 签名算法 | 编码格式 | +|---|---|---| +| EVM 地址 | EIP-712 Typed Data(chainId=1666,message.msg=消息体) | Hex | +| Solana 地址 | Ed25519 | Base58 | + +--- + +### 划转场景说明 + +| 场景 | `user` | `fromAccountAddress` | 签名私钥 | +|------|--------|----------------------|---------| +| 母账户 → 子账户 | 母账户地址 | *(无需传入)* | 母账户钱包私钥 | +| 子账户 → 母账户 | 子账户地址 | *(无需传入)* | 子账户钱包私钥 | +| 子账户 A → 子账户 B | 母账户地址 | 子账户 A 地址 | 母账户钱包私钥 | + +--- + +### 注意事项 + +* `signature` **必须使用 `user` 账户的钱包私钥签名**,不可使用 signer 私钥替代。 +* `user` 字段必须与签名所用私钥对应的地址一致。 +* 使用**子账户私钥**签名时,仅支持向**母账户**划转;子→子划转必须由母账户签名。 +* 向**已冻结的子账户**划转或从**已冻结的子账户**划出均会失败。 +* 不支持向**非子账户关系内的外部地址**划转。 + + # Websocket 账户信息推送 diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-spot-api_CN-v3.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-spot-api_CN-v3.md" index 1506fb7..26a53df 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-spot-api_CN-v3.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-spot-api_CN-v3.md" @@ -95,7 +95,8 @@ ## 接口鉴权类型 * 每个接口都有自己的鉴权类型,鉴权类型决定了访问时应当进行何种鉴权 -* 如果需要鉴权,应当在请求体中添加signer +* 如果需要使用API_WALLET鉴权,应当在请求体中添加signer +* 如果需要使用主地址鉴权,应当在请求体中添加user 鉴权类型 | 描述 ------------ | ------------ From 1395c6a97c079052d2b63e2d6bc98dc227f23ef0 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Tue, 28 Apr 2026 13:49:58 +0800 Subject: [PATCH 100/131] docs: sync auth section updates to all V3 docs - Split auth note into API_WALLET and master account variants - Remove my_dict['user'] from send_by_url and send_by_body examples Co-Authored-By: Claude Sonnet 4.6 --- V3(Recommended)/EN/aster-finance-futures-api-testnet.md | 5 ++--- V3(Recommended)/EN/aster-finance-futures-api-v3.md | 5 ++--- V3(Recommended)/EN/aster-finance-spot-api-testnet.md | 5 ++--- V3(Recommended)/EN/aster-finance-spot-api-v3.md | 2 -- .../aster-finance-futures-api-testnet_CN.md" | 5 ++--- .../aster-finance-futures-api-v3_CN.md" | 5 ++--- .../aster-finance-spot-api-testnet_CN.md" | 5 ++--- .../aster-finance-spot-api_CN-v3.md" | 2 -- 8 files changed, 12 insertions(+), 22 deletions(-) diff --git a/V3(Recommended)/EN/aster-finance-futures-api-testnet.md b/V3(Recommended)/EN/aster-finance-futures-api-testnet.md index dae004a..5cbdfa1 100644 --- a/V3(Recommended)/EN/aster-finance-futures-api-testnet.md +++ b/V3(Recommended)/EN/aster-finance-futures-api-testnet.md @@ -218,7 +218,8 @@ It is recommended to use a small recvWindow of 5000 or less! ## API authentication type * Each API has its own authentication type, which determines what kind of authentication is required when accessing it. -* If authentication is required, a signer should be included in the request body. +* If API_WALLET authentication is required, a signer should be included in the request body. +* If master account authentication is required, a user should be included in the request body. | Security Type | Description | | ------------- | ----------------------------------------- | @@ -341,7 +342,6 @@ def send_by_url(api) : url = host + api['url'] my_dict['nonce'] = str(get_nonce()) - my_dict['user'] = user my_dict['signer'] = signer param = urllib.parse.urlencode(my_dict) @@ -360,7 +360,6 @@ def send_by_body(api) : my_dict = api['params'] url = host +api['url'] my_dict['nonce'] = str(get_nonce()) - my_dict['user'] = user my_dict['signer'] = signer param = urllib.parse.urlencode(my_dict) diff --git a/V3(Recommended)/EN/aster-finance-futures-api-v3.md b/V3(Recommended)/EN/aster-finance-futures-api-v3.md index eba95f5..27d9145 100644 --- a/V3(Recommended)/EN/aster-finance-futures-api-v3.md +++ b/V3(Recommended)/EN/aster-finance-futures-api-v3.md @@ -212,7 +212,8 @@ It is strongly recommended to use websocket stream for getting data as much as p ## API authentication type * Each API has its own authentication type, which determines what kind of authentication is required when accessing it. -* If authentication is required, a signer should be included in the request body. +* If API_WALLET authentication is required, a signer should be included in the request body. +* If master account authentication is required, a user should be included in the request body. | Security Type | Description | | ------------- | ----------------------------------------- | @@ -338,7 +339,6 @@ def send_by_url(api) : method = api['method'] my_dict['nonce'] = str(get_nonce()) - my_dict['user'] = user my_dict['signer'] = signer param = urllib.parse.urlencode(my_dict) @@ -364,7 +364,6 @@ def send_by_body(api) : method = api['method'] my_dict['nonce'] = str(get_nonce()) - my_dict['user'] = user my_dict['signer'] = signer param = urllib.parse.urlencode(my_dict) diff --git a/V3(Recommended)/EN/aster-finance-spot-api-testnet.md b/V3(Recommended)/EN/aster-finance-spot-api-testnet.md index 23cb93d..595894d 100644 --- a/V3(Recommended)/EN/aster-finance-spot-api-testnet.md +++ b/V3(Recommended)/EN/aster-finance-spot-api-testnet.md @@ -91,7 +91,8 @@ You are advised to use WebSocket messages to obtain the corresponding data as mu ## API authentication types * Each API has its own authentication type, which determines what kind of authentication is required when accessing it. -* If authentication is required, a signer should be included in the request body. +* If API_WALLET authentication is required, a signer should be included in the request body. +* If master account authentication is required, a user should be included in the request body. | Security Type | Description | | ------------- | ----------------------------------------- | @@ -217,7 +218,6 @@ def send_by_url(api) : url = host + api['url'] my_dict['nonce'] = str(get_nonce()) - my_dict['user'] = user my_dict['signer'] = signer param = urllib.parse.urlencode(my_dict) @@ -236,7 +236,6 @@ def send_by_body(api) : my_dict = api['params'] url = host +api['url'] my_dict['nonce'] = str(get_nonce()) - my_dict['user'] = user my_dict['signer'] = signer param = urllib.parse.urlencode(my_dict) diff --git a/V3(Recommended)/EN/aster-finance-spot-api-v3.md b/V3(Recommended)/EN/aster-finance-spot-api-v3.md index ab523e5..ebc0518 100644 --- a/V3(Recommended)/EN/aster-finance-spot-api-v3.md +++ b/V3(Recommended)/EN/aster-finance-spot-api-v3.md @@ -211,7 +211,6 @@ def send_by_url(api) : url = host + api['url'] my_dict['nonce'] = str(get_nonce()) - my_dict['user'] = user my_dict['signer'] = signer param = urllib.parse.urlencode(my_dict) @@ -230,7 +229,6 @@ def send_by_body(api) : my_dict = api['params'] url = host +api['url'] my_dict['nonce'] = str(get_nonce()) - my_dict['user'] = user my_dict['signer'] = signer param = urllib.parse.urlencode(my_dict) diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" index c4c679e..6962832 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" @@ -196,7 +196,8 @@ ## 接口鉴权类型 * 每个接口都有自己的鉴权类型,鉴权类型决定了访问时应当进行何种鉴权 -* 如果需要鉴权,应当在请求体中添加signer +* 如果需要使用API_WALLET鉴权,应当在请求体中添加signer +* 如果需要使用主地址鉴权,应当在请求体中添加user 鉴权类型 | 描述 ------------ | ------------ @@ -316,7 +317,6 @@ def send_by_url(api) : method = api['method'] my_dict['nonce'] = str(get_nonce()) - my_dict['user'] = user my_dict['signer'] = signer param = urllib.parse.urlencode(my_dict) @@ -342,7 +342,6 @@ def send_by_body(api) : method = api['method'] my_dict['nonce'] = str(get_nonce()) - my_dict['user'] = user my_dict['signer'] = signer param = urllib.parse.urlencode(my_dict) diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" index b9f62fe..892a48b 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" @@ -204,7 +204,8 @@ ## 接口鉴权类型 * 每个接口都有自己的鉴权类型,鉴权类型决定了访问时应当进行何种鉴权 -* 如果需要鉴权,应当在请求体中添加signer +* 如果需要使用API_WALLET鉴权,应当在请求体中添加signer +* 如果需要使用主地址鉴权,应当在请求体中添加user 鉴权类型 | 描述 ------------ | ------------ @@ -324,7 +325,6 @@ def send_by_url(api) : method = api['method'] my_dict['nonce'] = str(get_nonce()) - my_dict['user'] = user my_dict['signer'] = signer param = urllib.parse.urlencode(my_dict) @@ -350,7 +350,6 @@ def send_by_body(api) : method = api['method'] my_dict['nonce'] = str(get_nonce()) - my_dict['user'] = user my_dict['signer'] = signer param = urllib.parse.urlencode(my_dict) diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-spot-api-testnet_CN.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-spot-api-testnet_CN.md" index 7a81ae1..8147da3 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-spot-api-testnet_CN.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-spot-api-testnet_CN.md" @@ -58,7 +58,8 @@ ## 接口鉴权类型 * 每个接口都有自己的鉴权类型,鉴权类型决定了访问时应当进行何种鉴权 -* 如果需要鉴权,应当在请求体中添加signer +* 如果需要使用API_WALLET鉴权,应当在请求体中添加signer +* 如果需要使用主地址鉴权,应当在请求体中添加user 鉴权类型 | 描述 ------------ | ------------ @@ -163,7 +164,6 @@ def send_by_url(api) : url = host + api['url'] my_dict['nonce'] = str(get_nonce()) - my_dict['user'] = user my_dict['signer'] = signer param = urllib.parse.urlencode(my_dict) @@ -182,7 +182,6 @@ def send_by_body(api) : my_dict = api['params'] url = host +api['url'] my_dict['nonce'] = str(get_nonce()) - my_dict['user'] = user my_dict['signer'] = signer param = urllib.parse.urlencode(my_dict) diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-spot-api_CN-v3.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-spot-api_CN-v3.md" index 26a53df..5191c46 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-spot-api_CN-v3.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-spot-api_CN-v3.md" @@ -201,7 +201,6 @@ def send_by_url(api) : url = host + api['url'] my_dict['nonce'] = str(get_nonce()) - my_dict['user'] = user my_dict['signer'] = signer param = urllib.parse.urlencode(my_dict) @@ -220,7 +219,6 @@ def send_by_body(api) : my_dict = api['params'] url = host +api['url'] my_dict['nonce'] = str(get_nonce()) - my_dict['user'] = user my_dict['signer'] = signer param = urllib.parse.urlencode(my_dict) From b2fe0b1d28e8dcf06fe8ca7c0d8560dcdf7a3cbb Mon Sep 17 00:00:00 2001 From: Vanessa Date: Tue, 28 Apr 2026 14:40:28 +0800 Subject: [PATCH 101/131] add spot doc --- RPC/aster-chain-rpc.md | 184 +++++++++++++++++++++++++++++++++++++- RPC/aster-chain-rpc_CN.md | 182 ++++++++++++++++++++++++++++++++++++- 2 files changed, 364 insertions(+), 2 deletions(-) diff --git a/RPC/aster-chain-rpc.md b/RPC/aster-chain-rpc.md index ea2693b..2b61ca7 100644 --- a/RPC/aster-chain-rpc.md +++ b/RPC/aster-chain-rpc.md @@ -4,6 +4,8 @@ - [Get Balance](#get-balance) - [Get Open Orders](#get-open-orders) - [Get User Futures Fills](#get-user-futures-fills) + - [Get Spot Open Orders](#get-spot-open-orders) + - [Get User Spot Fills](#get-user-spot-fills) # General Info @@ -323,4 +325,184 @@ fills[].price | STRING | Fill price fills[].qty | STRING | Fill quantity fills[].time | LONG | Fill time in milliseconds -> **Note:** This endpoint only returns futures trade fill data. \ No newline at end of file +> **Note:** This endpoint only returns futures trade fill data. + + +## Get Spot Open Orders + +`` +POST /info +`` + +Query spot open orders for a given address. + +> **Note:** Only open orders created at or after block 1 genesis time (`1772678119418`) are returned. Maximum **1000** records returned. + +**Method:** `aster_spotOpenOrders` + +**Weight:** +1 + +**Parameters (params array):** + +Index | Name | Type | Mandatory | Description +----- | ---- | ---- | --------- | ----------- +0 | address | STRING | YES | The wallet address to query +1 | symbol | STRING | NO | Trading pair symbol (e.g. `"ASTCUSDT"`); pass `null` or `""` to query all symbols +2 | blockTag | STRING | YES | Block tag, use `"latest"` for the most recent state + +> **Request Example:** + +```shell +curl -X POST "https://tapi.asterdex.com/info" \ + -H "accept: */*" \ + -H "Content-Type: application/json" \ + -d '{ + "id": {}, + "jsonrpc": "2.0", + "method": "aster_spotOpenOrders", + "params": [ + "0x90B8DE626a8*****************", + null, + "latest" + ] + }' +``` + +> **Response:** + +```javascript +{ + "result": { + "address": "0x90B8DE626a8***************", + "accountPrivacy": "enabled", + "openOrders": [ + { + "orderId": "web_rgXtfO0hXb3EbaagJYLe", + "symbol": "ASTCUSDT", + "side": "BUY", + "type": "LIMIT", + "origQty": "0.00600000", + "price": "19000.00000000" + }, + { + "orderId": "web_iXqhwgrotPEFZ7hpw1vq", + "symbol": "ASTCUSDC", + "side": "SELL", + "type": "LIMIT", + "origQty": "0.00420000", + "price": "49000.00000000" + }, + { + "orderId": "web_dUdf2dUyFfvp4mqauXKg", + "symbol": "ADOGUSDT", + "side": "BUY", + "type": "LIMIT", + "origQty": "1000.00000000", + "price": "4.20000000" + } + ] + }, + "id": {}, + "jsonrpc": "2.0" +} +``` + +**Response Fields:** + +Name | Type | Description +---- | ---- | ----------- +address | STRING | Wallet address +accountPrivacy | STRING | Privacy mode status: `"disabled"` or `"enabled"` +openOrders | ARRAY | List of open orders +openOrders[].orderId | STRING | Order ID +openOrders[].symbol | STRING | Trading pair symbol +openOrders[].side | STRING | Order side: `BUY` or `SELL` +openOrders[].type | STRING | Order type: e.g. `LIMIT`, `MARKET` +openOrders[].origQty | STRING | Original order quantity +openOrders[].price | STRING | Order price + + +## Get User Spot Fills + +`` +POST /info +`` + +Query the spot trade fill history for a given address within a specified time range. + +**Method:** `aster_spotUserFills` + +**Weight:** +1 + +**Parameters (params array):** + +Index | Name | Type | Mandatory | Description +----- | ---- | ---- | --------- | ----------- +0 | address | STRING | YES | The wallet address to query +1 | symbol | STRING | NO | Trading pair symbol (e.g. `"ASTCUSDT"`); pass `null` or `""` to query all symbols +2 | from | LONG | NO | Start time in milliseconds. If omitted and `to` is provided, defaults to `to - 7 days`. If both are omitted, defaults to 7 days before current time. Must be ≥ `1772678119418` (block 1 genesis); queries before this timestamp return empty results. +3 | to | LONG | NO | End time in milliseconds. If omitted and `from` is provided, defaults to `from + 7 days`. If both are omitted, defaults to current time. The time range between `from` and `to` must not exceed 7 days. +4 | blockTag | STRING | YES | Block tag, use `"latest"` for the most recent state + +> **Request Example:** + +```shell +curl -X POST "https://tapi.asterdex.com/info" \ + -H "accept: */*" \ + -H "Content-Type: application/json" \ + -d '{ + "id": {}, + "jsonrpc": "2.0", + "method": "aster_spotUserFills", + "params": [ + "0x90B8DE626a8*****************", + null, + null, + null, + "latest" + ] + }' +``` + +> **Response:** + +```javascript +{ + "result": { + "address": "0x90B8DE626a8***************", + "accountPrivacy": "enabled", + "startTime": 1776410901599, + "endTime": 1777015701599, + "fills": [ + { + "symbol": "ASTCUSDT", + "side": "BUY", + "price": "21000", + "qty": "0.00170000", + "time": 1777000095000 + } + ] + }, + "id": {}, + "jsonrpc": "2.0" +} +``` + +**Response Fields:** + +Name | Type | Description +---- | ---- | ----------- +address | STRING | Wallet address +accountPrivacy | STRING | Privacy mode status: `"disabled"` or `"enabled"` +startTime | LONG | Actual query start time in milliseconds +endTime | LONG | Actual query end time in milliseconds +fills | ARRAY | List of trade fills; returns at most `1000` records +fills[].symbol | STRING | Trading pair symbol +fills[].side | STRING | Trade side: `BUY` or `SELL` +fills[].price | STRING | Fill price +fills[].qty | STRING | Fill quantity +fills[].time | LONG | Fill time in milliseconds + +> **Note:** This endpoint only returns spot trade fill data. \ No newline at end of file diff --git a/RPC/aster-chain-rpc_CN.md b/RPC/aster-chain-rpc_CN.md index adecf48..2003443 100644 --- a/RPC/aster-chain-rpc_CN.md +++ b/RPC/aster-chain-rpc_CN.md @@ -323,4 +323,184 @@ fills[].price | STRING | 成交价格 fills[].qty | STRING | 成交数量 fills[].time | LONG | 成交时间(毫秒时间戳) -> **注意:** 该接口仅返回期货成交数据。 \ No newline at end of file +> **注意:** 该接口仅返回期货成交数据。 + + +## 查询用户现货当前挂单 + +`` +POST /info +`` + +查询指定地址的现货当前挂单。 + +> **说明:** 仅返回创建时间不早于 block 1 创世时间(`1772678119418`)的挂单,最多返回 **1000** 条。 + +**方法名:** `aster_spotOpenOrders` + +**权重:** +1 + +**请求参数(params 数组):** + +下标 | 参数名 | 类型 | 是否必填 | 说明 +---- | ------ | ---- | -------- | ---- +0 | address | STRING | 是 | 要查询的钱包地址 +1 | symbol | STRING | 否 | 交易对名称(如 `"ASTCUSDT"`);传 `null` 或 `""` 查询所有交易对 +2 | blockTag | STRING | 是 | 区块标签,传入 `"latest"` 表示查询最新状态 + +> **请求示例:** + +```shell +curl -X POST "https://tapi.asterdex.com/info" \ + -H "accept: */*" \ + -H "Content-Type: application/json" \ + -d '{ + "id": {}, + "jsonrpc": "2.0", + "method": "aster_spotOpenOrders", + "params": [ + "0x90B8DE626a8*****************", + null, + "latest" + ] + }' +``` + +> **返回结果:** + +```javascript +{ + "result": { + "address": "0x90B8DE626a8***************", + "accountPrivacy": "enabled", + "openOrders": [ + { + "orderId": "web_rgXtfO0hXb3EbaagJYLe", + "symbol": "ASTCUSDT", + "side": "BUY", + "type": "LIMIT", + "origQty": "0.00600000", + "price": "19000.00000000" + }, + { + "orderId": "web_iXqhwgrotPEFZ7hpw1vq", + "symbol": "ASTCUSDC", + "side": "SELL", + "type": "LIMIT", + "origQty": "0.00420000", + "price": "49000.00000000" + }, + { + "orderId": "web_dUdf2dUyFfvp4mqauXKg", + "symbol": "ADOGUSDT", + "side": "BUY", + "type": "LIMIT", + "origQty": "1000.00000000", + "price": "4.20000000" + } + ] + }, + "id": {}, + "jsonrpc": "2.0" +} +``` + +**返回字段说明:** + +字段名 | 类型 | 说明 +------ | ---- | ---- +address | STRING | 钱包地址 +accountPrivacy | STRING | 隐私模式状态:`"disabled"` 已关闭 / `"enabled"` 已开启 +openOrders | ARRAY | 当前挂单列表 +openOrders[].orderId | STRING | 订单 ID +openOrders[].symbol | STRING | 交易对名称 +openOrders[].side | STRING | 买卖方向:`BUY` 买入 / `SELL` 卖出 +openOrders[].type | STRING | 订单类型:如 `LIMIT` 限价单、`MARKET` 市价单 +openOrders[].origQty | STRING | 原始委托数量 +openOrders[].price | STRING | 委托价格 + + +## 查询用户现货成交记录 + +`` +POST /info +`` + +查询指定地址在指定时间范围内的现货历史成交记录。 + +**方法名:** `aster_spotUserFills` + +**权重:** +1 + +**请求参数(params 数组):** + +下标 | 参数名 | 类型 | 是否必填 | 说明 +---- | ------ | ---- | -------- | ---- +0 | address | STRING | 是 | 要查询的钱包地址 +1 | symbol | STRING | 否 | 交易对名称(如 `"ASTCUSDT"`);传 `null` 或 `""` 查询所有交易对 +2 | from | LONG | 否 | 查询起始时间(毫秒时间戳)。若不填且填了 `to`,则默认为 `to - 7天`;若两者均不填,则默认为当前时间往前 7 天。最小值为 `1772678119418`(block 1 创世时间),早于此时间的查询默认返回空。 +3 | to | LONG | 否 | 查询结束时间(毫秒时间戳)。若不填且填了 `from`,则默认为 `from + 7天`;若两者均不填,则默认为当前时间。`from` 与 `to` 时间间隔不得超过 7 天。 +4 | blockTag | STRING | 是 | 区块标签,传入 `"latest"` 表示查询最新状态 + +> **请求示例:** + +```shell +curl -X POST "https://tapi.asterdex.com/info" \ + -H "accept: */*" \ + -H "Content-Type: application/json" \ + -d '{ + "id": {}, + "jsonrpc": "2.0", + "method": "aster_spotUserFills", + "params": [ + "0x90B8DE626a8*****************", + null, + null, + null, + "latest" + ] + }' +``` + +> **返回结果:** + +```javascript +{ + "result": { + "address": "0x90B8DE626a8***************", + "accountPrivacy": "enabled", + "startTime": 1776410901599, + "endTime": 1777015701599, + "fills": [ + { + "symbol": "ASTCUSDT", + "side": "BUY", + "price": "21000", + "qty": "0.00170000", + "time": 1777000095000 + } + ] + }, + "id": {}, + "jsonrpc": "2.0" +} +``` + +**返回字段说明:** + +字段名 | 类型 | 说明 +------ | ---- | ---- +address | STRING | 钱包地址 +accountPrivacy | STRING | 隐私模式状态:`"disabled"` 已关闭 / `"enabled"` 已开启 +startTime | LONG | 实际查询起始时间(毫秒时间戳) +endTime | LONG | 实际查询结束时间(毫秒时间戳) +fills | ARRAY | 成交记录列表,最多返回 `1000` 条 +fills[].symbol | STRING | 交易对名称 +fills[].side | STRING | 成交方向:`BUY` 买入 / `SELL` 卖出 +fills[].price | STRING | 成交价格 +fills[].qty | STRING | 成交数量 +fills[].time | LONG | 成交时间(毫秒时间戳) + +> **注意:** 该接口仅返回现货成交数据。 \ No newline at end of file From 5957c5318c5d1c80aa8518ee4ddf222502b8779d Mon Sep 17 00:00:00 2001 From: Vanessa Date: Tue, 28 Apr 2026 16:44:34 +0800 Subject: [PATCH 102/131] spot cn doc update --- RPC/aster-chain-rpc_CN.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/RPC/aster-chain-rpc_CN.md b/RPC/aster-chain-rpc_CN.md index 2003443..42b0f93 100644 --- a/RPC/aster-chain-rpc_CN.md +++ b/RPC/aster-chain-rpc_CN.md @@ -4,6 +4,8 @@ - [查询账户余额](#查询账户余额) - [查询当前挂单](#查询当前挂单) - [查询用户期货成交记录](#查询用户期货成交记录) + - [查询用户现货当前挂单](#查询用户现货当前挂单) + - [查询用户现货成交记录](#查询用户现货成交记录) # 基本信息 From 165cad1aacb02175e8bbc6f957e4412bd09bd444 Mon Sep 17 00:00:00 2001 From: Vanessa Date: Tue, 28 Apr 2026 16:47:47 +0800 Subject: [PATCH 103/131] spot cn doc update --- RPC/aster-chain-rpc.md | 7 ++----- RPC/aster-chain-rpc_CN.md | 7 ++----- 2 files changed, 4 insertions(+), 10 deletions(-) diff --git a/RPC/aster-chain-rpc.md b/RPC/aster-chain-rpc.md index 2b61ca7..c29a6b0 100644 --- a/RPC/aster-chain-rpc.md +++ b/RPC/aster-chain-rpc.md @@ -189,16 +189,14 @@ curl -X POST "https://tapi.asterdex.com/info" \ "symbol": "TRUMPUSDT", "side": "SELL", "type": "LIMIT", - "origQty": "4.44000000", - "status": "NEW" + "origQty": "4.44000000" }, { "orderId": "web_AD_4u1emfjslzt4hqnc5_98", "symbol": "BTCUSDT", "side": "BUY", "type": "LIMIT", - "origQty": "0.00100000", - "status": "NEW" + "origQty": "0.00100000" } ] }, @@ -219,7 +217,6 @@ openOrders[].symbol | STRING | Trading pair symbol openOrders[].side | STRING | Order side: `BUY` or `SELL` openOrders[].type | STRING | Order type: e.g. `LIMIT`, `MARKET` openOrders[].origQty | STRING | Original order quantity -openOrders[].status | STRING | Order status: e.g. `NEW` ## Get User Futures Fills diff --git a/RPC/aster-chain-rpc_CN.md b/RPC/aster-chain-rpc_CN.md index 42b0f93..2234350 100644 --- a/RPC/aster-chain-rpc_CN.md +++ b/RPC/aster-chain-rpc_CN.md @@ -189,16 +189,14 @@ curl -X POST "https://tapi.asterdex.com/info" \ "symbol": "TRUMPUSDT", "side": "SELL", "type": "LIMIT", - "origQty": "4.44000000", - "status": "NEW" + "origQty": "4.44000000" }, { "orderId": "web_AD_4u1emfjslzt4hqnc5_98", "symbol": "BTCUSDT", "side": "BUY", "type": "LIMIT", - "origQty": "0.00100000", - "status": "NEW" + "origQty": "0.00100000" } ] }, @@ -219,7 +217,6 @@ openOrders[].symbol | STRING | 交易对名称 openOrders[].side | STRING | 买卖方向:`BUY` 买入 / `SELL` 卖出 openOrders[].type | STRING | 订单类型:如 `LIMIT` 限价单、`MARKET` 市价单 openOrders[].origQty | STRING | 原始委托数量 -openOrders[].status | STRING | 订单状态:如 `NEW` 待成交 ## 查询用户期货成交记录 From 22723dc6ccec509e1e19dc3d0681789138437d64 Mon Sep 17 00:00:00 2001 From: Vanessa Date: Tue, 28 Apr 2026 16:52:28 +0800 Subject: [PATCH 104/131] future doc update --- RPC/aster-chain-rpc.md | 7 +++++-- RPC/aster-chain-rpc_CN.md | 7 +++++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/RPC/aster-chain-rpc.md b/RPC/aster-chain-rpc.md index c29a6b0..594c0bd 100644 --- a/RPC/aster-chain-rpc.md +++ b/RPC/aster-chain-rpc.md @@ -189,14 +189,16 @@ curl -X POST "https://tapi.asterdex.com/info" \ "symbol": "TRUMPUSDT", "side": "SELL", "type": "LIMIT", - "origQty": "4.44000000" + "origQty": "4.44000000", + "price": "10.00000000" }, { "orderId": "web_AD_4u1emfjslzt4hqnc5_98", "symbol": "BTCUSDT", "side": "BUY", "type": "LIMIT", - "origQty": "0.00100000" + "origQty": "0.00100000", + "price": "95000.00000000" } ] }, @@ -217,6 +219,7 @@ openOrders[].symbol | STRING | Trading pair symbol openOrders[].side | STRING | Order side: `BUY` or `SELL` openOrders[].type | STRING | Order type: e.g. `LIMIT`, `MARKET` openOrders[].origQty | STRING | Original order quantity +openOrders[].price | STRING | Order price ## Get User Futures Fills diff --git a/RPC/aster-chain-rpc_CN.md b/RPC/aster-chain-rpc_CN.md index 2234350..aa518e0 100644 --- a/RPC/aster-chain-rpc_CN.md +++ b/RPC/aster-chain-rpc_CN.md @@ -189,14 +189,16 @@ curl -X POST "https://tapi.asterdex.com/info" \ "symbol": "TRUMPUSDT", "side": "SELL", "type": "LIMIT", - "origQty": "4.44000000" + "origQty": "4.44000000", + "price": "10.00000000" }, { "orderId": "web_AD_4u1emfjslzt4hqnc5_98", "symbol": "BTCUSDT", "side": "BUY", "type": "LIMIT", - "origQty": "0.00100000" + "origQty": "0.00100000", + "price": "95000.00000000" } ] }, @@ -217,6 +219,7 @@ openOrders[].symbol | STRING | 交易对名称 openOrders[].side | STRING | 买卖方向:`BUY` 买入 / `SELL` 卖出 openOrders[].type | STRING | 订单类型:如 `LIMIT` 限价单、`MARKET` 市价单 openOrders[].origQty | STRING | 原始委托数量 +openOrders[].price | STRING | 委托价格 ## 查询用户期货成交记录 From 156b157eb61d3949cbccaa9a0bc93741add9f5c9 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Thu, 7 May 2026 14:09:15 +0800 Subject: [PATCH 105/131] docs: update modify order rule - quantity and price are both required MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit quantity 与 price 均必须发送(原文:必须至少发送一个) Co-Authored-By: Claude Sonnet 4.6 --- V3(Recommended)/EN/aster-finance-futures-api-testnet.md | 2 +- V3(Recommended)/EN/aster-finance-futures-api-v3.md | 2 +- .../aster-finance-futures-api-testnet_CN.md" | 2 +- .../aster-finance-futures-api-v3_CN.md" | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/V3(Recommended)/EN/aster-finance-futures-api-testnet.md b/V3(Recommended)/EN/aster-finance-futures-api-testnet.md index 5cbdfa1..c541370 100644 --- a/V3(Recommended)/EN/aster-finance-futures-api-testnet.md +++ b/V3(Recommended)/EN/aster-finance-futures-api-testnet.md @@ -2283,7 +2283,7 @@ price | DECIMAL | NO | Order price * Either `orderId` or `origClientOrderId` must be sent. If both are sent, `orderId` takes precedence. -* At least one of `quantity` or `price` must be sent. +* Both `quantity` and `price` must be sent. * If the new `quantity` or `price` does not meet `PRICE_FILTER` / `PERCENT_FILTER` / `LOT_SIZE` restrictions, the modification will be rejected and the original order will remain. * Only `LIMIT` order type is supported. * Maximum 10000 modifications per order. diff --git a/V3(Recommended)/EN/aster-finance-futures-api-v3.md b/V3(Recommended)/EN/aster-finance-futures-api-v3.md index 27d9145..506adf6 100644 --- a/V3(Recommended)/EN/aster-finance-futures-api-v3.md +++ b/V3(Recommended)/EN/aster-finance-futures-api-v3.md @@ -2497,7 +2497,7 @@ price | DECIMAL | NO | Order price * Either `orderId` or `origClientOrderId` must be sent. If both are sent, `orderId` takes precedence. -* At least one of `quantity` or `price` must be sent. +* Both `quantity` and `price` must be sent. * If the new `quantity` or `price` does not meet `PRICE_FILTER` / `PERCENT_FILTER` / `LOT_SIZE` restrictions, the modification will be rejected and the original order will remain. * Only `LIMIT` order type is supported. * Maximum 10000 modifications per order. diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" index 6962832..1189214 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" @@ -2473,7 +2473,7 @@ price | DECIMAL | NO | 委托价格 * orderId 与 origClientOrderId 必须至少发送一个,同时发送则以 order id为准 -* quantity 与 price 必须至少发送一个 +* quantity 与 price 均必须发送 * 当新订单的quantity 或 price不满足PRICE_FILTER / PERCENT_FILTER / LOT_SIZE限制,修改会被拒绝,原订单依旧被保留 订单只支持limit类型 * 同一订单修改次数最多10000次 diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" index 892a48b..269305e 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" @@ -2558,7 +2558,7 @@ price | DECIMAL | NO | 委托价格 * orderId 与 origClientOrderId 必须至少发送一个,同时发送则以 order id为准 -* quantity 与 price 必须至少发送一个 +* quantity 与 price 均必须发送 * 当新订单的quantity 或 price不满足PRICE_FILTER / PERCENT_FILTER / LOT_SIZE限制,修改会被拒绝,原订单依旧被保留 订单只支持limit类型 * 同一订单修改次数最多10000次 From e3fb1c73e6b52300503b5ab5fd5f67fb05270925 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Thu, 7 May 2026 20:26:11 +0800 Subject: [PATCH 106/131] docs: update sub-account transfer scenarios and notes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add Sub A → Sub B transfer row using sub-account private key across all V3 docs (EN/CN, mainnet/testnet). Update Important Notes to reflect that sub-account private key also supports sub→sub transfers, with the source address being the signing sub-account. Co-Authored-By: Claude Sonnet 4.6 --- V3(Recommended)/EN/aster-finance-futures-api-testnet.md | 3 ++- V3(Recommended)/EN/aster-finance-futures-api-v3.md | 4 ++-- .../aster-finance-futures-api-testnet_CN.md" | 3 ++- .../aster-finance-futures-api-v3_CN.md" | 3 ++- 4 files changed, 8 insertions(+), 5 deletions(-) diff --git a/V3(Recommended)/EN/aster-finance-futures-api-testnet.md b/V3(Recommended)/EN/aster-finance-futures-api-testnet.md index c541370..a0b7088 100644 --- a/V3(Recommended)/EN/aster-finance-futures-api-testnet.md +++ b/V3(Recommended)/EN/aster-finance-futures-api-testnet.md @@ -3736,6 +3736,7 @@ toAccountAddress={toAccountAddress}&asset={asset}&amount={amount}&kindType={kind | Master → Sub | Master account address | *(not required)* | Master account wallet private key | | Sub → Master | Sub-account address | *(not required)* | Sub-account wallet private key | | Sub A → Sub B | Master account address | Sub A address | Master account wallet private key | +| Sub A → Sub B | Sub-account address | *(not required)* | Sub-account wallet private key | --- @@ -3743,7 +3744,7 @@ toAccountAddress={toAccountAddress}&asset={asset}&amount={amount}&kindType={kind * `signature` **must be signed using the `user` account's wallet private key** — the signer private key must not be used as a substitute. * The `user` field must match the address corresponding to the private key used for signing. -* When signing with a **sub-account's private key**, only transfers **to the master account** are supported. Sub→Sub transfers must be signed by the master account. +* When signing with a **sub-account's private key**, transfers **to the master account** are supported. Sub→Sub transfers are also supported, with the source address being the signing **sub-account**. * Transfers to or from a **frozen sub-account** will fail. * Transfers to **external addresses** (addresses not within the sub-account relationship) are not supported. diff --git a/V3(Recommended)/EN/aster-finance-futures-api-v3.md b/V3(Recommended)/EN/aster-finance-futures-api-v3.md index 506adf6..6d12961 100644 --- a/V3(Recommended)/EN/aster-finance-futures-api-v3.md +++ b/V3(Recommended)/EN/aster-finance-futures-api-v3.md @@ -4000,14 +4000,14 @@ toAccountAddress={toAccountAddress}&asset={asset}&amount={amount}&kindType={kind | Master → Sub | Master account address | *(not required)* | Master account wallet private key | | Sub → Master | Sub-account address | *(not required)* | Sub-account wallet private key | | Sub A → Sub B | Master account address | Sub A address | Master account wallet private key | - +| Sub A → Sub B | Sub-account address | *(not required)* | Sub-account wallet private key | --- ### Important Notes * `signature` **must be signed using the `user` account's wallet private key** — the signer private key must not be used as a substitute. * The `user` field must match the address corresponding to the private key used for signing. -* When signing with a **sub-account's private key**, only transfers **to the master account** are supported. Sub→Sub transfers must be signed by the master account. +* When signing with a **sub-account's private key**, transfers **to the master account** are supported. Sub→Sub transfers are also supported, with the source address being the signing **sub-account**. * Transfers to or from a **frozen sub-account** will fail. * Transfers to **external addresses** (addresses not within the sub-account relationship) are not supported. diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" index 1189214..eb75470 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" @@ -3964,6 +3964,7 @@ toAccountAddress={toAccountAddress}&asset={asset}&amount={amount}&kindType={kind | 母账户 → 子账户 | 母账户地址 | *(无需传入)* | 母账户钱包私钥 | | 子账户 → 母账户 | 子账户地址 | *(无需传入)* | 子账户钱包私钥 | | 子账户 A → 子账户 B | 母账户地址 | 子账户 A 地址 | 母账户钱包私钥 | +| 子账户 A → 子账户 B | 子账户地址 | *(无需传入)* | 子账户钱包私钥 | --- @@ -3971,7 +3972,7 @@ toAccountAddress={toAccountAddress}&asset={asset}&amount={amount}&kindType={kind * `signature` **必须使用 `user` 账户的钱包私钥签名**,不可使用 signer 私钥替代。 * `user` 字段必须与签名所用私钥对应的地址一致。 -* 使用**子账户私钥**签名时,仅支持向**母账户**划转;子→子划转必须由母账户签名。 +* 使用**子账户私钥**签名时,支持向**母账户**划转;也支持子→子划转,此时转账的来源地址为签名的**子账户** * 向**已冻结的子账户**划转或从**已冻结的子账户**划出均会失败。 * 不支持向**非子账户关系内的外部地址**划转。 diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" index 269305e..0b97b2d 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" @@ -4154,6 +4154,7 @@ toAccountAddress={toAccountAddress}&asset={asset}&amount={amount}&kindType={kind | 母账户 → 子账户 | 母账户地址 | *(无需传入)* | 母账户钱包私钥 | | 子账户 → 母账户 | 子账户地址 | *(无需传入)* | 子账户钱包私钥 | | 子账户 A → 子账户 B | 母账户地址 | 子账户 A 地址 | 母账户钱包私钥 | +| 子账户 A → 子账户 B | 子账户地址 | *(无需传入)* | 子账户钱包私钥 | --- @@ -4161,7 +4162,7 @@ toAccountAddress={toAccountAddress}&asset={asset}&amount={amount}&kindType={kind * `signature` **必须使用 `user` 账户的钱包私钥签名**,不可使用 signer 私钥替代。 * `user` 字段必须与签名所用私钥对应的地址一致。 -* 使用**子账户私钥**签名时,仅支持向**母账户**划转;子→子划转必须由母账户签名。 +* 使用**子账户私钥**签名时,支持向**母账户**划转;也支持子→子划转,此时转账的来源地址为签名的**子账户** * 向**已冻结的子账户**划转或从**已冻结的子账户**划出均会失败。 * 不支持向**非子账户关系内的外部地址**划转。 From 698b3f4a1f80bf4093621dd8dc34d2bd04839398 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Mon, 11 May 2026 20:39:54 +0800 Subject: [PATCH 107/131] docs: add migrateUser and migrateUser/history API documentation Add POST /fapi/v3/asset/migrateUser (WITHDRAW) and GET /fapi/v3/asset/migrateUser/history (USER_DATA) to both v3 and testnet docs in English and Chinese. Co-Authored-By: Claude Sonnet 4.6 --- .../EN/aster-finance-futures-api-testnet.md | 80 +++++++++++++++++ .../EN/aster-finance-futures-api-v3.md | 80 +++++++++++++++++ .../aster-finance-futures-api-testnet_CN.md" | 84 ++++++++++++++++++ .../aster-finance-futures-api-v3_CN.md" | 85 +++++++++++++++++++ 4 files changed, 329 insertions(+) diff --git a/V3(Recommended)/EN/aster-finance-futures-api-testnet.md b/V3(Recommended)/EN/aster-finance-futures-api-testnet.md index a0b7088..fa4fc18 100644 --- a/V3(Recommended)/EN/aster-finance-futures-api-testnet.md +++ b/V3(Recommended)/EN/aster-finance-futures-api-testnet.md @@ -100,6 +100,8 @@ - [Get Sub-Account List (USER_DATA)](#get-sub-account-list-user_data) - [Update Sub-Account (TRADE)](#update-sub-account-trade) - [Sub-Account Transfer (TRADE)](#sub-account-transfer-trade) + - [Migrate User Assets (WITHDRAW)](#migrate-user-assets-withdraw) + - [Migrate User Assets History (USER_DATA)](#migrate-user-assets-history-user_data) - [User Data Streams](#user-data-streams) - [Start User Data Stream (USER_STREAM)](#start-user-data-stream-user_stream) - [Keepalive User Data Stream (USER_STREAM)](#keepalive-user-data-stream-user_stream) @@ -3750,6 +3752,84 @@ toAccountAddress={toAccountAddress}&asset={asset}&amount={amount}&kindType={kind +# Migrate User Assets (WITHDRAW) + +> **Response:** + +```javascript +{ + "batchId": "a1B2c3D4e5F6g7H8i9J0k1" // batch ID for querying migration history +} +``` + +`POST /fapi/v3/asset/migrateUser` + +**Weight:** 50 + +**Parameters:** + +| Name | Type | Required | Description | +|------|------|----------|-------------| +| user | STRING | YES | Source account wallet address — the account from which assets will be migrated | +| nonce | LONG | YES | Microsecond-level timestamp, used for replay attack prevention | +| signature | STRING | YES | Signature over the request body, signed using the `user` account's wallet private key (EIP-712 for EVM addresses, Ed25519 for Solana addresses) | + +**Notes:** + +* The source account must have **no open positions** before migration can proceed; the request will be rejected otherwise. +* The source account must have **no open orders** before migration can proceed; the request will be rejected otherwise. +* All assets with a positive available balance are automatically included. Assets with zero balance are skipped. +* Up to **300 assets** are processed per migration batch. +* Assets are transferred to the **authenticated user's account** (the destination). +* If the source account has no assets with a positive balance, an empty response is returned and no transfer is initiated. +* Record the returned `batchId` to query migration status via [Migrate User Assets History](#migrate-user-assets-history-user_data). + +--- + +# Migrate User Assets History (USER_DATA) + +> **Response:** + +```javascript +{ + "batchId": "a1B2c3D4e5F6g7H8i9J0k1", + "fromUserId": 12345678, + "toUserId": 87654321, + "status": "SUCCESS", // migration status + "items": [ + { + "asset": "USDT", + "amount": "500.00000000" + }, + { + "asset": "BTC", + "amount": "0.05000000" + } + ] +} +``` + +`GET /fapi/v3/asset/migrateUser/history` + +**Weight:** 50 + +**Parameters:** + +| Name | Type | Required | Description | +|------|------|----------|-------------| +| batchId | STRING | YES | Batch ID returned from the [Migrate User Assets](#migrate-user-assets-withdraw) endpoint | +| nonce | LONG | YES | Microsecond-level timestamp, used for replay attack prevention | +| user | STRING | YES | Authenticated user's wallet address | +| signer | STRING | YES | Signer address associated with the `user` account | +| signature | STRING | YES | Signature over the request body | + +**Notes:** + +* `batchId` is mandatory. Each `batchId` corresponds to a single migration batch. +* The query is scoped to the authenticated user — only migrations initiated by or associated with the authenticated account are returned. + + + # User Data Streams * The base API endpoint is: **https://fapi.asterdex-testnet.com** diff --git a/V3(Recommended)/EN/aster-finance-futures-api-v3.md b/V3(Recommended)/EN/aster-finance-futures-api-v3.md index 6d12961..25a7669 100644 --- a/V3(Recommended)/EN/aster-finance-futures-api-v3.md +++ b/V3(Recommended)/EN/aster-finance-futures-api-v3.md @@ -104,6 +104,8 @@ - [Get Sub-Account List (USER_DATA)](#get-sub-account-list-user_data) - [Update Sub-Account (TRADE)](#update-sub-account-trade) - [Sub-Account Transfer (TRADE)](#sub-account-transfer-trade) + - [Migrate User Assets (WITHDRAW)](#migrate-user-assets-withdraw) + - [Migrate User Assets History (USER_DATA)](#migrate-user-assets-history-user_data) - [User Data Streams](#user-data-streams) - [Start User Data Stream (USER_STREAM)](#start-user-data-stream-user_stream) - [Keepalive User Data Stream (USER_STREAM)](#keepalive-user-data-stream-user_stream) @@ -4013,6 +4015,84 @@ toAccountAddress={toAccountAddress}&asset={asset}&amount={amount}&kindType={kind +# Migrate User Assets (WITHDRAW) + +> **Response:** + +```javascript +{ + "batchId": "a1B2c3D4e5F6g7H8i9J0k1" // batch ID for querying migration history +} +``` + +`POST /fapi/v3/asset/migrateUser` + +**Weight:** 50 + +**Parameters:** + +| Name | Type | Required | Description | +|------|------|----------|-------------| +| user | STRING | YES | Source account wallet address — the account from which assets will be migrated | +| nonce | LONG | YES | Microsecond-level timestamp, used for replay attack prevention | +| signature | STRING | YES | Signature over the request body, signed using the `user` account's wallet private key (EIP-712 for EVM addresses, Ed25519 for Solana addresses) | + +**Notes:** + +* The source account must have **no open positions** before migration can proceed; the request will be rejected otherwise. +* The source account must have **no open orders** before migration can proceed; the request will be rejected otherwise. +* All assets with a positive available balance are automatically included. Assets with zero balance are skipped. +* Up to **300 assets** are processed per migration batch. +* Assets are transferred to the **authenticated user's account** (the destination). +* If the source account has no assets with a positive balance, an empty response is returned and no transfer is initiated. +* Record the returned `batchId` to query migration status via [Migrate User Assets History](#migrate-user-assets-history-user_data). + +--- + +# Migrate User Assets History (USER_DATA) + +> **Response:** + +```javascript +{ + "batchId": "a1B2c3D4e5F6g7H8i9J0k1", + "fromUserId": 12345678, + "toUserId": 87654321, + "status": "SUCCESS", // migration status + "items": [ + { + "asset": "USDT", + "amount": "500.00000000" + }, + { + "asset": "BTC", + "amount": "0.05000000" + } + ] +} +``` + +`GET /fapi/v3/asset/migrateUser/history` + +**Weight:** 50 + +**Parameters:** + +| Name | Type | Required | Description | +|------|------|----------|-------------| +| batchId | STRING | YES | Batch ID returned from the [Migrate User Assets](#migrate-user-assets-withdraw) endpoint | +| nonce | LONG | YES | Microsecond-level timestamp, used for replay attack prevention | +| user | STRING | YES | Authenticated user's wallet address | +| signer | STRING | YES | Signer address associated with the `user` account | +| signature | STRING | YES | Signature over the request body | + +**Notes:** + +* `batchId` is mandatory. Each `batchId` corresponds to a single migration batch. +* The query is scoped to the authenticated user — only migrations initiated by or associated with the authenticated account are returned. + + + # User Data Streams * The base API endpoint is: **https://fapi.asterdex.com** diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" index eb75470..16d10f0 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" @@ -94,6 +94,8 @@ - [查询子账户列表 (USER_DATA)](#查询子账户列表-user_data) - [更新子账户 (TRADE)](#更新子账户-trade) - [子账户划转 (TRADE)](#子账户划转-trade) + - [用户资产迁移 (WITHDRAW)](#用户资产迁移-withdraw) + - [用户资产迁移历史 (USER_DATA)](#用户资产迁移历史-user_data) - [Websocket 账户信息推送](#websocket-账户信息推送) - [生成listenKey (USER_STREAM)](#生成listenkey-user_stream) - [延长listenKey有效期 (USER_STREAM)](#延长listenkey有效期-user_stream) @@ -3978,6 +3980,88 @@ toAccountAddress={toAccountAddress}&asset={asset}&amount={amount}&kindType={kind +# 用户资产迁移 (WITHDRAW) + +> **响应:** + +```javascript +{ + "batchId": "a1B2c3D4e5F6g7H8i9J0k1" // 批次 ID,用于查询迁移历史 +} +``` + +`POST /fapi/v3/asset/migrateUser` + +**权重:** 50 + +**所需权限:** WITHDRAW + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| user | STRING | YES | 来源账户钱包地址,即待迁移资产所在的账户 | +| nonce | LONG | YES | 微秒级时间戳,用于防重放攻击 | +| signature | STRING | YES | 对请求体的签名,**必须使用 `user` 账户的钱包私钥签名**(EVM 地址使用 EIP-712,Solana 地址使用 Ed25519) | + +**注意事项:** + +* 来源账户必须**无持仓**,否则请求将被拒绝。 +* 来源账户必须**无挂单**,否则请求将被拒绝。 +* 所有可用余额大于 0 的资产将自动包含在迁移批次中;余额为 0 的资产将被跳过。 +* 单次迁移批次最多处理 **300 种资产**。 +* 资产将转移至**当前已认证用户的账户**(目标账户)。 +* 若来源账户无可用资产,接口将返回空响应,不发起实际转账。 +* 请记录返回的 `batchId`,以便通过 [用户资产迁移历史](#用户资产迁移历史-user_data) 接口查询迁移状态。 + +--- + +# 用户资产迁移历史 (USER_DATA) + +> **响应:** + +```javascript +{ + "batchId": "a1B2c3D4e5F6g7H8i9J0k1", + "fromUserId": 12345678, + "toUserId": 87654321, + "status": "SUCCESS", // 迁移状态 + "items": [ + { + "asset": "USDT", + "amount": "500.00000000" + }, + { + "asset": "BTC", + "amount": "0.05000000" + } + ] +} +``` + +`GET /fapi/v3/asset/migrateUser/history` + +**权重:** 50 + +**所需权限:** USER_DATA + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| batchId | STRING | YES | 调用 [用户资产迁移](#用户资产迁移-withdraw) 接口时返回的批次 ID | +| nonce | LONG | YES | 微秒级时间戳,用于防重放攻击 | +| user | STRING | YES | 当前认证用户的钱包地址 | +| signer | STRING | YES | 与 `user` 关联的 signer 地址 | +| signature | STRING | YES | 对请求体的签名 | + +**注意事项:** + +* `batchId` 为必传参数,每个 `batchId` 对应一次迁移批次。 +* 查询结果仅限当前认证用户——只返回与该账户相关的迁移记录。 + + + # Websocket 账户信息推送 diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" index 0b97b2d..cad2d1f 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" @@ -102,6 +102,8 @@ - [查询子账户列表 (USER_DATA)](#查询子账户列表-user_data) - [更新子账户 (TRADE)](#更新子账户-trade) - [子账户划转 (TRADE)](#子账户划转-trade) + - [用户资产迁移 (WITHDRAW)](#用户资产迁移-withdraw) + - [用户资产迁移历史 (USER_DATA)](#用户资产迁移历史-user_data) - [Websocket 账户信息推送](#websocket-账户信息推送) - [生成listenKey (USER_STREAM)](#生成listenkey-user_stream) - [延长listenKey有效期 (USER_STREAM)](#延长listenkey有效期-user_stream) @@ -4167,6 +4169,89 @@ toAccountAddress={toAccountAddress}&asset={asset}&amount={amount}&kindType={kind * 不支持向**非子账户关系内的外部地址**划转。 + +# 用户资产迁移 (WITHDRAW) + +> **响应:** + +```javascript +{ + "batchId": "a1B2c3D4e5F6g7H8i9J0k1" // 批次 ID,用于查询迁移历史 +} +``` + +`POST /fapi/v3/asset/migrateUser` + +**权重:** 50 + +**所需权限:** WITHDRAW + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| user | STRING | YES | 来源账户钱包地址,即待迁移资产所在的账户 | +| nonce | LONG | YES | 微秒级时间戳,用于防重放攻击 | +| signature | STRING | YES | 对请求体的签名,**必须使用 `user` 账户的钱包私钥签名**(EVM 地址使用 EIP-712,Solana 地址使用 Ed25519) | + +**注意事项:** + +* 来源账户必须**无持仓**,否则请求将被拒绝。 +* 来源账户必须**无挂单**,否则请求将被拒绝。 +* 所有可用余额大于 0 的资产将自动包含在迁移批次中;余额为 0 的资产将被跳过。 +* 单次迁移批次最多处理 **300 种资产**。 +* 资产将转移至**当前已认证用户的账户**(目标账户)。 +* 若来源账户无可用资产,接口将返回空响应,不发起实际转账。 +* 请记录返回的 `batchId`,以便通过 [用户资产迁移历史](#用户资产迁移历史-user_data) 接口查询迁移状态。 + +--- + +# 用户资产迁移历史 (USER_DATA) + +> **响应:** + +```javascript +{ + "batchId": "a1B2c3D4e5F6g7H8i9J0k1", + "fromUserId": 12345678, + "toUserId": 87654321, + "status": "SUCCESS", // 迁移状态 + "items": [ + { + "asset": "USDT", + "amount": "500.00000000" + }, + { + "asset": "BTC", + "amount": "0.05000000" + } + ] +} +``` + +`GET /fapi/v3/asset/migrateUser/history` + +**权重:** 50 + +**所需权限:** USER_DATA + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| batchId | STRING | YES | 调用 [用户资产迁移](#用户资产迁移-withdraw) 接口时返回的批次 ID | +| nonce | LONG | YES | 微秒级时间戳,用于防重放攻击 | +| user | STRING | YES | 当前认证用户的钱包地址 | +| signer | STRING | YES | 与 `user` 关联的 signer 地址 | +| signature | STRING | YES | 对请求体的签名 | + +**注意事项:** + +* `batchId` 为必传参数,每个 `batchId` 对应一次迁移批次。 +* 查询结果仅限当前认证用户——只返回与该账户相关的迁移记录。 + + + # Websocket 账户信息推送 From 93e2216e19ffc1c66d06fce193f49abc586124ed Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Mon, 11 May 2026 20:41:26 +0800 Subject: [PATCH 108/131] demo code --- demo/aster-code.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/demo/aster-code.py b/demo/aster-code.py index bbfdc21..a367a0a 100644 --- a/demo/aster-code.py +++ b/demo/aster-code.py @@ -51,7 +51,8 @@ placeOrder = {'url': '/fapi/v3/order', 'method': 'POST', 'params':{'symbol': 'BTCUSDT', 'type': 'MARKET','builder':builder,'feeRate':0.00001, 'side': 'BUY','quantity': "0.03"}} - +migrateUser = {'url': '/fapi/v3/asset/migrateUser', 'method': 'POST', + 'params':{},'main':True,"primary_type":"UserAssetMigrate" } # 模板只包含 EIP712Domain eip712_template = { @@ -237,6 +238,7 @@ def send_by_url(method_config): # send_by_url(updateBuilder) # send_by_url(delBuilder) # send_by_url(placeOrder) + #send_by_url(migrateUser) From 0e10ef64f352ebb01ca088749eb58b4eafd0e98b Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Tue, 12 May 2026 17:40:50 +0800 Subject: [PATCH 109/131] docs: add registerAndApproveAgent API documentation Add POST /fapi/v3/registerAndApproveAgent endpoint docs to all four futures API files (v3 + testnet, EN + CN) and create CHANGELOG.md. Co-Authored-By: Claude Sonnet 4.6 --- CHANGELOG.md | 38 ++++++++ .../EN/aster-finance-futures-api-testnet.md | 71 +++++++++++++++ .../EN/aster-finance-futures-api-v3.md | 89 +++++++++++++++++++ .../aster-finance-futures-api-testnet_CN.md" | 71 +++++++++++++++ .../aster-finance-futures-api-v3_CN.md" | 88 ++++++++++++++++++ 5 files changed, 357 insertions(+) create mode 100644 CHANGELOG.md diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..fef95e4 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,38 @@ +# Changelog + +## 2026-05-12 + +### Added + +#### `POST /fapi/v3/registerAndApproveAgent` — Register and Approve Agent / 注册并授权 Agent + +A new public endpoint that **registers an API agent account and grants trading/withdrawal permissions in a single atomic call**. + +新增公开接口,**一次调用完成 Agent 账户注册与权限授予**。 + +**Key details / 要点:** + +- **No authentication required** — authorization is verified through the `signature` parameter (no API Key or HMAC header needed). + **无需鉴权** — 通过请求参数中的 `signature` 验证,无需 API Key 或 HMAC 请求头。 +- `signature` is generated by signing the concatenated request parameters (`key=value&key=value...`) with the user's wallet private key. + `signature` 通过对拼接的请求参数字符串(`key=value&key=value...`)使用用户钱包私钥签名生成。 +- Supports **EVM** (EIP-712 Typed Data, chainId=56) and **Solana** (Ed25519) signing. + 支持 **EVM**(EIP-712 Typed Data,chainId=56)和 **Solana**(Ed25519)签名。 +- Configurable per-agent permissions: `canSpotTrade`, `canPerpTrade`, `canWithdraw`. + 可配置 Agent 权限:`canSpotTrade`、`canPerpTrade`、`canWithdraw`。 +- `ipWhitelist`: space-separated, supports CIDR; **required when `canWithdraw=true`**. + `ipWhitelist`:空格分隔,支持 CIDR;**`canWithdraw=true` 时必填**。 +- Optional referral code: `agentCode`. + 可选邀请码:`agentCode`。 +- Agent validity bounded by `expired` (millisecond timestamp) / Agent 有效期由 `expired`(毫秒时间戳)控制。 +- Rate weight / 权重: **50**. + +--- + +## 2025-xx-xx + +### Added + +#### `POST /fapi/v3/asset/migrateUser` — Migrate User Assets / 用户资产迁移 + +#### `GET /fapi/v3/asset/migrateUser/history` — Migrate User Assets History / 用户资产迁移历史 diff --git a/V3(Recommended)/EN/aster-finance-futures-api-testnet.md b/V3(Recommended)/EN/aster-finance-futures-api-testnet.md index fa4fc18..d72a286 100644 --- a/V3(Recommended)/EN/aster-finance-futures-api-testnet.md +++ b/V3(Recommended)/EN/aster-finance-futures-api-testnet.md @@ -102,6 +102,7 @@ - [Sub-Account Transfer (TRADE)](#sub-account-transfer-trade) - [Migrate User Assets (WITHDRAW)](#migrate-user-assets-withdraw) - [Migrate User Assets History (USER_DATA)](#migrate-user-assets-history-user_data) + - [Register and Approve Agent (PUBLIC)](#register-and-approve-agent-public) - [User Data Streams](#user-data-streams) - [Start User Data Stream (USER_STREAM)](#start-user-data-stream-user_stream) - [Keepalive User Data Stream (USER_STREAM)](#keepalive-user-data-stream-user_stream) @@ -3830,6 +3831,76 @@ toAccountAddress={toAccountAddress}&asset={asset}&amount={amount}&kindType={kind + +# Register and Approve Agent (PUBLIC) + +> **Response:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +`POST /fapi/v3/registerAndApproveAgent` + +Registers a new API agent account and grants it trading/withdrawal permissions in a single call. Once approved, the agent can use API Keys to act on behalf of the user within the specified permission scope. + +**Weight:** 50 + +**Parameters:** + +| Name | Type | Required | Description | +|------|------|----------|-------------| +| user | STRING | YES | User's wallet address | +| nonce | LONG | YES | Microsecond-level timestamp, used for replay attack prevention | +| agentName | STRING | YES | Display name for the agent | +| agentAddress | STRING | YES | Agent's wallet address | +| expired | LONG | YES | Agent expiration timestamp (milliseconds) | +| signatureChainId | LONG | YES | Chain ID used when generating the signature (`56` for EVM addresses, `101` for Solana addresses) | +| signature | STRING | YES | Signature over the message body, signed using the user's wallet private key (see Signature Instructions below) | +| canSpotTrade | BOOLEAN | YES | Whether the agent is permitted to place spot orders | +| canPerpTrade | BOOLEAN | YES | Whether the agent is permitted to place perpetual futures orders | +| canWithdraw | BOOLEAN | YES | Whether the agent is permitted to initiate withdrawals | +| ipWhitelist | STRING | NO | Space-separated list of permitted IP addresses or CIDR ranges (e.g. `192.168.1.1 10.0.0.0/24`). **Required when `canWithdraw` is `true`.** | +| agentCode | STRING | NO | Referral/invitation code for agent registration | + +--- + +### Signature Instructions + +Sign the following message body using the **user's wallet private key**: + +``` +user={user}&nonce={nonce}&agentName={agentName}&agentAddress={agentAddress}&expired={expired}&signatureChainId={signatureChainId}&canSpotTrade={canSpotTrade}&canPerpTrade={canPerpTrade}&canWithdraw={canWithdraw} +``` + +If `ipWhitelist` is provided, append it to the message body: + +``` +user={user}&nonce={nonce}&agentName={agentName}&agentAddress={agentAddress}&expired={expired}&signatureChainId={signatureChainId}&canSpotTrade={canSpotTrade}&canPerpTrade={canPerpTrade}&canWithdraw={canWithdraw}&ipWhitelist={ipWhitelist} +``` + +#### Supported Signing Algorithms + +| Account Type | Signing Algorithm | Encoding | +|---|---|---| +| EVM Address | EIP-712 Typed Data (chainId=56, message.msg=message body) | Hex | +| Solana Address | Ed25519 | Base58 | + +--- + +### Important Notes + +* `nonce` must be a microsecond-precision timestamp. The difference from server time must not exceed **10 seconds**, and the same nonce cannot be reused. +* `expired` is the agent's validity deadline in **milliseconds**. The agent will automatically expire after this timestamp. +* `ipWhitelist` uses **spaces** as the delimiter and supports CIDR notation (e.g. `192.168.1.1 10.0.0.0/24`). **`ipWhitelist` is required and must not be empty when `canWithdraw` is `true`.** +* This endpoint is **unauthenticated** — no API Key or HMAC header is required. All authorization is verified through the on-chain `signature`. +* This endpoint combines agent registration and permission granting into a single call, equivalent to the standalone registration step followed by `approveAgent`. + + + # User Data Streams * The base API endpoint is: **https://fapi.asterdex-testnet.com** diff --git a/V3(Recommended)/EN/aster-finance-futures-api-v3.md b/V3(Recommended)/EN/aster-finance-futures-api-v3.md index 25a7669..f8bed7a 100644 --- a/V3(Recommended)/EN/aster-finance-futures-api-v3.md +++ b/V3(Recommended)/EN/aster-finance-futures-api-v3.md @@ -106,6 +106,7 @@ - [Sub-Account Transfer (TRADE)](#sub-account-transfer-trade) - [Migrate User Assets (WITHDRAW)](#migrate-user-assets-withdraw) - [Migrate User Assets History (USER_DATA)](#migrate-user-assets-history-user_data) + - [Register and Approve Agent (PUBLIC)](#register-and-approve-agent-public) - [User Data Streams](#user-data-streams) - [Start User Data Stream (USER_STREAM)](#start-user-data-stream-user_stream) - [Keepalive User Data Stream (USER_STREAM)](#keepalive-user-data-stream-user_stream) @@ -4093,6 +4094,94 @@ toAccountAddress={toAccountAddress}&asset={asset}&amount={amount}&kindType={kind + +# Register and Approve Agent (PUBLIC) + +> **Response:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +`POST /fapi/v3/registerAndApproveAgent` + +Registers a new API agent account and grants it trading/withdrawal permissions in a single call. Once approved, the agent can use API Keys to act on behalf of the user within the specified permission scope. + +**Weight:** 50 + +**Parameters:** + +| Name | Type | Required | Description | +|------|------|----------|-------------| +| user | STRING | YES | User's wallet address | +| nonce | LONG | YES | Microsecond-level timestamp, used for replay attack prevention | +| agentName | STRING | YES | Display name for the agent | +| agentAddress | STRING | YES | Agent's wallet address | +| expired | LONG | YES | Agent expiration timestamp (milliseconds) | +| signatureChainId | LONG | YES | Chain ID used when generating the signature (`56` for EVM addresses, `101` for Solana addresses) | +| signature | STRING | YES | Signature over the message body, signed using the user's wallet private key (see Signature Instructions below) | +| canSpotTrade | BOOLEAN | YES | Whether the agent is permitted to place spot orders | +| canPerpTrade | BOOLEAN | YES | Whether the agent is permitted to place perpetual futures orders | +| canWithdraw | BOOLEAN | YES | Whether the agent is permitted to initiate withdrawals | +| ipWhitelist | STRING | NO | Space-separated list of permitted IP addresses or CIDR ranges (e.g. `192.168.1.1 10.0.0.0/24`). **Required when `canWithdraw` is `true`.** | +| agentCode | STRING | NO | Referral/invitation code for agent registration | + +--- + +### Signature Instructions + +Sign the following message body using the **user's wallet private key**: + +``` +msg: user={user}&nonce={nonce}&agentName={agentName}&agentAddress={agentAddress}&expired={expired}&signatureChainId={signatureChainId}&canSpotTrade={canSpotTrade}&canPerpTrade={canPerpTrade}&canWithdraw={canWithdraw} + +typed_data = { + "types": { + "EIP712Domain": [ + {"name": "name", "type": "string"}, + {"name": "version", "type": "string"}, + {"name": "chainId", "type": "uint256"}, + {"name": "verifyingContract", "type": "address"} + ], + "Message": [ + { "name": "msg", "type": "string" } + ] + }, + "primaryType": "Message", + "domain": { + "name": "AsterSignTransaction", + "version": "1", + "chainId": 1666, + "verifyingContract": "0x0000000000000000000000000000000000000000" + }, + "message": { + "msg": "$msg" + } +} +``` + +#### Supported Signing Algorithms + +| Account Type | Signing Algorithm | Encoding | +|---|---|---| +| EVM Address | EIP-712 Typed Data (chainId=56, message.msg=message body) | Hex | +| Solana Address | Ed25519 | Base58 | + +--- + +### Important Notes + +* `nonce` must be a microsecond-precision timestamp. The difference from server time must not exceed **10 seconds**, and the same nonce cannot be reused. +* `expired` is the agent's validity deadline in **milliseconds**. The agent will automatically expire after this timestamp. +* `ipWhitelist` uses **spaces** as the delimiter and supports CIDR notation (e.g. `192.168.1.1 10.0.0.0/24`). **`ipWhitelist` is required and must not be empty when `canWithdraw` is `true`.** +* This endpoint is **unauthenticated** — no API Key or HMAC header is required. All authorization is verified through the on-chain `signature`. +* This endpoint combines agent registration and permission granting into a single call, equivalent to the standalone registration step followed by `approveAgent`. + + + # User Data Streams * The base API endpoint is: **https://fapi.asterdex.com** diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" index 16d10f0..3c294a7 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" @@ -96,6 +96,7 @@ - [子账户划转 (TRADE)](#子账户划转-trade) - [用户资产迁移 (WITHDRAW)](#用户资产迁移-withdraw) - [用户资产迁移历史 (USER_DATA)](#用户资产迁移历史-user_data) + - [注册并授权 Agent (PUBLIC)](#注册并授权-agent-public) - [Websocket 账户信息推送](#websocket-账户信息推送) - [生成listenKey (USER_STREAM)](#生成listenkey-user_stream) - [延长listenKey有效期 (USER_STREAM)](#延长listenkey有效期-user_stream) @@ -4062,6 +4063,76 @@ toAccountAddress={toAccountAddress}&asset={asset}&amount={amount}&kindType={kind + +# 注册并授权 Agent (PUBLIC) + +> **响应:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +`POST /fapi/v3/registerAndApproveAgent` + +注册新的 API Agent 账户并一次性授予其交易/提现权限。Agent 授权后,可使用 API Key 在指定权限范围内代表用户进行操作。 + +**权重:** 50 + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| user | STRING | YES | 用户钱包地址 | +| nonce | LONG | YES | 微秒级时间戳,用于防重放攻击 | +| agentName | STRING | YES | Agent 的显示名称 | +| agentAddress | STRING | YES | Agent 的钱包地址 | +| expired | LONG | YES | Agent 到期时间戳(毫秒) | +| signatureChainId | LONG | YES | 生成签名时所使用的链 ID(EVM 地址填 `56`,Solana 地址填 `101`) | +| signature | STRING | YES | 对消息体的签名,必须使用用户钱包私钥签名(见下方签名说明) | +| canSpotTrade | BOOLEAN | YES | 是否允许 Agent 下现货订单 | +| canPerpTrade | BOOLEAN | YES | 是否允许 Agent 下永续合约订单 | +| canWithdraw | BOOLEAN | YES | 是否允许 Agent 发起提现 | +| ipWhitelist | STRING | NO | 允许访问的 IP 地址或 CIDR 段列表,以**空格**分隔(如 `192.168.1.1 10.0.0.0/24`)。**当 `canWithdraw` 为 `true` 时必填,不可为空。** | +| agentCode | STRING | NO | Agent 注册邀请码 | + +--- + +### 签名说明 + +使用**用户钱包私钥**对以下消息体签名: + +``` +user={user}&nonce={nonce}&agentName={agentName}&agentAddress={agentAddress}&expired={expired}&signatureChainId={signatureChainId}&canSpotTrade={canSpotTrade}&canPerpTrade={canPerpTrade}&canWithdraw={canWithdraw} +``` + +若传入 `ipWhitelist`,则在消息体末尾追加: + +``` +user={user}&nonce={nonce}&agentName={agentName}&agentAddress={agentAddress}&expired={expired}&signatureChainId={signatureChainId}&canSpotTrade={canSpotTrade}&canPerpTrade={canPerpTrade}&canWithdraw={canWithdraw}&ipWhitelist={ipWhitelist} +``` + +#### 支持的签名算法 + +| 账户类型 | 签名算法 | 编码格式 | +|---|---|---| +| EVM 地址 | EIP-712 Typed Data(chainId=56,message.msg=消息体) | Hex | +| Solana 地址 | Ed25519 | Base58 | + +--- + +### 注意事项 + +* `nonce` 必须为微秒精度时间戳,与服务器时间差不得超过 **10 秒**,且同一 nonce 不可重复使用。 +* `expired` 为 Agent 的有效期截止时间,单位为**毫秒**,超时后 Agent 将自动失效。 +* `ipWhitelist` 以**空格**作为分隔符,支持 CIDR 格式(如 `192.168.1.1 10.0.0.0/24`)。**当 `canWithdraw` 为 `true` 时,`ipWhitelist` 必填且不可为空。** +* 本接口**无需鉴权**——无需传入 API Key 或 HMAC 请求头,所有授权均通过链上 `signature` 验证。 +* 本接口将 Agent 注册与权限授予合并为单次调用,等同于独立注册接口与 `approveAgent` 接口的组合操作。 + + + # Websocket 账户信息推送 diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" index cad2d1f..6e45472 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" @@ -104,6 +104,7 @@ - [子账户划转 (TRADE)](#子账户划转-trade) - [用户资产迁移 (WITHDRAW)](#用户资产迁移-withdraw) - [用户资产迁移历史 (USER_DATA)](#用户资产迁移历史-user_data) + - [注册并授权 Agent (PUBLIC)](#注册并授权-agent-public) - [Websocket 账户信息推送](#websocket-账户信息推送) - [生成listenKey (USER_STREAM)](#生成listenkey-user_stream) - [延长listenKey有效期 (USER_STREAM)](#延长listenkey有效期-user_stream) @@ -4252,6 +4253,93 @@ toAccountAddress={toAccountAddress}&asset={asset}&amount={amount}&kindType={kind + +# 注册并授权 Agent (PUBLIC) + +> **响应:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +`POST /fapi/v3/registerAndApproveAgent` + +注册新的 API Agent 账户并一次性授予其交易/提现权限。Agent 授权后,可使用 API Key 在指定权限范围内代表用户进行操作。 + +**权重:** 50 + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| user | STRING | YES | 用户钱包地址 | +| nonce | LONG | YES | 微秒级时间戳,用于防重放攻击 | +| agentName | STRING | YES | Agent 的显示名称 | +| agentAddress | STRING | YES | Agent 的钱包地址 | +| expired | LONG | YES | Agent 到期时间戳(毫秒) | +| signatureChainId | LONG | YES | 生成签名时所使用的链 ID(EVM 地址填 `56`,Solana 地址填 `101`) | +| signature | STRING | YES | 对消息体的签名,必须使用用户钱包私钥签名(见下方签名说明) | +| canSpotTrade | BOOLEAN | YES | 是否允许 Agent 下现货订单 | +| canPerpTrade | BOOLEAN | YES | 是否允许 Agent 下永续合约订单 | +| canWithdraw | BOOLEAN | YES | 是否允许 Agent 发起提现 | +| ipWhitelist | STRING | NO | 允许访问的 IP 地址或 CIDR 段列表,以**空格**分隔(如 `192.168.1.1 10.0.0.0/24`)。**当 `canWithdraw` 为 `true` 时必填,不可为空。** | +| agentCode | STRING | NO | Agent 注册邀请码 | + +--- + +### 签名说明 + +使用**用户钱包私钥**对以下消息体签名: + +``` +msg: user={user}&nonce={nonce}&agentName={agentName}&agentAddress={agentAddress}&expired={expired}&signatureChainId={signatureChainId}&canSpotTrade={canSpotTrade}&canPerpTrade={canPerpTrade}&canWithdraw={canWithdraw} + +typed_data = { + "types": { + "EIP712Domain": [ + {"name": "name", "type": "string"}, + {"name": "version", "type": "string"}, + {"name": "chainId", "type": "uint256"}, + {"name": "verifyingContract", "type": "address"} + ], + "Message": [ + { "name": "msg", "type": "string" } + ] + }, + "primaryType": "Message", + "domain": { + "name": "AsterSignTransaction", + "version": "1", + "chainId": 1666, + "verifyingContract": "0x0000000000000000000000000000000000000000" + }, + "message": { + "msg": "$msg" + } +} +``` + +#### 支持的签名算法 + +| 账户类型 | 签名算法 | 编码格式 | +|---|---|---| +| EVM 地址 | EIP-712 Typed Data(chainId=56,message.msg=消息体) | Hex | +| Solana 地址 | Ed25519 | Base58 | + +--- + +### 注意事项 + +* `nonce` 必须为微秒精度时间戳,与服务器时间差不得超过 **10 秒**,且同一 nonce 不可重复使用。 +* `expired` 为 Agent 的有效期截止时间,单位为**毫秒**,超时后 Agent 将自动失效。 +* `ipWhitelist` 以**空格**作为分隔符,支持 CIDR 格式(如 `192.168.1.1 10.0.0.0/24`)。**当 `canWithdraw` 为 `true` 时,`ipWhitelist` 必填且不可为空。** +* 本接口**无需鉴权**——无需传入 API Key 或 HMAC 请求头,所有授权均通过链上 `signature` 验证。 +* 本接口将 Agent 注册与权限授予合并为单次调用,等同于独立注册接口与 `approveAgent` 接口的组合操作。 + + # Websocket 账户信息推送 From c80b5fdbc14f70fbae220707c8aa6e6ca44a5c4e Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Tue, 12 May 2026 17:45:12 +0800 Subject: [PATCH 110/131] docs: update signature instructions and simplify CHANGELOG - Unify EIP-712 typed_data structure in signature section (all 4 docs) - Always include ipWhitelist in msg, remove conditional two-case format - Simplify CHANGELOG entry Co-Authored-By: Claude Sonnet 4.6 --- CHANGELOG.md | 19 ------------ .../EN/aster-finance-futures-api-testnet.md | 30 +++++++++++++++---- .../EN/aster-finance-futures-api-v3.md | 2 +- .../aster-finance-futures-api-testnet_CN.md" | 30 +++++++++++++++---- .../aster-finance-futures-api-v3_CN.md" | 2 +- 5 files changed, 50 insertions(+), 33 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fef95e4..4c7d277 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,25 +8,6 @@ A new public endpoint that **registers an API agent account and grants trading/withdrawal permissions in a single atomic call**. -新增公开接口,**一次调用完成 Agent 账户注册与权限授予**。 - -**Key details / 要点:** - -- **No authentication required** — authorization is verified through the `signature` parameter (no API Key or HMAC header needed). - **无需鉴权** — 通过请求参数中的 `signature` 验证,无需 API Key 或 HMAC 请求头。 -- `signature` is generated by signing the concatenated request parameters (`key=value&key=value...`) with the user's wallet private key. - `signature` 通过对拼接的请求参数字符串(`key=value&key=value...`)使用用户钱包私钥签名生成。 -- Supports **EVM** (EIP-712 Typed Data, chainId=56) and **Solana** (Ed25519) signing. - 支持 **EVM**(EIP-712 Typed Data,chainId=56)和 **Solana**(Ed25519)签名。 -- Configurable per-agent permissions: `canSpotTrade`, `canPerpTrade`, `canWithdraw`. - 可配置 Agent 权限:`canSpotTrade`、`canPerpTrade`、`canWithdraw`。 -- `ipWhitelist`: space-separated, supports CIDR; **required when `canWithdraw=true`**. - `ipWhitelist`:空格分隔,支持 CIDR;**`canWithdraw=true` 时必填**。 -- Optional referral code: `agentCode`. - 可选邀请码:`agentCode`。 -- Agent validity bounded by `expired` (millisecond timestamp) / Agent 有效期由 `expired`(毫秒时间戳)控制。 -- Rate weight / 权重: **50**. - --- ## 2025-xx-xx diff --git a/V3(Recommended)/EN/aster-finance-futures-api-testnet.md b/V3(Recommended)/EN/aster-finance-futures-api-testnet.md index d72a286..14db4d4 100644 --- a/V3(Recommended)/EN/aster-finance-futures-api-testnet.md +++ b/V3(Recommended)/EN/aster-finance-futures-api-testnet.md @@ -3873,13 +3873,31 @@ Registers a new API agent account and grants it trading/withdrawal permissions i Sign the following message body using the **user's wallet private key**: ``` -user={user}&nonce={nonce}&agentName={agentName}&agentAddress={agentAddress}&expired={expired}&signatureChainId={signatureChainId}&canSpotTrade={canSpotTrade}&canPerpTrade={canPerpTrade}&canWithdraw={canWithdraw} -``` - -If `ipWhitelist` is provided, append it to the message body: +msg: user={user}&nonce={nonce}&agentName={agentName}&agentAddress={agentAddress}&expired={expired}&signatureChainId={signatureChainId}&canSpotTrade={canSpotTrade}&canPerpTrade={canPerpTrade}&canWithdraw={canWithdraw}&ipWhitelist={ipWhitelist} -``` -user={user}&nonce={nonce}&agentName={agentName}&agentAddress={agentAddress}&expired={expired}&signatureChainId={signatureChainId}&canSpotTrade={canSpotTrade}&canPerpTrade={canPerpTrade}&canWithdraw={canWithdraw}&ipWhitelist={ipWhitelist} +typed_data = { + "types": { + "EIP712Domain": [ + {"name": "name", "type": "string"}, + {"name": "version", "type": "string"}, + {"name": "chainId", "type": "uint256"}, + {"name": "verifyingContract", "type": "address"} + ], + "Message": [ + { "name": "msg", "type": "string" } + ] + }, + "primaryType": "Message", + "domain": { + "name": "AsterSignTransaction", + "version": "1", + "chainId": 1666, + "verifyingContract": "0x0000000000000000000000000000000000000000" + }, + "message": { + "msg": "$msg" + } +} ``` #### Supported Signing Algorithms diff --git a/V3(Recommended)/EN/aster-finance-futures-api-v3.md b/V3(Recommended)/EN/aster-finance-futures-api-v3.md index f8bed7a..409ec02 100644 --- a/V3(Recommended)/EN/aster-finance-futures-api-v3.md +++ b/V3(Recommended)/EN/aster-finance-futures-api-v3.md @@ -4136,7 +4136,7 @@ Registers a new API agent account and grants it trading/withdrawal permissions i Sign the following message body using the **user's wallet private key**: ``` -msg: user={user}&nonce={nonce}&agentName={agentName}&agentAddress={agentAddress}&expired={expired}&signatureChainId={signatureChainId}&canSpotTrade={canSpotTrade}&canPerpTrade={canPerpTrade}&canWithdraw={canWithdraw} +msg: user={user}&nonce={nonce}&agentName={agentName}&agentAddress={agentAddress}&expired={expired}&signatureChainId={signatureChainId}&canSpotTrade={canSpotTrade}&canPerpTrade={canPerpTrade}&canWithdraw={canWithdraw}&ipWhitelist={ipWhitelist} typed_data = { "types": { diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" index 3c294a7..a4a78de 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" @@ -4105,13 +4105,31 @@ toAccountAddress={toAccountAddress}&asset={asset}&amount={amount}&kindType={kind 使用**用户钱包私钥**对以下消息体签名: ``` -user={user}&nonce={nonce}&agentName={agentName}&agentAddress={agentAddress}&expired={expired}&signatureChainId={signatureChainId}&canSpotTrade={canSpotTrade}&canPerpTrade={canPerpTrade}&canWithdraw={canWithdraw} -``` - -若传入 `ipWhitelist`,则在消息体末尾追加: +msg: user={user}&nonce={nonce}&agentName={agentName}&agentAddress={agentAddress}&expired={expired}&signatureChainId={signatureChainId}&canSpotTrade={canSpotTrade}&canPerpTrade={canPerpTrade}&canWithdraw={canWithdraw}&ipWhitelist={ipWhitelist} -``` -user={user}&nonce={nonce}&agentName={agentName}&agentAddress={agentAddress}&expired={expired}&signatureChainId={signatureChainId}&canSpotTrade={canSpotTrade}&canPerpTrade={canPerpTrade}&canWithdraw={canWithdraw}&ipWhitelist={ipWhitelist} +typed_data = { + "types": { + "EIP712Domain": [ + {"name": "name", "type": "string"}, + {"name": "version", "type": "string"}, + {"name": "chainId", "type": "uint256"}, + {"name": "verifyingContract", "type": "address"} + ], + "Message": [ + { "name": "msg", "type": "string" } + ] + }, + "primaryType": "Message", + "domain": { + "name": "AsterSignTransaction", + "version": "1", + "chainId": 1666, + "verifyingContract": "0x0000000000000000000000000000000000000000" + }, + "message": { + "msg": "$msg" + } +} ``` #### 支持的签名算法 diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" index 6e45472..78f0ac8 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" @@ -4295,7 +4295,7 @@ toAccountAddress={toAccountAddress}&asset={asset}&amount={amount}&kindType={kind 使用**用户钱包私钥**对以下消息体签名: ``` -msg: user={user}&nonce={nonce}&agentName={agentName}&agentAddress={agentAddress}&expired={expired}&signatureChainId={signatureChainId}&canSpotTrade={canSpotTrade}&canPerpTrade={canPerpTrade}&canWithdraw={canWithdraw} +msg: user={user}&nonce={nonce}&agentName={agentName}&agentAddress={agentAddress}&expired={expired}&signatureChainId={signatureChainId}&canSpotTrade={canSpotTrade}&canPerpTrade={canPerpTrade}&canWithdraw={canWithdraw}&ipWhitelist={ipWhitelist} typed_data = { "types": { From cf0cccb387db5df471368987dbd1f434a4a53b26 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Tue, 12 May 2026 17:50:26 +0800 Subject: [PATCH 111/131] docs: clarify typed_data is EVM-only in signature instructions Co-Authored-By: Claude Sonnet 4.6 --- V3(Recommended)/EN/aster-finance-futures-api-testnet.md | 4 ++++ V3(Recommended)/EN/aster-finance-futures-api-v3.md | 4 ++++ .../aster-finance-futures-api-testnet_CN.md" | 4 ++++ .../aster-finance-futures-api-v3_CN.md" | 4 ++++ 4 files changed, 16 insertions(+) diff --git a/V3(Recommended)/EN/aster-finance-futures-api-testnet.md b/V3(Recommended)/EN/aster-finance-futures-api-testnet.md index 14db4d4..025d5f6 100644 --- a/V3(Recommended)/EN/aster-finance-futures-api-testnet.md +++ b/V3(Recommended)/EN/aster-finance-futures-api-testnet.md @@ -3874,7 +3874,11 @@ Sign the following message body using the **user's wallet private key**: ``` msg: user={user}&nonce={nonce}&agentName={agentName}&agentAddress={agentAddress}&expired={expired}&signatureChainId={signatureChainId}&canSpotTrade={canSpotTrade}&canPerpTrade={canPerpTrade}&canWithdraw={canWithdraw}&ipWhitelist={ipWhitelist} +``` + +> **EVM addresses only:** wrap the `msg` string above as `message.msg` in the following EIP-712 typed data structure before signing: +``` typed_data = { "types": { "EIP712Domain": [ diff --git a/V3(Recommended)/EN/aster-finance-futures-api-v3.md b/V3(Recommended)/EN/aster-finance-futures-api-v3.md index 409ec02..f19aca7 100644 --- a/V3(Recommended)/EN/aster-finance-futures-api-v3.md +++ b/V3(Recommended)/EN/aster-finance-futures-api-v3.md @@ -4137,7 +4137,11 @@ Sign the following message body using the **user's wallet private key**: ``` msg: user={user}&nonce={nonce}&agentName={agentName}&agentAddress={agentAddress}&expired={expired}&signatureChainId={signatureChainId}&canSpotTrade={canSpotTrade}&canPerpTrade={canPerpTrade}&canWithdraw={canWithdraw}&ipWhitelist={ipWhitelist} +``` + +> **EVM addresses only:** wrap the `msg` string above as `message.msg` in the following EIP-712 typed data structure before signing: +``` typed_data = { "types": { "EIP712Domain": [ diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" index a4a78de..0fcd477 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" @@ -4106,7 +4106,11 @@ toAccountAddress={toAccountAddress}&asset={asset}&amount={amount}&kindType={kind ``` msg: user={user}&nonce={nonce}&agentName={agentName}&agentAddress={agentAddress}&expired={expired}&signatureChainId={signatureChainId}&canSpotTrade={canSpotTrade}&canPerpTrade={canPerpTrade}&canWithdraw={canWithdraw}&ipWhitelist={ipWhitelist} +``` + +> **EVM 地址专用:** 将上述 `msg` 字符串作为 EIP-712 结构化数据中 `message.msg` 的值进行签名,结构如下: +``` typed_data = { "types": { "EIP712Domain": [ diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" index 78f0ac8..bf31e74 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" @@ -4296,7 +4296,11 @@ toAccountAddress={toAccountAddress}&asset={asset}&amount={amount}&kindType={kind ``` msg: user={user}&nonce={nonce}&agentName={agentName}&agentAddress={agentAddress}&expired={expired}&signatureChainId={signatureChainId}&canSpotTrade={canSpotTrade}&canPerpTrade={canPerpTrade}&canWithdraw={canWithdraw}&ipWhitelist={ipWhitelist} +``` + +> **EVM 地址专用:** 将上述 `msg` 字符串作为 EIP-712 结构化数据中 `message.msg` 的值进行签名,结构如下: +``` typed_data = { "types": { "EIP712Domain": [ From 93922c90abc86ccea2b639a2540375ddb02baa7e Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Tue, 12 May 2026 17:53:23 +0800 Subject: [PATCH 112/131] docs: fix testnet chainId to 714 in EIP-712 domain Co-Authored-By: Claude Sonnet 4.6 --- V3(Recommended)/EN/aster-finance-futures-api-testnet.md | 2 +- .../aster-finance-futures-api-testnet_CN.md" | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/V3(Recommended)/EN/aster-finance-futures-api-testnet.md b/V3(Recommended)/EN/aster-finance-futures-api-testnet.md index 025d5f6..37129fb 100644 --- a/V3(Recommended)/EN/aster-finance-futures-api-testnet.md +++ b/V3(Recommended)/EN/aster-finance-futures-api-testnet.md @@ -3895,7 +3895,7 @@ typed_data = { "domain": { "name": "AsterSignTransaction", "version": "1", - "chainId": 1666, + "chainId": 714, "verifyingContract": "0x0000000000000000000000000000000000000000" }, "message": { diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" index 0fcd477..2254320 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" @@ -4127,7 +4127,7 @@ typed_data = { "domain": { "name": "AsterSignTransaction", "version": "1", - "chainId": 1666, + "chainId": 714, "verifyingContract": "0x0000000000000000000000000000000000000000" }, "message": { From 70bf2fc373708126dfad252d0468e1589d20b972 Mon Sep 17 00:00:00 2001 From: "brad.x" Date: Tue, 19 May 2026 17:08:27 +0800 Subject: [PATCH 113/131] add_chase_order_and_bbo_api --- CHANGELOG.md | 16 ++++ .../EN/aster-finance-futures-api-testnet.md | 76 +++++++++++++++++++ .../EN/aster-finance-futures-api-v3.md | 74 ++++++++++++++++++ .../aster-finance-futures-api-testnet_CN.md" | 76 +++++++++++++++++++ .../aster-finance-futures-api-v3_CN.md" | 74 ++++++++++++++++++ 5 files changed, 316 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c7d277..98e3260 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,21 @@ # Changelog +## 2026-05-19 + +### Added + +#### `POST /fapi/v3/chase` — Place Chase Order / 下追单 + +A new public endpoint that **places a BBO-pegged GTX limit order with automatic price tracking**. The strategy service polls each tick and re-pegs the order to `bid1 − chaseOffset` (BUY) or `ask1 + chaseOffset` (SELL). The chase auto-cancels when the market moves beyond `maxChaseOffset` from the original BBO. Supports `priceLimit`, `quantityUnit` (`BASE` / `QUOTE`), and optional `maxChaseOffset` in `ABSOLUTE` or `PERCENTAGE` units. + +### Changed + +#### `PUT /fapi/v3/order` — Modify Order: clarified BBO-pegged behavior + +Added a note that BBO-pegged orders (placed with `pegPriceType = COUNTERPARTY_1 / QUEUE_1`) cannot have their price re-resolved via plain modify — to continuously track the BBO use a Chase order (`POST /fapi/v3/chase`). + +--- + ## 2026-05-12 ### Added diff --git a/V3(Recommended)/EN/aster-finance-futures-api-testnet.md b/V3(Recommended)/EN/aster-finance-futures-api-testnet.md index 37129fb..4d88579 100644 --- a/V3(Recommended)/EN/aster-finance-futures-api-testnet.md +++ b/V3(Recommended)/EN/aster-finance-futures-api-testnet.md @@ -2190,6 +2190,9 @@ Send in a new order. | workingType | ENUM | NO | stopPrice triggered by: "MARK_PRICE", "CONTRACT_PRICE". Default "CONTRACT_PRICE" | | priceProtect | STRING | NO | "TRUE" or "FALSE", default "FALSE". Used with`STOP/STOP_MARKET` or `TAKE_PROFIT/TAKE_PROFIT_MARKET` orders. | | newOrderRespType | ENUM | NO | "ACK", "RESULT", default "ACK" | +| pegPriceType | ENUM | NO | BBO peg mode: `COUNTERPARTY_1` or `QUEUE_1`. When set on a `LIMIT` order, the engine resolves the actual price from the order book at trigger time using the BBO + `pegOffset`. Defaults to no peg. | +| pegOffset | DECIMAL | NO | Signed offset from BBO when `pegPriceType` is set. BUY orders should use a non-positive value (e.g. `-0.5`); SELL non-negative. Units: same scale as `price` (must be a `tickSize` multiple). | +| priceLimit | DECIMAL | NO | Absolute price cap for BBO-pegged orders. BUY: ceiling — peg never resolves above this; SELL: floor. Must be > 0 and a multiple of `tickSize`. Defaults to no cap. | | recvWindow | LONG | NO | | | timestamp | LONG | YES | | @@ -2290,6 +2293,79 @@ price | DECIMAL | NO | Order price * If the new `quantity` or `price` does not meet `PRICE_FILTER` / `PERCENT_FILTER` / `LOT_SIZE` restrictions, the modification will be rejected and the original order will remain. * Only `LIMIT` order type is supported. * Maximum 10000 modifications per order. +* **BBO-pegged orders** (those placed with `pegPriceType` = `COUNTERPARTY_1` / `QUEUE_1`): the engine resolves the actual price from the order book at trigger time. To auto-track the BBO with a continuously re-pegged limit order, use a **Chase order** (see `POST /fapi/v3/chase` below) which the strategy service amends in real time as the BBO moves. + +## Place Chase Order (TRADE) + +> **Response:** + +```javascript +{ + "strategyId": 12345, + "clientStrategyId": "my_chase_1", + "symbol": "BTCUSDT", + "side": "BUY", + "positionSide": "BOTH", + "quantity": "0.1", + "quantityUnit": "BASE", + "reduceOnly": false, + "chaseOffset": "0.5", + "chaseOffsetType": "ABSOLUTE", + "maxChaseOffset": "10.0", + "maxChaseOffsetType": "ABSOLUTE", + "priceLimit": "50100.00", + "timeInForce": "GTX", + "strategyStatus": "NEW", + "bookTime": 1747728000000, + "updateTime": 1747728000000 +} +``` + +``POST /fapi/v3/chase`` + +Place a **Chase strategy order** — a BBO-pegged GTX limit order that automatically re-pegs to the best bid/ask as the market moves. The strategy service polls the order book each tick and amends the order price in real time to keep the order near the top of the book until it fills or until the market moves beyond `maxChaseOffset` from the original BBO. + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ------------------ | ------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| symbol | STRING | YES | Trading pair. | +| side | ENUM | YES | `BUY` or `SELL`. Missing/blank returns `"Mandatory parameter 'side' was not sent, was empty/null, or malformed."` | +| positionSide | ENUM | NO | Default `BOTH` for One-way Mode; `LONG` or `SHORT` for Hedge Mode. | +| quantityUnit | STRING | YES | `BASE` (qty in base asset, e.g. BTC) or `QUOTE` (qty in quote asset, e.g. USDT). For `QUOTE` orders the system converts to BASE using mark price. | +| quantity | DECIMAL | YES | Order quantity in the unit specified by `quantityUnit`. | +| reduceOnly | STRING | NO | `"true"` or `"false"` (case-insensitive). Any other value is rejected. Default `"false"`. | +| chaseOffset | DECIMAL | NO | Distance from BBO to peg the order. Default `"0"` (exact BBO peg). Must be ≥ 0 and a multiple of `tickSize`. BUY price = `bid1 − chaseOffset`; SELL price = `ask1 + chaseOffset`. | +| chaseOffsetType | STRING | NO | `ABSOLUTE` (default) . only supports `ABSOLUTE` for now. Will support or `PERCENTAGE` latter | +| maxChaseOffset | DECIMAL | NO | Maximum tolerated distance from the original BBO before the chase auto-cancels. Required if `maxChaseOffsetType` is sent. Must be `> 0`. | +| maxChaseOffsetType | STRING | NO | `ABSOLUTE` or `PERCENTAGE` (default `ABSOLUTE` when `maxChaseOffset` is sent). `ABSOLUTE`: same unit as price, must be a multiple of `tickSize`. `PERCENTAGE`: ≤ 2 decimal places. | +| priceLimit | DECIMAL | NO | Absolute price cap. BUY: ceiling — chase never crosses above this; SELL: floor. Must be > 0 and a multiple of `tickSize`. | +| timeInForce | ENUM | NO | Default `GTX` (post-only). **`NO_FILL` is not allowed** and is rejected with `INVALID_TIF`. | +| clientStrategyId | STRING | NO | User-defined strategy id. Auto-generated if not sent. **Length ≤ 28 characters** (DB column is `varchar(28)`). Must match `^[\.A-Z\:/a-z0-9_-]{1,28}$`. | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +**Validation rules:** + +* `side` is mandatory. +* `reduceOnly` accepts only `"true"` / `"false"` (case-insensitive). Any other string returns `INVALID_PARAMETER` with `reduceOnly` as the offending param name. +* `chaseOffset` must be ≥ 0 and a multiple of `tickSize`. +* `chaseOffsetType` / `maxChaseOffsetType` must be `ABSOLUTE` or `PERCENTAGE`; an invalid value returns `INVALID_PARAMETER` (not `INVALID_CHASE_OFFSET`). +* When `maxChaseOffsetType = PERCENTAGE`, the input value must have ≤ 2 decimal places (it is stored at scale 2 on the wire, e.g. `"1"` → 1.00%, `"100"` → 100.00%). +* When `maxChaseOffsetType = ABSOLUTE`, `maxChaseOffset` must be a multiple of `tickSize`. +* `timeInForce` cannot be `NO_FILL`. +* `clientStrategyId` length must be ≤ 28 characters. +* OI cap check: for `quantityUnit = QUOTE`, the gateway converts to BASE quantity for the symbol-leverage OI bracket check using `qtyBase = qtyQuote × 10^quantityDecimal / markPrice`. + +**Behavior:** + +* The initial order is placed as a GTX (post-only) limit with `pegPriceType = QUEUE_1` and signed `pegOffset` (negative for BUY, positive for SELL). +* The strategy service polls every second and amends the order price as the BBO moves, keeping the order at `bid1 − chaseOffset` (BUY) or `ask1 + chaseOffset` (SELL). +* If the market moves beyond `maxChaseOffset` from the original BBO, the chase **auto-cancels** with reason `OFFSET_CANCELLED`. +* If the new peg price would breach `priceLimit`, the chase clamps to `priceLimit` and stops further re-pegs in that direction. +* The chase terminates on FILL, user cancel (via standard `DELETE /fapi/v3/order`), `maxChaseOffset` breach, or `priceLimit` clamp + no further improvement opportunity. ## Place Multiple Orders (TRADE) diff --git a/V3(Recommended)/EN/aster-finance-futures-api-v3.md b/V3(Recommended)/EN/aster-finance-futures-api-v3.md index f19aca7..0489b33 100644 --- a/V3(Recommended)/EN/aster-finance-futures-api-v3.md +++ b/V3(Recommended)/EN/aster-finance-futures-api-v3.md @@ -2405,6 +2405,9 @@ Send in a new order. | workingType | ENUM | NO | stopPrice triggered by: "MARK_PRICE", "CONTRACT_PRICE". Default "CONTRACT_PRICE" | | priceProtect | STRING | NO | "TRUE" or "FALSE", default "FALSE". Used with`STOP/STOP_MARKET` or `TAKE_PROFIT/TAKE_PROFIT_MARKET` orders. | | newOrderRespType | ENUM | NO | "ACK", "RESULT", default "ACK" | +| pegPriceType | ENUM | NO | BBO peg mode: `COUNTERPARTY_1` or `QUEUE_1`. When set on a `LIMIT` order, the engine resolves the actual price from the order book at trigger time using the BBO + `pegOffset`. Defaults to no peg. | +| pegOffset | DECIMAL | NO | Signed offset from BBO when `pegPriceType` is set. BUY orders should use a non-positive value (e.g. `-0.5`); SELL non-negative. Units: same scale as `price` (must be a `tickSize` multiple). | +| priceLimit | DECIMAL | NO | Absolute price cap for BBO-pegged orders. BUY: ceiling — peg never resolves above this; SELL: floor. Must be > 0 and a multiple of `tickSize`. Defaults to no cap. | Additional mandatory parameters based on `type`: @@ -2504,6 +2507,77 @@ price | DECIMAL | NO | Order price * If the new `quantity` or `price` does not meet `PRICE_FILTER` / `PERCENT_FILTER` / `LOT_SIZE` restrictions, the modification will be rejected and the original order will remain. * Only `LIMIT` order type is supported. * Maximum 10000 modifications per order. +* **BBO-pegged orders** (those placed with `pegPriceType` = `COUNTERPARTY_1` / `QUEUE_1`): the engine resolves the actual price from the order book at trigger time. To auto-track the BBO with a continuously re-pegged limit order, use a **Chase order** (see `POST /fapi/v3/chase` below) which the strategy service amends in real time as the BBO moves. + +## Place Chase Order (TRADE) + +> **Response:** + +```javascript +{ + "strategyId": 12345, + "clientStrategyId": "my_chase_1", + "symbol": "BTCUSDT", + "side": "BUY", + "positionSide": "BOTH", + "quantity": "0.1", + "quantityUnit": "BASE", + "reduceOnly": false, + "chaseOffset": "0.5", + "chaseOffsetType": "ABSOLUTE", + "maxChaseOffset": "10.0", + "maxChaseOffsetType": "ABSOLUTE", + "priceLimit": "50100.00", + "timeInForce": "GTX", + "strategyStatus": "NEW", + "bookTime": 1747728000000, + "updateTime": 1747728000000 +} +``` + +``POST /fapi/v3/chase`` + +Place a **Chase strategy order** — a BBO-pegged GTX limit order that automatically re-pegs to the best bid/ask as the market moves. The strategy service polls the order book each tick and amends the order price in real time to keep the order near the top of the book until it fills or until the market moves beyond `maxChaseOffset` from the original BBO. + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +| ------------------ | ------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| symbol | STRING | YES | Trading pair. | +| side | ENUM | YES | `BUY` or `SELL`. Missing/blank returns `"Mandatory parameter 'side' was not sent, was empty/null, or malformed."` | +| positionSide | ENUM | NO | Default `BOTH` for One-way Mode; `LONG` or `SHORT` for Hedge Mode. | +| quantityUnit | STRING | YES | `BASE` (qty in base asset, e.g. BTC) or `QUOTE` (qty in quote asset, e.g. USDT). For `QUOTE` orders the system converts to BASE using mark price. | +| quantity | DECIMAL | YES | Order quantity in the unit specified by `quantityUnit`. | +| reduceOnly | STRING | NO | `"true"` or `"false"` (case-insensitive). Any other value is rejected. Default `"false"`. | +| chaseOffset | DECIMAL | NO | Distance from BBO to peg the order. Default `"0"` (exact BBO peg). Must be ≥ 0 and a multiple of `tickSize`. BUY price = `bid1 − chaseOffset`; SELL price = `ask1 + chaseOffset`. | +| chaseOffsetType | STRING | NO | `ABSOLUTE` (default). only supports `ABSOLUTE` for now. Will support or `PERCENTAGE` latter later. | +| maxChaseOffset | DECIMAL | NO | Maximum tolerated distance from the original BBO before the chase auto-cancels. Required if `maxChaseOffsetType` is sent. Must be `> 0`. | +| maxChaseOffsetType | STRING | NO | `ABSOLUTE` or `PERCENTAGE` (default `ABSOLUTE` when `maxChaseOffset` is sent). `ABSOLUTE`: same unit as price, must be a multiple of `tickSize`. `PERCENTAGE`: ≤ 2 decimal places. | +| priceLimit | DECIMAL | NO | Absolute price cap. BUY: ceiling — chase never crosses above this; SELL: floor. Must be > 0 and a multiple of `tickSize`. | +| timeInForce | ENUM | NO | Default `GTX` (post-only). **`NO_FILL` is not allowed** and is rejected with `INVALID_TIF`. | +| clientStrategyId | STRING | NO | User-defined strategy id. Auto-generated if not sent. **Length ≤ 28 characters** (DB column is `varchar(28)`). Must match `^[\.A-Z\:/a-z0-9_-]{1,28}$`. | + +**Validation rules:** + +* `side` is mandatory. +* `reduceOnly` accepts only `"true"` / `"false"` (case-insensitive). Any other string returns `INVALID_PARAMETER` with `reduceOnly` as the offending param name. +* `chaseOffset` must be ≥ 0 and a multiple of `tickSize`. +* `chaseOffsetType` / `maxChaseOffsetType` must be `ABSOLUTE` or `PERCENTAGE`; an invalid value returns `INVALID_PARAMETER` (not `INVALID_CHASE_OFFSET`). +* When `maxChaseOffsetType = PERCENTAGE`, the input value must have ≤ 2 decimal places (it is stored at scale 2 on the wire, e.g. `"1"` → 1.00%, `"100"` → 100.00%). +* When `maxChaseOffsetType = ABSOLUTE`, `maxChaseOffset` must be a multiple of `tickSize`. +* `timeInForce` cannot be `NO_FILL`. +* `clientStrategyId` length must be ≤ 28 characters. +* OI cap check: for `quantityUnit = QUOTE`, the gateway converts to BASE quantity for the symbol-leverage OI bracket check using `qtyBase = qtyQuote × 10^quantityDecimal / markPrice`. + +**Behavior:** + +* The initial order is placed as a GTX (post-only) limit with `pegPriceType = QUEUE_1` and signed `pegOffset` (negative for BUY, positive for SELL). +* The strategy service polls every second and amends the order price as the BBO moves, keeping the order at `bid1 − chaseOffset` (BUY) or `ask1 + chaseOffset` (SELL). +* If the market moves beyond `maxChaseOffset` from the original BBO, the chase **auto-cancels** with reason `OFFSET_CANCELLED`. +* If the new peg price would breach `priceLimit`, the chase clamps to `priceLimit` and stops further re-pegs in that direction. +* The chase terminates on FILL, user cancel (via standard `DELETE /fapi/v3/order`), `maxChaseOffset` breach, or `priceLimit` clamp + no further improvement opportunity. ## Place Multiple Orders (TRADE) diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" index 2254320..a26b7d8 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" @@ -2359,6 +2359,9 @@ timeInForce | ENUM | NO | 有效方法 workingType | ENUM | NO | stopPrice 触发类型: `MARK_PRICE`(标记价格), `CONTRACT_PRICE`(合约最新价). 默认 `CONTRACT_PRICE` priceProtect | STRING | NO | 条件单触发保护:"TRUE","FALSE", 默认"FALSE". 仅 `STOP`, `STOP_MARKET`, `TAKE_PROFIT`, `TAKE_PROFIT_MARKET` 需要此参数 newOrderRespType | ENUM | NO | "ACK", "RESULT", 默认 "ACK" +pegPriceType | ENUM | NO | BBO peg 模式: `COUNTERPARTY_1` 或 `QUEUE_1`。在 `LIMIT` 订单上设置此参数后,撮合引擎在触发时基于订单簿的 BBO 加 `pegOffset` 解析实际价格。默认不使用 peg。 +pegOffset | DECIMAL | NO | 当 `pegPriceType` 已设置时,相对 BBO 的有符号偏移量。买单应为非正值(如 `-0.5`),卖单为非负值。单位与 `price` 相同,必须是 `tickSize` 的倍数。 +priceLimit | DECIMAL | NO | BBO peg 订单的绝对价格上下限。买单:上限——peg 不会高于此;卖单:下限。必须 > 0 且为 `tickSize` 倍数。默认无限制。 根据 order `type`的不同,某些参数强制要求,具体如下: @@ -2480,6 +2483,79 @@ price | DECIMAL | NO | 委托价格 * 当新订单的quantity 或 price不满足PRICE_FILTER / PERCENT_FILTER / LOT_SIZE限制,修改会被拒绝,原订单依旧被保留 订单只支持limit类型 * 同一订单修改次数最多10000次 +* **BBO peg 订单**(使用 `pegPriceType` = `COUNTERPARTY_1` / `QUEUE_1` 下的订单):撮合引擎在触发时从订单簿解析实际价格。普通 modify 无法改变 peg 解析后的价格。若需要持续追踪 BBO,请使用追单接口 `POST /fapi/v3/chase`。 + +## 追单 (TRADE) + +> **响应:** + +```javascript +{ + "strategyId": 12345, + "clientStrategyId": "my_chase_1", + "symbol": "BTCUSDT", + "side": "BUY", + "positionSide": "BOTH", + "quantity": "0.1", + "quantityUnit": "BASE", + "reduceOnly": false, + "chaseOffset": "0.5", + "chaseOffsetType": "ABSOLUTE", + "maxChaseOffset": "10.0", + "maxChaseOffsetType": "ABSOLUTE", + "priceLimit": "50100.00", + "timeInForce": "GTX", + "strategyStatus": "NEW", + "bookTime": 1747728000000, + "updateTime": 1747728000000 +} +``` + +``POST /fapi/v3/chase`` + +下一笔**追单策略订单** —— BBO peg GTX 限价单,自动跟随最优买/卖价重新挂单。策略服务每个 tick 轮询订单簿,实时修改委托价格,使订单保持在盘口前列,直到成交或市场偏离原始 BBO 超过 `maxChaseOffset`。 + +**权重:** 1 + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +| ------------------ | ------- | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| symbol | STRING | YES | 交易对。 | +| side | ENUM | YES | `BUY` 或 `SELL`。缺失/空值返回 `"Mandatory parameter 'side' was not sent, was empty/null, or malformed."` | +| positionSide | ENUM | NO | 单向持仓模式默认 `BOTH`;双向持仓模式必须传 `LONG` 或 `SHORT`。 | +| quantityUnit | STRING | YES | `BASE`(数量以标的资产计价,如 BTC)或 `QUOTE`(数量以计价资产计价,如 USDT)。`QUOTE` 时系统按 mark price 换算到 BASE。 | +| quantity | DECIMAL | YES | 数量,单位由 `quantityUnit` 决定。 | +| reduceOnly | STRING | NO | `"true"` 或 `"false"`(大小写不敏感)。任何其他值会被拒绝。默认 `"false"`。 | +| chaseOffset | DECIMAL | NO | 距 BBO 的偏移量。默认 `"0"`(完全贴近 BBO)。必须 ≥ 0 且为 `tickSize` 的倍数。买单价 = `bid1 − chaseOffset`;卖单价 = `ask1 + chaseOffset`。 | +| chaseOffsetType | STRING | NO | `ABSOLUTE`(默认)。v1 仅支持 `ABSOLUTE`。`PERCENTAGE` 后续支持。 | +| maxChaseOffset | DECIMAL | NO | 相对原始 BBO 允许偏移的最大距离,超出后追单自动撤销。当 `maxChaseOffsetType` 已传时必填。必须 > 0。 | +| maxChaseOffsetType | STRING | NO | `ABSOLUTE` 或 `PERCENTAGE`(默认 `ABSOLUTE`)。`ABSOLUTE`:同价格单位,必须为 `tickSize` 倍数;`PERCENTAGE`:≤ 2 位小数。 | +| priceLimit | DECIMAL | NO | 绝对价格上下限。买单:上限(追单不会高于此);卖单:下限。必须 > 0 且为 `tickSize` 倍数。 | +| timeInForce | ENUM | NO | 默认 `GTX`(post-only)。**不允许 `NO_FILL`**,否则返回 `INVALID_TIF`。 | +| clientStrategyId | STRING | NO | 用户自定义策略 id。未传则自动生成。**长度 ≤ 28 字符**(DB 字段为 `varchar(28)`)。须满足 `^[\.A-Z\:/a-z0-9_-]{1,28}$`。 | +| recvWindow | LONG | NO | | +| timestamp | LONG | YES | | + +**校验规则:** + +* `side` 必填。 +* `reduceOnly` 仅接受 `"true"` / `"false"`(大小写不敏感)。其他值返回 `INVALID_PARAMETER`,参数名为 `reduceOnly`。 +* `chaseOffset` 必须 ≥ 0 且为 `tickSize` 倍数。 +* `chaseOffsetType` / `maxChaseOffsetType` 必须为 `ABSOLUTE` 或 `PERCENTAGE`;非法值返回 `INVALID_PARAMETER`(不再误用 `INVALID_CHASE_OFFSET`)。 +* `maxChaseOffsetType = PERCENTAGE` 时,输入值小数位数 ≤ 2(线上以 ×100 存储,如 `"1"` → 1.00%,`"100"` → 100.00%)。 +* `maxChaseOffsetType = ABSOLUTE` 时,`maxChaseOffset` 必须为 `tickSize` 倍数。 +* `timeInForce` 不允许 `NO_FILL`。 +* `clientStrategyId` 长度必须 ≤ 28 字符。 +* OI cap 校验:`quantityUnit = QUOTE` 时按 mark price 换算到 BASE 数量进行 symbol-leverage OI 档位校验,公式 `qtyBase = qtyQuote × 10^quantityDecimal / markPrice`。 + +**行为:** + +* 初始订单以 GTX(post-only)LIMIT 形式发出,`pegPriceType = QUEUE_1`、`pegOffset` 取符号(买单为负,卖单为正)。 +* 策略服务每秒轮询,将订单价格修改为 `bid1 − chaseOffset`(买单)或 `ask1 + chaseOffset`(卖单),跟随 BBO 移动。 +* 当市场偏移超过 `maxChaseOffset` 时**自动撤销**,原因为 `OFFSET_CANCELLED`。 +* 新的 peg 价若会突破 `priceLimit`,追单将 clamp 在 `priceLimit` 并在该方向停止继续追价。 +* 追单在以下情形终止:成交、用户撤单(`DELETE /fapi/v3/order`)、`maxChaseOffset` 触发、`priceLimit` clamp 且无新的优化空间。 ## 批量下单 (TRADE) diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" index bf31e74..73f23ab 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" @@ -2444,6 +2444,9 @@ timeInForce | ENUM | NO | 有效方法 workingType | ENUM | NO | stopPrice 触发类型: `MARK_PRICE`(标记价格), `CONTRACT_PRICE`(合约最新价). 默认 `CONTRACT_PRICE` priceProtect | STRING | NO | 条件单触发保护:"TRUE","FALSE", 默认"FALSE". 仅 `STOP`, `STOP_MARKET`, `TAKE_PROFIT`, `TAKE_PROFIT_MARKET` 需要此参数 newOrderRespType | ENUM | NO | "ACK", "RESULT", 默认 "ACK" +pegPriceType | ENUM | NO | BBO peg 模式: `COUNTERPARTY_1` 或 `QUEUE_1`。在 `LIMIT` 订单上设置此参数后,撮合引擎在触发时基于订单簿的 BBO 加 `pegOffset` 解析实际价格。默认不使用 peg。 +pegOffset | DECIMAL | NO | 当 `pegPriceType` 已设置时,相对 BBO 的有符号偏移量。买单应为非正值(如 `-0.5`),卖单为非负值。单位与 `price` 相同,必须是 `tickSize` 的倍数。 +priceLimit | DECIMAL | NO | BBO peg 订单的绝对价格上下限。买单:上限——peg 不会高于此;卖单:下限。必须 > 0 且为 `tickSize` 倍数。默认无限制。 根据 order `type`的不同,某些参数强制要求,具体如下: @@ -2565,6 +2568,77 @@ price | DECIMAL | NO | 委托价格 * 当新订单的quantity 或 price不满足PRICE_FILTER / PERCENT_FILTER / LOT_SIZE限制,修改会被拒绝,原订单依旧被保留 订单只支持limit类型 * 同一订单修改次数最多10000次 +* **BBO peg 订单**(使用 `pegPriceType` = `COUNTERPARTY_1` / `QUEUE_1` 下的订单):撮合引擎在触发时从订单簿解析实际价格。普通 modify 无法改变 peg 解析后的价格。若需要持续追踪 BBO,请使用追单接口 `POST /fapi/v3/chase`。 + +## 追单 (TRADE) + +> **响应:** + +```javascript +{ + "strategyId": 12345, + "clientStrategyId": "my_chase_1", + "symbol": "BTCUSDT", + "side": "BUY", + "positionSide": "BOTH", + "quantity": "0.1", + "quantityUnit": "BASE", + "reduceOnly": false, + "chaseOffset": "0.5", + "chaseOffsetType": "ABSOLUTE", + "maxChaseOffset": "10.0", + "maxChaseOffsetType": "ABSOLUTE", + "priceLimit": "50100.00", + "timeInForce": "GTX", + "strategyStatus": "NEW", + "bookTime": 1747728000000, + "updateTime": 1747728000000 +} +``` + +``POST /fapi/v3/chase`` + +下一笔**追单策略订单** —— BBO peg GTX 限价单,自动跟随最优买/卖价重新挂单。策略服务每个 tick 轮询订单簿,实时修改委托价格,使订单保持在盘口前列,直到成交或市场偏离原始 BBO 超过 `maxChaseOffset`。 + +**权重:** 1 + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +| ------------------ | ------- | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| symbol | STRING | YES | 交易对。 | +| side | ENUM | YES | `BUY` 或 `SELL`。缺失/空值返回 `"Mandatory parameter 'side' was not sent, was empty/null, or malformed."` | +| positionSide | ENUM | NO | 单向持仓模式默认 `BOTH`;双向持仓模式必须传 `LONG` 或 `SHORT`。 | +| quantityUnit | STRING | YES | `BASE`(数量以标的资产计价,如 BTC)或 `QUOTE`(数量以计价资产计价,如 USDT)。`QUOTE` 时系统按 mark price 换算到 BASE。 | +| quantity | DECIMAL | YES | 数量,单位由 `quantityUnit` 决定。 | +| reduceOnly | STRING | NO | `"true"` 或 `"false"`(大小写不敏感)。任何其他值会被拒绝。默认 `"false"`。 | +| chaseOffset | DECIMAL | NO | 距 BBO 的偏移量。默认 `"0"`(完全贴近 BBO)。必须 ≥ 0 且为 `tickSize` 的倍数。买单价 = `bid1 − chaseOffset`;卖单价 = `ask1 + chaseOffset`。 | +| chaseOffsetType | STRING | NO | `ABSOLUTE`(默认)。v1 仅支持 `ABSOLUTE`。`PERCENTAGE` 后续支持。 | +| maxChaseOffset | DECIMAL | NO | 相对原始 BBO 允许偏移的最大距离,超出后追单自动撤销。当 `maxChaseOffsetType` 已传时必填。必须 > 0。 | +| maxChaseOffsetType | STRING | NO | `ABSOLUTE` 或 `PERCENTAGE`(默认 `ABSOLUTE`)。`ABSOLUTE`:同价格单位,必须为 `tickSize` 倍数;`PERCENTAGE`:≤ 2 位小数。 | +| priceLimit | DECIMAL | NO | 绝对价格上下限。买单:上限(追单不会高于此);卖单:下限。必须 > 0 且为 `tickSize` 倍数。 | +| timeInForce | ENUM | NO | 默认 `GTX`(post-only)。**不允许 `NO_FILL`**,否则返回 `INVALID_TIF`。 | +| clientStrategyId | STRING | NO | 用户自定义策略 id。未传则自动生成。**长度 ≤ 28 字符**(DB 字段为 `varchar(28)`)。须满足 `^[\.A-Z\:/a-z0-9_-]{1,28}$`。 | + +**校验规则:** + +* `side` 必填。 +* `reduceOnly` 仅接受 `"true"` / `"false"`(大小写不敏感)。其他值返回 `INVALID_PARAMETER`,参数名为 `reduceOnly`。 +* `chaseOffset` 必须 ≥ 0 且为 `tickSize` 倍数。 +* `chaseOffsetType` / `maxChaseOffsetType` 必须为 `ABSOLUTE` 或 `PERCENTAGE`;非法值返回 `INVALID_PARAMETER`(不再误用 `INVALID_CHASE_OFFSET`)。 +* `maxChaseOffsetType = PERCENTAGE` 时,输入值小数位数 ≤ 2(线上以 ×100 存储,如 `"1"` → 1.00%,`"100"` → 100.00%)。 +* `maxChaseOffsetType = ABSOLUTE` 时,`maxChaseOffset` 必须为 `tickSize` 倍数。 +* `timeInForce` 不允许 `NO_FILL`。 +* `clientStrategyId` 长度必须 ≤ 28 字符。 +* OI cap 校验:`quantityUnit = QUOTE` 时按 mark price 换算到 BASE 数量进行 symbol-leverage OI 档位校验,公式 `qtyBase = qtyQuote × 10^quantityDecimal / markPrice`。 + +**行为:** + +* 初始订单以 GTX(post-only)LIMIT 形式发出,`pegPriceType = QUEUE_1`、`pegOffset` 取符号(买单为负,卖单为正)。 +* 策略服务每秒轮询,将订单价格修改为 `bid1 − chaseOffset`(买单)或 `ask1 + chaseOffset`(卖单),跟随 BBO 移动。 +* 当市场偏移超过 `maxChaseOffset` 时**自动撤销**,原因为 `OFFSET_CANCELLED`。 +* 新的 peg 价若会突破 `priceLimit`,追单将 clamp 在 `priceLimit` 并在该方向停止继续追价。 +* 追单在以下情形终止:成交、用户撤单(`DELETE /fapi/v3/order`)、`maxChaseOffset` 触发、`priceLimit` clamp 且无新的优化空间。 ## 批量下单 (TRADE) From 7d4224488ba441c2ee4604165e9571f95ca34306 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Thu, 21 May 2026 15:12:16 +0800 Subject: [PATCH 114/131] docs: add fapi/v3/stpMode endpoints and stpMode order parameter - Add POST/GET /fapi/v3/stpMode (Change/Get STP Mode) to EN and CN futures docs (v3 + testnet) - Add stpMode TOC entries and ENUM definitions in all four files - Add optional stpMode parameter to POST /fapi/v3/order parameter table - Auth params use nonce/signer/signature consistent with v3 auth - Update CHANGELOG.md Co-Authored-By: Claude Sonnet 4.6 --- CHANGELOG.md | 20 ++++++ .../EN/aster-finance-futures-api-testnet.md | 61 ++++++++++++++++++ .../EN/aster-finance-futures-api-v3.md | 61 ++++++++++++++++++ .../aster-finance-futures-api-testnet_CN.md" | 63 +++++++++++++++++++ .../aster-finance-futures-api-v3_CN.md" | 63 +++++++++++++++++++ 5 files changed, 268 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 98e3260..3a7c367 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,25 @@ # Changelog +## 2026-05-21 + +### Added + +#### `POST /fapi/v3/stpMode` — Change STP Mode / 更改STP模式 + +A new TRADE endpoint that sets the account-level **Self-Trade Prevention (STP) mode** applied to all orders by default. Accepted values: `EXPIRE_TAKER`, `EXPIRE_MAKER`, `EXPIRE_BOTH`. + +#### `GET /fapi/v3/stpMode` — Get Current STP Mode / 查询STP模式 + +A new USER_DATA endpoint that returns the account's current STP mode. + +### Changed + +#### `POST /fapi/v3/order` — New Order: added optional `stpMode` parameter + +Added `stpMode` (ENUM, optional) to the place-order parameter list. When specified, it overrides the account-level STP default for that individual order. + +--- + ## 2026-05-19 ### Added diff --git a/V3(Recommended)/EN/aster-finance-futures-api-testnet.md b/V3(Recommended)/EN/aster-finance-futures-api-testnet.md index 4d88579..b174043 100644 --- a/V3(Recommended)/EN/aster-finance-futures-api-testnet.md +++ b/V3(Recommended)/EN/aster-finance-futures-api-testnet.md @@ -69,6 +69,8 @@ - [Account/Trades Endpoints](#accounttrades-endpoints) - [Change Position Mode(TRADE)](#change-position-modetrade) - [Get Current Position Mode(USER_DATA)](#get-current-position-modeuser_data) + - [Change STP Mode (TRADE)](#change-stp-modetrade) + - [Get Current STP Mode (USER_DATA)](#get-current-stp-modeuser_data) - [Change Multi-Assets Mode (TRADE)](#change-multi-assets-mode-trade) - [Get Current Multi-Assets Mode (USER_DATA)](#get-current-multi-assets-mode-user_data) - [New Order (TRADE)](#new-order--trade) @@ -463,6 +465,12 @@ if __name__ == '__main__': * ACK * RESULT +**STP Mode (stpMode)** + +* EXPIRE_TAKER +* EXPIRE_MAKER +* EXPIRE_BOTH + **Kline/Candlestick chart intervals:** m -> minutes; h -> hours; d -> days; w -> weeks; M -> months @@ -2081,6 +2089,58 @@ Get user's position mode (Hedge Mode or One-way Mode ) on ***EVERY symbol*** | recvWindow | LONG | NO | | | timestamp | LONG | YES | | +## Change STP Mode (TRADE) + +> **Response:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +``POST /fapi/v3/stpMode`` + +Change user's Self-Trade Prevention (STP) mode on ***EVERY symbol*** + +**Weight:** +1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +|------|------|-----------|-------------| +| stpMode | ENUM | YES | `EXPIRE_TAKER`: expire taker order; `EXPIRE_MAKER`: expire maker order; `EXPIRE_BOTH`: expire both maker and taker orders | +| nonce | LONG | YES | Microsecond-level timestamp | +| signer | STRING | YES | API wallet address | +| signature | STRING | YES | Signature | + +## Get Current STP Mode (USER_DATA) + +> **Response:** + +```javascript +{ + "stpMode": "EXPIRE_TAKER" // Current STP mode +} +``` + +``GET /fapi/v3/stpMode`` + +Get user's current Self-Trade Prevention (STP) mode on ***EVERY symbol*** + +**Weight:** +30 + +**Parameters:** + +| Name | Type | Mandatory | Description | +|------|------|-----------|-------------| +| nonce | LONG | YES | Microsecond-level timestamp | +| signer | STRING | YES | API wallet address | +| signature | STRING | YES | Signature | + ## Change Multi-Assets Mode (TRADE) > **Response:** @@ -2193,6 +2253,7 @@ Send in a new order. | pegPriceType | ENUM | NO | BBO peg mode: `COUNTERPARTY_1` or `QUEUE_1`. When set on a `LIMIT` order, the engine resolves the actual price from the order book at trigger time using the BBO + `pegOffset`. Defaults to no peg. | | pegOffset | DECIMAL | NO | Signed offset from BBO when `pegPriceType` is set. BUY orders should use a non-positive value (e.g. `-0.5`); SELL non-negative. Units: same scale as `price` (must be a `tickSize` multiple). | | priceLimit | DECIMAL | NO | Absolute price cap for BBO-pegged orders. BUY: ceiling — peg never resolves above this; SELL: floor. Must be > 0 and a multiple of `tickSize`. Defaults to no cap. | +| stpMode | ENUM | NO | Self-Trade Prevention mode for this order. Overrides the account-level default. `EXPIRE_TAKER`: cancel the taker side; `EXPIRE_MAKER`: cancel the maker side; `EXPIRE_BOTH`: cancel both sides. | | recvWindow | LONG | NO | | | timestamp | LONG | YES | | diff --git a/V3(Recommended)/EN/aster-finance-futures-api-v3.md b/V3(Recommended)/EN/aster-finance-futures-api-v3.md index 0489b33..ed0f51d 100644 --- a/V3(Recommended)/EN/aster-finance-futures-api-v3.md +++ b/V3(Recommended)/EN/aster-finance-futures-api-v3.md @@ -68,6 +68,8 @@ - [Account/Trades Endpoints](#accounttrades-endpoints) - [Change Position Mode(TRADE)](#change-position-modetrade) - [Get Current Position Mode(USER_DATA)](#get-current-position-modeuser_data) + - [Change STP Mode (TRADE)](#change-stp-modetrade) + - [Get Current STP Mode (USER_DATA)](#get-current-stp-modeuser_data) - [Change Multi-Assets Mode (TRADE)](#change-multi-assets-mode-trade) - [Get Current Multi-Assets Mode (USER_DATA)](#get-current-multi-assets-mode-user_data) - [New Order (TRADE)](#new-order--trade) @@ -468,6 +470,12 @@ if __name__ == '__main__': * ACK * RESULT +**STP Mode (stpMode)** + +* EXPIRE_TAKER +* EXPIRE_MAKER +* EXPIRE_BOTH + **Kline/Candlestick chart intervals:** m -> minutes; h -> hours; d -> days; w -> weeks; M -> months @@ -2300,6 +2308,58 @@ Get user's position mode (Hedge Mode or One-way Mode ) on ***EVERY symbol*** | Name | Type | Mandatory | Description | | ---------- | ---- | --------- | ----------- | +## Change STP Mode (TRADE) + +> **Response:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +``POST /fapi/v3/stpMode`` + +Change user's Self-Trade Prevention (STP) mode on ***EVERY symbol*** + +**Weight:** +1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +|------|------|-----------|-------------| +| stpMode | ENUM | YES | `EXPIRE_TAKER`: expire taker order; `EXPIRE_MAKER`: expire maker order; `EXPIRE_BOTH`: expire both maker and taker orders | +| nonce | LONG | YES | Microsecond-level timestamp | +| signer | STRING | YES | API wallet address | +| signature | STRING | YES | Signature | + +## Get Current STP Mode (USER_DATA) + +> **Response:** + +```javascript +{ + "stpMode": "EXPIRE_TAKER" // Current STP mode +} +``` + +``GET /fapi/v3/stpMode`` + +Get user's current Self-Trade Prevention (STP) mode on ***EVERY symbol*** + +**Weight:** +30 + +**Parameters:** + +| Name | Type | Mandatory | Description | +|------|------|-----------|-------------| +| nonce | LONG | YES | Microsecond-level timestamp | +| signer | STRING | YES | API wallet address | +| signature | STRING | YES | Signature | + ## Change Multi-Assets Mode (TRADE) > **Response:** @@ -2408,6 +2468,7 @@ Send in a new order. | pegPriceType | ENUM | NO | BBO peg mode: `COUNTERPARTY_1` or `QUEUE_1`. When set on a `LIMIT` order, the engine resolves the actual price from the order book at trigger time using the BBO + `pegOffset`. Defaults to no peg. | | pegOffset | DECIMAL | NO | Signed offset from BBO when `pegPriceType` is set. BUY orders should use a non-positive value (e.g. `-0.5`); SELL non-negative. Units: same scale as `price` (must be a `tickSize` multiple). | | priceLimit | DECIMAL | NO | Absolute price cap for BBO-pegged orders. BUY: ceiling — peg never resolves above this; SELL: floor. Must be > 0 and a multiple of `tickSize`. Defaults to no cap. | +| stpMode | ENUM | NO | Self-Trade Prevention mode for this order. Overrides the account-level default. `EXPIRE_TAKER`: cancel the taker side; `EXPIRE_MAKER`: cancel the maker side; `EXPIRE_BOTH`: cancel both sides. | Additional mandatory parameters based on `type`: diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" index a26b7d8..7eae78b 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-testnet_CN.md" @@ -63,6 +63,8 @@ - [账户和交易接口](#账户和交易接口) - [更改持仓模式(TRADE)](#更改持仓模式trade) - [查询持仓模式(USER_DATA)](#查询持仓模式user_data) + - [更改STP模式(TRADE)](#更改stp模式trade) + - [查询STP模式(USER_DATA)](#查询stp模式user_data) - [更改联合保证金模式(TRADE)](#更改联合保证金模式trade) - [查询联合保证金模式(USER_DATA)](#查询联合保证金模式user_data) - [下单 (TRADE)](#下单-trade) @@ -447,6 +449,12 @@ if __name__ == '__main__': * ACK * RESULT +**自成交防止模式 (stpMode)** + +* EXPIRE_TAKER 撤销taker订单 +* EXPIRE_MAKER 撤销maker订单 +* EXPIRE_BOTH 同时撤销双方订单 + **K线间隔:** m -> 分钟; h -> 小时; d -> 天; w -> 周; M -> 月 @@ -2249,6 +2257,60 @@ GET /fapi/v3/positionSide/dual`` **权重:** 30 +## 更改STP模式(TRADE) + +> **响应:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +`` +POST /fapi/v3/stpMode`` + +变换用户在 ***所有symbol*** 合约上的STP(自成交防止)模式。 + +**权重:** +1 + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| stpMode | ENUM | YES | `EXPIRE_TAKER`: 撤销taker订单;`EXPIRE_MAKER`: 撤销maker订单;`EXPIRE_BOTH`: 同时撤销双方订单 | +| nonce | LONG | YES | 微秒级时间戳 | +| signer | STRING | YES | API钱包地址 | +| signature | STRING | YES | 签名 | + +## 查询STP模式(USER_DATA) + +> **响应:** + +```javascript +{ + "stpMode": "EXPIRE_TAKER" // 当前STP模式 +} +``` + +`` +GET /fapi/v3/stpMode`` + +查询用户目前在 ***所有symbol*** 合约上的STP(自成交防止)模式。 + +**权重:** +30 + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| nonce | LONG | YES | 微秒级时间戳 | +| signer | STRING | YES | API钱包地址 | +| signature | STRING | YES | 签名 | + ## 更改联合保证金模式(TRADE) > **响应:** @@ -2362,6 +2424,7 @@ newOrderRespType | ENUM | NO | "ACK", "RESULT", 默认 "ACK" pegPriceType | ENUM | NO | BBO peg 模式: `COUNTERPARTY_1` 或 `QUEUE_1`。在 `LIMIT` 订单上设置此参数后,撮合引擎在触发时基于订单簿的 BBO 加 `pegOffset` 解析实际价格。默认不使用 peg。 pegOffset | DECIMAL | NO | 当 `pegPriceType` 已设置时,相对 BBO 的有符号偏移量。买单应为非正值(如 `-0.5`),卖单为非负值。单位与 `price` 相同,必须是 `tickSize` 的倍数。 priceLimit | DECIMAL | NO | BBO peg 订单的绝对价格上下限。买单:上限——peg 不会高于此;卖单:下限。必须 > 0 且为 `tickSize` 倍数。默认无限制。 +stpMode | ENUM | NO | 本订单的自成交防止(STP)模式,覆盖账户级默认设置。`EXPIRE_TAKER`:撤销taker订单;`EXPIRE_MAKER`:撤销maker订单;`EXPIRE_BOTH`:同时撤销双方订单。 根据 order `type`的不同,某些参数强制要求,具体如下: diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" index 73f23ab..b6f2e1e 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" @@ -66,6 +66,8 @@ - [账户和交易接口](#账户和交易接口) - [更改持仓模式(TRADE)](#更改持仓模式trade) - [查询持仓模式(USER_DATA)](#查询持仓模式user_data) + - [更改STP模式(TRADE)](#更改stp模式trade) + - [查询STP模式(USER_DATA)](#查询stp模式user_data) - [更改联合保证金模式(TRADE)](#更改联合保证金模式trade) - [查询联合保证金模式(USER_DATA)](#查询联合保证金模式user_data) - [下单 (TRADE)](#下单-trade) @@ -455,6 +457,12 @@ if __name__ == '__main__': * ACK * RESULT +**自成交防止模式 (stpMode)** + +* EXPIRE_TAKER 撤销taker订单 +* EXPIRE_MAKER 撤销maker订单 +* EXPIRE_BOTH 同时撤销双方订单 + **K线间隔:** m -> 分钟; h -> 小时; d -> 天; w -> 周; M -> 月 @@ -2334,6 +2342,60 @@ GET /fapi/v3/positionSide/dual`` **权重:** 30 +## 更改STP模式(TRADE) + +> **响应:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +`` +POST /fapi/v3/stpMode`` + +变换用户在 ***所有symbol*** 合约上的STP(自成交防止)模式。 + +**权重:** +1 + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| stpMode | ENUM | YES | `EXPIRE_TAKER`: 撤销taker订单;`EXPIRE_MAKER`: 撤销maker订单;`EXPIRE_BOTH`: 同时撤销双方订单 | +| nonce | LONG | YES | 微秒级时间戳 | +| signer | STRING | YES | API钱包地址 | +| signature | STRING | YES | 签名 | + +## 查询STP模式(USER_DATA) + +> **响应:** + +```javascript +{ + "stpMode": "EXPIRE_TAKER" // 当前STP模式 +} +``` + +`` +GET /fapi/v3/stpMode`` + +查询用户目前在 ***所有symbol*** 合约上的STP(自成交防止)模式。 + +**权重:** +30 + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| nonce | LONG | YES | 微秒级时间戳 | +| signer | STRING | YES | API钱包地址 | +| signature | STRING | YES | 签名 | + ## 更改联合保证金模式(TRADE) > **响应:** @@ -2447,6 +2509,7 @@ newOrderRespType | ENUM | NO | "ACK", "RESULT", 默认 "ACK" pegPriceType | ENUM | NO | BBO peg 模式: `COUNTERPARTY_1` 或 `QUEUE_1`。在 `LIMIT` 订单上设置此参数后,撮合引擎在触发时基于订单簿的 BBO 加 `pegOffset` 解析实际价格。默认不使用 peg。 pegOffset | DECIMAL | NO | 当 `pegPriceType` 已设置时,相对 BBO 的有符号偏移量。买单应为非正值(如 `-0.5`),卖单为非负值。单位与 `price` 相同,必须是 `tickSize` 的倍数。 priceLimit | DECIMAL | NO | BBO peg 订单的绝对价格上下限。买单:上限——peg 不会高于此;卖单:下限。必须 > 0 且为 `tickSize` 倍数。默认无限制。 +stpMode | ENUM | NO | 本订单的自成交防止(STP)模式,覆盖账户级默认设置。`EXPIRE_TAKER`:撤销taker订单;`EXPIRE_MAKER`:撤销maker订单;`EXPIRE_BOTH`:同时撤销双方订单。 根据 order `type`的不同,某些参数强制要求,具体如下: From b1a96ff90fad1147a0f7751ae9c08bd802b7ca3c Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Wed, 20 May 2026 16:52:22 +0800 Subject: [PATCH 115/131] strategy_api --- CHANGELOG.md | 15 ++ V3(Recommended)/EN/aster-chain.md | 58 ++++ .../EN/aster-finance-futures-api-v3.md | 254 ++++++++++++++++++ .../aster-chain_CN.md" | 58 ++++ .../aster-finance-futures-api-v3_CN.md" | 254 ++++++++++++++++++ 5 files changed, 639 insertions(+) create mode 100644 V3(Recommended)/EN/aster-chain.md create mode 100644 "V3(Recommended)/\344\270\255\346\226\207/aster-chain_CN.md" diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a7c367..3ce9a46 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,21 @@ Added `stpMode` (ENUM, optional) to the place-order parameter list. When specifi --- +## 2026-05-20 + +### Added + +#### Strategy Order APIs / 策略订单接口 + +- `POST /fapi/v3/placeStrategyOrder` — Place Strategy Order / 策略下单 +- `POST /fapi/v3/updateStrategyOrder` — Update Strategy Order / 更新策略订单 +- `GET /fapi/v3/strategyOrder` — Query Strategy Open Order / 查询策略当前挂单 +- `GET /fapi/v3/strategyOrder/history` — Query Strategy History Order / 查询策略历史订单 + +Supports OTO, OCO, and OTOCO strategy types. + +--- + ## 2026-05-19 ### Added diff --git a/V3(Recommended)/EN/aster-chain.md b/V3(Recommended)/EN/aster-chain.md new file mode 100644 index 0000000..e9b9fef --- /dev/null +++ b/V3(Recommended)/EN/aster-chain.md @@ -0,0 +1,58 @@ +# Aster-Chain API Overview + +* This document lists the base URL for the API endpoints: **https://chainapi.asterdex.com** +* All API responses are in JSON format. + +--- + +- [Aster-Chain Account Endpoints](#aster-chain-account-endpoints) + - [Get Account Status (USER_DATA)](#get-account-status-user_data) + - [Modify Account Status (TRADE)](#modify-account-status-trade) + +--- + +# Aster-Chain Account Endpoints + +## Get Account Status (USER_DATA) + +> **Response:** + +```javascript +{ + "status": "PRIVATE" // "PUBLIC" or "PRIVATE" +} +``` + +`GET /aster-chain/v3/account/status` + +Get the current account's privacy status. + +**Weight:** 1 + +**Parameters:** + +None + +--- + +## Modify Account Status (TRADE) + +> **Response:** + +```javascript +{ + "status": "PRIVATE" // "PUBLIC" or "PRIVATE" +} +``` + +`POST /aster-chain/v3/account/modify-status` + +Modify the account's privacy status. After a successful update, the change is broadcast to the Aster Chain. + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Mandatory | Description | +|------|------|-----------|-------------| +| status | STRING | YES | Account privacy mode: `"PUBLIC"` or `"PRIVATE"` | diff --git a/V3(Recommended)/EN/aster-finance-futures-api-v3.md b/V3(Recommended)/EN/aster-finance-futures-api-v3.md index ed0f51d..69abc01 100644 --- a/V3(Recommended)/EN/aster-finance-futures-api-v3.md +++ b/V3(Recommended)/EN/aster-finance-futures-api-v3.md @@ -101,6 +101,10 @@ - [Get User MMP (USER_DATA)](#get-user-mmp-user_data) - [Delete User MMP (USER_DATA)](#delete-user-mmp-user_data) - [Reset User MMP (USER_DATA)](#reset-user-mmp-user_data) + - [Place Strategy Order (TRADE)](#place-strategy-order-trade) + - [Update Strategy Order (TRADE)](#update-strategy-order-trade) + - [Query Strategy Open Order (USER_DATA)](#query-strategy-open-order-user_data) + - [Query Strategy History Order (USER_DATA)](#query-strategy-history-order-user_data) - [Bind Sub-Account (USER_DATA)](#bind-sub-account-user_data) - [Create Sub-Account (TRADE)](#create-sub-account-trade) - [Get Sub-Account List (USER_DATA)](#get-sub-account-list-user_data) @@ -3811,6 +3815,256 @@ true | symbol | STRING | YES | | +## Place Strategy Order (TRADE) + +> **Response:** + +```javascript +{ + "strategyId": 123456789, + "clientStrategyId": "myStrategy1", + "strategyType": "OTO", + "strategyStatus": "WORKING", + "updateTime": 1699900000000, + "failureCode": 0, + "failureReason": "" +} +``` + +`POST /fapi/v3/placeStrategyOrder` + +Place a new strategy order. Supports OTO (One-Triggers-the-Other), OCO (One-Cancels-the-Other), and OTOCO (One-Triggers-One-Cancels-the-Other) strategy types. + +**Weight:** 50 + +**Parameters:** + +| Name | Type | Mandatory | Description | +|------|------|-----------|-------------| +| clientStrategyId | STRING | NO | Client-assigned unique strategy ID | +| strategyType | ENUM | YES | Strategy type: `OTO`, `OCO`, `OTOCO` | +| subOrderList | JSON Array | YES | List of sub-orders. `OTO` and `OCO` require exactly 2; `OTOCO` requires exactly 3 | + +**Sub-order fields (each element in `subOrderList`):** + +| Name | Type | Mandatory | Description | +|------|------|-----------|-------------| +| strategySubId | STRING | YES | Sub-order sequence number starting from 1, must be sequential and match position in array | +| securityType | STRING | YES | Security type of the order | +| symbol | STRING | YES | Trading pair | +| side | STRING | YES | `BUY` or `SELL` | +| positionSide | STRING | NO | `BOTH`, `LONG`, `SHORT`. Default `BOTH` in one-way mode | +| type | STRING | YES | `LIMIT`, `MARKET`, `STOP`, `STOP_MARKET`, `TAKE_PROFIT`, `TAKE_PROFIT_MARKET`, `TRAILING_STOP_MARKET` | +| quantity | STRING | YES* | Order quantity. Not required when `closePosition=true` | +| price | STRING | YES* | Required for `LIMIT`, `STOP`, `TAKE_PROFIT` | +| stopPrice | STRING | YES* | Required for `STOP`, `STOP_MARKET`, `TAKE_PROFIT`, `TAKE_PROFIT_MARKET` | +| timeInForce | STRING | YES* | Required for `LIMIT`; optional for stop orders (default `GTC`). `IOC` and `FOK` are not supported | +| workingType | STRING | NO | `CONTRACT_PRICE` or `MARK_PRICE`. Default `CONTRACT_PRICE` | +| reduceOnly | STRING | NO | Reduce-only flag | +| closePosition | STRING | NO | Close-position flag | +| priceProtect | STRING | NO | Price protection flag | +| clientOrderId | STRING | NO | Client-assigned order ID | +| activationPrice | STRING | NO | Activation price for `TRAILING_STOP_MARKET` | +| callbackRate | STRING | NO | Callback rate for `TRAILING_STOP_MARKET` | +| firstDrivenId | STRING | NO | `strategySubId` of the driving sub-order for the first trigger condition | +| firstDrivenOn | STRING | NO | Event type that activates the first trigger | +| firstTrigger | STRING | NO | First trigger action | +| secondDrivenId | STRING | NO | `strategySubId` of the driving sub-order for the second trigger condition | +| secondDrivenOn | STRING | NO | Event type that activates the second trigger | +| secondTrigger | STRING | NO | Second trigger action | + +--- + +## Update Strategy Order (TRADE) + +> **Response:** + +```javascript +[ + { + "strategyId": 123456789, + "clientStrategyId": "myStrategy1", + "strategyType": "OTO", + "strategyStatus": "WORKING", + "updatedSubOrder": 1, + "updateStatus": "SUCCESS", + "updateTime": 1699900000000, + "failureCode": 0, + "failureReason": "" + } +] +``` + +`POST /fapi/v3/updateStrategyOrder` + +Update one or more sub-orders of an existing strategy order. Returns an array with one result per updated sub-order. + +**Weight:** 50 + +**Parameters:** + +| Name | Type | Mandatory | Description | +|------|------|-----------|-------------| +| strategyId | LONG | YES | Strategy order ID to update | +| strategyType | ENUM | YES | Strategy type: `OTO`, `OCO`, `OTOCO` | +| subOrderList | JSON Array | YES | Sub-orders to update. Max 2 items for `OTO`/`OCO`, max 3 for `OTOCO` | + +**Sub-order fields (each element in `subOrderList`):** + +| Name | Type | Mandatory | Description | +|------|------|-----------|-------------| +| strategySubId | STRING | YES | Sequence number of the sub-order to update | +| securityType | STRING | YES | Security type | +| symbol | STRING | YES | Trading pair | +| side | STRING | YES | `BUY` or `SELL` | +| positionSide | STRING | NO | `BOTH`, `LONG`, `SHORT` | +| type | STRING | YES | Order type | +| quantity | STRING | NO | New order quantity | +| price | STRING | NO | New price (applicable for `LIMIT`, `STOP`, `TAKE_PROFIT`) | +| stopPrice | STRING | NO | New stop price | +| timeInForce | STRING | NO | New time in force | +| workingType | STRING | NO | New working type | +| reduceOnly | STRING | NO | | +| closePosition | STRING | NO | | +| priceProtect | STRING | NO | | +| activationPrice | STRING | NO | For `TRAILING_STOP_MARKET` only | +| callbackRate | STRING | NO | For `TRAILING_STOP_MARKET` only | + +--- + +## Query Strategy Open Order (USER_DATA) + +> **Response:** + +```javascript +{ + "strategyId": 123456789, + "clientStrategyId": "myStrategy1", + "strategyType": "OTO", + "strategyStatus": "WORKING", + "bookTime": 1699900000000, + "updateTime": 1699900001000, + "subOrders": [ + { + "strategyId": 123456789, + "orderId": 987654321, + "clientOrderId": "myOrder1", + "status": "NEW", + "strategySubId": 1, + "firstDrivenId": 0, + "firstDrivenOn": "", + "firstTrigger": "", + "secondDrivenId": 0, + "secondDrivenOn": "", + "secondTrigger": "", + "securityType": "FUTURE", + "symbol": "BTCUSDT", + "side": "BUY", + "positionSide": "LONG", + "type": "LIMIT", + "timeInForce": "GTC", + "quantity": "0.001", + "reduceOnly": false, + "closePosition": false, + "price": "50000", + "avgPrice": "0", + "priceProtect": false, + "stopPrice": "0", + "activatePrice": null, + "callbackRate": null, + "workingType": "CONTRACT_PRICE", + "triggerTime": 0 + } + ] +} +``` + +`GET /fapi/v3/strategyOpenOrder` + +Query a current open strategy order. Either `strategyId` or `clientStrategyId` must be provided, but not both. + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Mandatory | Description | +|------|------|-----------|-------------| +| strategyId | LONG | NO* | Strategy order ID | +| clientStrategyId | STRING | NO* | Client-assigned strategy ID | +| strategyType | STRING | YES | Strategy type: `OTO`, `OCO`, `OTOCO` | + +*Either `strategyId` or `clientStrategyId` must be provided (mutually exclusive). + +--- + +## Query Strategy History Order (USER_DATA) + +> **Response:** + +```javascript +{ + "strategyId": 123456789, + "clientStrategyId": "myStrategy1", + "strategyType": "OTO", + "strategyStatus": "EXPIRED", + "bookTime": 1699800000000, + "updateTime": 1699800060000, + "subOrders": [ + { + "strategyId": 123456789, + "orderId": 987654321, + "clientOrderId": "myOrder1", + "status": "FILLED", + "strategySubId": 1, + "firstDrivenId": 0, + "firstDrivenOn": "", + "firstTrigger": "", + "secondDrivenId": 0, + "secondDrivenOn": "", + "secondTrigger": "", + "securityType": "FUTURE", + "symbol": "BTCUSDT", + "side": "BUY", + "positionSide": "LONG", + "type": "LIMIT", + "timeInForce": "GTC", + "quantity": "0.001", + "reduceOnly": false, + "closePosition": false, + "price": "50000", + "avgPrice": "50000", + "priceProtect": false, + "stopPrice": "0", + "activatePrice": null, + "callbackRate": null, + "workingType": "CONTRACT_PRICE", + "triggerTime": 1699800030000 + } + ] +} +``` + +`GET /fapi/v3/strategyHistoryOrder` + +Query historical strategy orders. Either `strategyId` or `clientStrategyId` must be provided, but not both. Maximum lookback window is 90 days. + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Mandatory | Description | +|------|------|-----------|-------------| +| strategyId | LONG | NO* | Strategy order ID | +| clientStrategyId | STRING | NO* | Client-assigned strategy ID | +| strategyType | STRING | YES | Strategy type: `OTO`, `OCO`, `OTOCO` | +| startTime | LONG | NO | Start time in milliseconds. Data older than 90 days cannot be queried | +| endTime | LONG | NO | End time in milliseconds | +| limit | INT | NO | Number of results returned. Default 500; max 1000 | + +*Either `strategyId` or `clientStrategyId` must be provided (mutually exclusive). + +--- + # Bind Sub-Account (USER_DATA) > **Response:** diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-chain_CN.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-chain_CN.md" new file mode 100644 index 0000000..52e013c --- /dev/null +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-chain_CN.md" @@ -0,0 +1,58 @@ +# Aster-Chain API 概览 + +* 本文档所列接口的 Base URL 为:**https://chainapi.asterdex.com** +* 所有接口响应均为 JSON 格式。 + +--- + +- [Aster-Chain 账户接口](#aster-chain-账户接口) + - [查询账户状态 (USER_DATA)](#查询账户状态-user_data) + - [修改账户状态 (TRADE)](#修改账户状态-trade) + +--- + +# Aster-Chain 账户接口 + +## 查询账户状态 (USER_DATA) + +> **响应:** + +```javascript +{ + "status": "PRIVATE" // "PUBLIC" 或 "PRIVATE" +} +``` + +`GET /aster-chain/v3/account/status` + +查询当前账户的隐私状态。 + +**权重:** 1 + +**参数:** + +无 + +--- + +## 修改账户状态 (TRADE) + +> **响应:** + +```javascript +{ + "status": "PRIVATE" // "PUBLIC" 或 "PRIVATE" +} +``` + +`POST /aster-chain/v3/account/modify-status` + +修改账户隐私状态。更新成功后,变更将广播至 Aster Chain。 + +**权重:** 5 + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| status | STRING | YES | 账户隐私模式:`"PUBLIC"` 或 `"PRIVATE"` | diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" index b6f2e1e..886dca4 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-futures-api-v3_CN.md" @@ -99,6 +99,10 @@ - [获取用户MMP (USER_DATA)](#获取用户mmp-user_data) - [删除用户MMP (USER_DATA)](#删除用户mmp-user_data) - [重置用户MMP (USER_DATA)](#重置用户mmp-user_data) + - [策略下单 (TRADE)](#策略下单-trade) + - [更新策略订单 (TRADE)](#更新策略订单-trade) + - [查询策略当前挂单 (USER_DATA)](#查询策略当前挂单-user_data) + - [查询策略历史订单 (USER_DATA)](#查询策略历史订单-user_data) - [绑定子账户 (USER_DATA)](#绑定子账户-user_data) - [创建子账户 (TRADE)](#创建子账户-trade) - [查询子账户列表 (USER_DATA)](#查询子账户列表-user_data) @@ -3963,6 +3967,256 @@ POST /fapi/v3/mmpReset`` ------------ | ------------ | ------------ | ------------ symbol | STRING | YES +## 策略下单 (TRADE) + +> **响应:** + +```javascript +{ + "strategyId": 123456789, + "clientStrategyId": "myStrategy1", + "strategyType": "OTO", + "strategyStatus": "WORKING", + "updateTime": 1699900000000, + "failureCode": 0, + "failureReason": "" +} +``` + +`POST /fapi/v3/placeStrategyOrder` + +下策略订单。支持 OTO(一单触发另一单)、OCO(一单取消另一单)、OTOCO(一单触发并取消另外两单)三种策略类型。 + +**权重:** 50 + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| clientStrategyId | STRING | NO | 客户端自定义策略 ID | +| strategyType | ENUM | YES | 策略类型:`OTO`、`OCO`、`OTOCO` | +| subOrderList | JSON Array | YES | 子订单列表。`OTO` 和 `OCO` 恰好需要 2 个子订单;`OTOCO` 恰好需要 3 个 | + +**`subOrderList` 中每个子订单的字段:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| strategySubId | STRING | YES | 子订单序号,从 1 开始,必须与数组位置保持一致 | +| securityType | STRING | YES | 订单的资产类型 | +| symbol | STRING | YES | 交易对 | +| side | STRING | YES | `BUY` 或 `SELL` | +| positionSide | STRING | NO | `BOTH`、`LONG`、`SHORT`,单向持仓模式下默认 `BOTH` | +| type | STRING | YES | `LIMIT`、`MARKET`、`STOP`、`STOP_MARKET`、`TAKE_PROFIT`、`TAKE_PROFIT_MARKET`、`TRAILING_STOP_MARKET` | +| quantity | STRING | YES* | 委托数量。`closePosition=true` 时可不填 | +| price | STRING | YES* | `LIMIT`、`STOP`、`TAKE_PROFIT` 时必填 | +| stopPrice | STRING | YES* | `STOP`、`STOP_MARKET`、`TAKE_PROFIT`、`TAKE_PROFIT_MARKET` 时必填 | +| timeInForce | STRING | YES* | `LIMIT` 时必填;止损类订单可选(默认 `GTC`)。不支持 `IOC` 和 `FOK` | +| workingType | STRING | NO | `CONTRACT_PRICE` 或 `MARK_PRICE`,默认 `CONTRACT_PRICE` | +| reduceOnly | STRING | NO | 是否仅减仓 | +| closePosition | STRING | NO | 是否全部平仓 | +| priceProtect | STRING | NO | 是否开启价格保护 | +| clientOrderId | STRING | NO | 客户端自定义订单 ID | +| activationPrice | STRING | NO | `TRAILING_STOP_MARKET` 专用激活价格 | +| callbackRate | STRING | NO | `TRAILING_STOP_MARKET` 回调比例 | +| firstDrivenId | STRING | NO | 第一触发条件的驱动子订单 `strategySubId` | +| firstDrivenOn | STRING | NO | 激活第一触发条件的事件类型 | +| firstTrigger | STRING | NO | 第一触发动作 | +| secondDrivenId | STRING | NO | 第二触发条件的驱动子订单 `strategySubId` | +| secondDrivenOn | STRING | NO | 激活第二触发条件的事件类型 | +| secondTrigger | STRING | NO | 第二触发动作 | + +--- + +## 更新策略订单 (TRADE) + +> **响应:** + +```javascript +[ + { + "strategyId": 123456789, + "clientStrategyId": "myStrategy1", + "strategyType": "OTO", + "strategyStatus": "WORKING", + "updatedSubOrder": 1, + "updateStatus": "SUCCESS", + "updateTime": 1699900000000, + "failureCode": 0, + "failureReason": "" + } +] +``` + +`POST /fapi/v3/updateStrategyOrder` + +修改已有策略订单中的一个或多个子订单。返回数组,每个子订单对应一条更新结果。 + +**权重:** 50 + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| strategyId | LONG | YES | 要修改的策略订单 ID | +| strategyType | ENUM | YES | 策略类型:`OTO`、`OCO`、`OTOCO` | +| subOrderList | JSON Array | YES | 要修改的子订单列表。`OTO`/`OCO` 最多 2 个,`OTOCO` 最多 3 个 | + +**`subOrderList` 中每个子订单的字段:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| strategySubId | STRING | YES | 要修改的子订单序号 | +| securityType | STRING | YES | 资产类型 | +| symbol | STRING | YES | 交易对 | +| side | STRING | YES | `BUY` 或 `SELL` | +| positionSide | STRING | NO | `BOTH`、`LONG`、`SHORT` | +| type | STRING | YES | 订单类型 | +| quantity | STRING | NO | 新委托数量 | +| price | STRING | NO | 新价格(适用于 `LIMIT`、`STOP`、`TAKE_PROFIT`) | +| stopPrice | STRING | NO | 新止损价 | +| timeInForce | STRING | NO | 新的有效方式 | +| workingType | STRING | NO | 新的触发价格类型 | +| reduceOnly | STRING | NO | | +| closePosition | STRING | NO | | +| priceProtect | STRING | NO | | +| activationPrice | STRING | NO | 仅适用于 `TRAILING_STOP_MARKET` | +| callbackRate | STRING | NO | 仅适用于 `TRAILING_STOP_MARKET` | + +--- + +## 查询策略当前挂单 (USER_DATA) + +> **响应:** + +```javascript +{ + "strategyId": 123456789, + "clientStrategyId": "myStrategy1", + "strategyType": "OTO", + "strategyStatus": "WORKING", + "bookTime": 1699900000000, + "updateTime": 1699900001000, + "subOrders": [ + { + "strategyId": 123456789, + "orderId": 987654321, + "clientOrderId": "myOrder1", + "status": "NEW", + "strategySubId": 1, + "firstDrivenId": 0, + "firstDrivenOn": "", + "firstTrigger": "", + "secondDrivenId": 0, + "secondDrivenOn": "", + "secondTrigger": "", + "securityType": "FUTURE", + "symbol": "BTCUSDT", + "side": "BUY", + "positionSide": "LONG", + "type": "LIMIT", + "timeInForce": "GTC", + "quantity": "0.001", + "reduceOnly": false, + "closePosition": false, + "price": "50000", + "avgPrice": "0", + "priceProtect": false, + "stopPrice": "0", + "activatePrice": null, + "callbackRate": null, + "workingType": "CONTRACT_PRICE", + "triggerTime": 0 + } + ] +} +``` + +`GET /fapi/v3/strategyOpenOrder` + +查询当前挂单中的策略订单。`strategyId` 与 `clientStrategyId` 必须且只能提供其中一个。 + +**权重:** 5 + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| strategyId | LONG | NO* | 策略订单 ID | +| clientStrategyId | STRING | NO* | 客户端自定义策略 ID | +| strategyType | STRING | YES | 策略类型:`OTO`、`OCO`、`OTOCO` | + +*`strategyId` 与 `clientStrategyId` 二选一,不可同时传入。 + +--- + +## 查询策略历史订单 (USER_DATA) + +> **响应:** + +```javascript +{ + "strategyId": 123456789, + "clientStrategyId": "myStrategy1", + "strategyType": "OTO", + "strategyStatus": "EXPIRED", + "bookTime": 1699800000000, + "updateTime": 1699800060000, + "subOrders": [ + { + "strategyId": 123456789, + "orderId": 987654321, + "clientOrderId": "myOrder1", + "status": "FILLED", + "strategySubId": 1, + "firstDrivenId": 0, + "firstDrivenOn": "", + "firstTrigger": "", + "secondDrivenId": 0, + "secondDrivenOn": "", + "secondTrigger": "", + "securityType": "FUTURE", + "symbol": "BTCUSDT", + "side": "BUY", + "positionSide": "LONG", + "type": "LIMIT", + "timeInForce": "GTC", + "quantity": "0.001", + "reduceOnly": false, + "closePosition": false, + "price": "50000", + "avgPrice": "50000", + "priceProtect": false, + "stopPrice": "0", + "activatePrice": null, + "callbackRate": null, + "workingType": "CONTRACT_PRICE", + "triggerTime": 1699800030000 + } + ] +} +``` + +`GET /fapi/v3/strategyHistoryOrder` + +查询历史策略订单。`strategyId` 与 `clientStrategyId` 必须且只能提供其中一个。最大可查询范围为 90 天。 + +**权重:** 5 + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| strategyId | LONG | NO* | 策略订单 ID | +| clientStrategyId | STRING | NO* | 客户端自定义策略 ID | +| strategyType | STRING | YES | 策略类型:`OTO`、`OCO`、`OTOCO` | +| startTime | LONG | NO | 起始时间(毫秒),最远可查 90 天前的数据 | +| endTime | LONG | NO | 结束时间(毫秒) | +| limit | INT | NO | 返回条数,默认 500,最大 1000 | + +*`strategyId` 与 `clientStrategyId` 二选一,不可同时传入。 + +--- + # 绑定子账户 (USER_DATA) > **响应:** From 06e3641d6937419a728ae65466fe19a3ab48e0dd Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Fri, 22 May 2026 16:25:19 +0800 Subject: [PATCH 116/131] docs: add aster-chain/v3/transfer endpoint (EN & CN) Co-Authored-By: Claude Sonnet 4.6 --- CHANGELOG.md | 15 ++++---- V3(Recommended)/EN/aster-chain.md | 36 +++++++++++++++++++ .../aster-chain_CN.md" | 36 +++++++++++++++++++ 3 files changed, 78 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3ce9a46..7a3af25 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,19 +4,16 @@ ### Added -#### `POST /fapi/v3/stpMode` — Change STP Mode / 更改STP模式 +#### `POST /aster-chain/v3/transfer` — Transfer to Address / 转账至地址 -A new TRADE endpoint that sets the account-level **Self-Trade Prevention (STP) mode** applied to all orders by default. Accepted values: `EXPIRE_TAKER`, `EXPIRE_MAKER`, `EXPIRE_BOTH`. +A new WITHDRAW-authenticated endpoint for transferring assets to another registered Aster Chain user address. Returns `transferId`, `asset`, `amount`, `toAddress`, `timestamp`, and `status`. -#### `GET /fapi/v3/stpMode` — Get Current STP Mode / 查询STP模式 +#### STP Mode APIs / 自成交防止模式接口 -A new USER_DATA endpoint that returns the account's current STP mode. +- `POST /fapi/v3/stpMode` — Change STP Mode / 更改STP模式 (TRADE, weight 1) +- `GET /fapi/v3/stpMode` — Get Current STP Mode / 查询STP模式 (USER_DATA, weight 30) -### Changed - -#### `POST /fapi/v3/order` — New Order: added optional `stpMode` parameter - -Added `stpMode` (ENUM, optional) to the place-order parameter list. When specified, it overrides the account-level STP default for that individual order. +Supports `EXPIRE_TAKER`, `EXPIRE_MAKER`, `EXPIRE_BOTH`. Added `stpMode` optional parameter to `POST /fapi/v3/order` for per-order STP override. --- diff --git a/V3(Recommended)/EN/aster-chain.md b/V3(Recommended)/EN/aster-chain.md index e9b9fef..29ba55a 100644 --- a/V3(Recommended)/EN/aster-chain.md +++ b/V3(Recommended)/EN/aster-chain.md @@ -8,6 +8,7 @@ - [Aster-Chain Account Endpoints](#aster-chain-account-endpoints) - [Get Account Status (USER_DATA)](#get-account-status-user_data) - [Modify Account Status (TRADE)](#modify-account-status-trade) + - [Transfer to Address (WITHDRAW)](#transfer-to-address-withdraw) --- @@ -56,3 +57,38 @@ Modify the account's privacy status. After a successful update, the change is br | Name | Type | Mandatory | Description | |------|------|-----------|-------------| | status | STRING | YES | Account privacy mode: `"PUBLIC"` or `"PRIVATE"` | + +--- + +## Transfer to Address (WITHDRAW) + +> **Response:** + +```javascript +{ + "transferId": "123456789", + "asset": "USDT", + "amount": "10.00", + "toAddress": "0xAbCd1234...", + "timestamp": 1699900800000, + "status": "SUCCESS" // "SUCCESS" or "PENDING" +} +``` + +`POST /aster-chain/v3/transfer` + +Transfer assets to another Aster Chain address. The recipient address must belong to a registered Aster Chain user. + +**Weight:** 50 + +**Parameters:** + +| Name | Type | Mandatory | Description | +|------|------|-----------|-------------| +| asset | STRING | YES | Asset name to transfer (e.g. `"USDT"`) | +| amount | DECIMAL | YES | Transfer amount, must be greater than 0 | +| toAddress | STRING | YES | Recipient's Aster Chain wallet address | +| clientTranId | STRING | NO | Client-defined transfer ID; auto-generated if not provided | +| nonce | LONG | YES | Microsecond timestamp | +| user | STRING | YES | Source account wallet address | +| signature | STRING | YES | EIP-712 signature, signed with the `user` account's wallet private key | diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-chain_CN.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-chain_CN.md" index 52e013c..f37e324 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-chain_CN.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-chain_CN.md" @@ -8,6 +8,7 @@ - [Aster-Chain 账户接口](#aster-chain-账户接口) - [查询账户状态 (USER_DATA)](#查询账户状态-user_data) - [修改账户状态 (TRADE)](#修改账户状态-trade) + - [转账至地址 (WITHDRAW)](#转账至地址-withdraw) --- @@ -56,3 +57,38 @@ | 名称 | 类型 | 是否必需 | 描述 | |------|------|---------|------| | status | STRING | YES | 账户隐私模式:`"PUBLIC"` 或 `"PRIVATE"` | + +--- + +## 转账至地址 (WITHDRAW) + +> **响应:** + +```javascript +{ + "transferId": "123456789", + "asset": "USDT", + "amount": "10.00", + "toAddress": "0xAbCd1234...", + "timestamp": 1699900800000, + "status": "SUCCESS" // "SUCCESS" 或 "PENDING" +} +``` + +`POST /aster-chain/v3/transfer` + +将资产转账至另一个 Aster Chain 地址。接收地址必须属于已注册的 Aster Chain 用户。 + +**权重:** 50 + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| asset | STRING | YES | 转账资产名称(如 `"USDT"`) | +| amount | DECIMAL | YES | 转账金额,必须大于 0 | +| toAddress | STRING | YES | 接收方的 Aster Chain 钱包地址 | +| clientTranId | STRING | NO | 客户端自定义划转 ID,若未提供则自动生成 | +| nonce | LONG | YES | 微秒时间戳 | +| user | STRING | YES | 发起账户钱包地址 | +| signature | STRING | YES | EIP-712 签名,使用 `user` 账户的钱包私钥签名 | From d2e89b448c43554670a81c62f9a6770f67461e55 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Fri, 22 May 2026 16:33:00 +0800 Subject: [PATCH 117/131] docs: update CHANGELOG for 2026-05-21 STP mode entries Co-Authored-By: Claude Sonnet 4.6 --- CHANGELOG.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7a3af25..17bdb84 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,23 @@ A new WITHDRAW-authenticated endpoint for transferring assets to another registe Supports `EXPIRE_TAKER`, `EXPIRE_MAKER`, `EXPIRE_BOTH`. Added `stpMode` optional parameter to `POST /fapi/v3/order` for per-order STP override. + +### Added + +#### `POST /fapi/v3/stpMode` — Change STP Mode / 更改STP模式 + +A new TRADE endpoint that sets the account-level **Self-Trade Prevention (STP) mode** applied to all orders by default. Accepted values: `EXPIRE_TAKER`, `EXPIRE_MAKER`, `EXPIRE_BOTH`. + +#### `GET /fapi/v3/stpMode` — Get Current STP Mode / 查询STP模式 + +A new USER_DATA endpoint that returns the account's current STP mode. + +### Changed + +#### `POST /fapi/v3/order` — New Order: added optional `stpMode` parameter + +Added `stpMode` (ENUM, optional) to the place-order parameter list. When specified, it overrides the account-level STP default for that individual order. + --- ## 2026-05-20 From 866b7e5a2aa2bac2b6c44cc2cfb0c5b908c144dd Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Tue, 26 May 2026 10:28:49 +0800 Subject: [PATCH 118/131] docs: add Prediction API testnet documentation (EN & CN) Add full REST and WebSocket API reference for the prediction market testnet (https://papi.asterdex-testnet.com), covering market data, trading, prediction market mint/burn/positions, account, and WebSocket streams. Update CHANGELOG for 2026-05-26. Co-Authored-By: Claude Sonnet 4.6 --- CHANGELOG.md | 18 + .../aster-finance-prediction-api-tesetnet.md | 2939 ++++++++++++++++ .../aster-finance-prediction-api-testnet.md" | 3073 +++++++++++++++++ 3 files changed, 6030 insertions(+) create mode 100644 V3(Recommended)/EN/aster-finance-prediction-api-tesetnet.md create mode 100644 "V3(Recommended)/\344\270\255\346\226\207/aster-finance-prediction-api-testnet.md" diff --git a/CHANGELOG.md b/CHANGELOG.md index 17bdb84..4c46685 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,23 @@ # Changelog +## 2026-05-26 + +### Added + +#### Prediction API Testnet Documentation / 预测市场 API 测试网文档 + +Added full API reference documentation for the Prediction API on testnet (`https://papi.asterdex-testnet.com`), covering: + +- **Market data**: `GET /api/v3/prediction/ping`, `GET /api/v3/prediction/time`, `GET /api/v3/prediction/exchangeInfo`, depth, trades, klines, tickers, best order book +- **Trading**: `POST /api/v3/order` (Place order), `DELETE /api/v3/order` (Cancel order), `GET /api/v3/order`, open orders, all orders, cancel all open orders +- **Prediction market**: mint (`POST /api/v3/prediction/mint`), burn (`POST /api/v3/prediction/burn`), positions (`GET /api/v3/prediction/positionRisk`), position history, settlement history +- **Account**: perp-spot transfer, withdraw fee, withdraw, account info, trade history +- **WebSocket streams**: trades, klines, tickers, order book depth (limited & incremental), listen key lifecycle, `ACCOUNT_UPDATE` payload + +Documentation available in both English (`V3(Recommended)/EN/aster-finance-prediction-api-tesetnet.md`) and Chinese (`V3(Recommended)/中文/aster-finance-prediction-api-testnet.md`). + +--- + ## 2026-05-21 ### Added diff --git a/V3(Recommended)/EN/aster-finance-prediction-api-tesetnet.md b/V3(Recommended)/EN/aster-finance-prediction-api-tesetnet.md new file mode 100644 index 0000000..ecc9de6 --- /dev/null +++ b/V3(Recommended)/EN/aster-finance-prediction-api-tesetnet.md @@ -0,0 +1,2939 @@ +# Prediction API Overview + +* This document lists the base URL for the API endpoints: [**https://papi.asterdex-testnet.com**](https://papi.asterdex-testnet.com) +* All API responses are in JSON format. + +## API Agent Address settings + +* Many endpoints require an API Key to access. +* When setting the Agent Address, for security reasons it is recommended to set an IP access whitelist. +* **Never reveal your Agent Address/private key to anyone.** + +If an API Key is accidentally exposed, immediately delete that Key and generate a new one. + +### Attention +* TESTUSDT or any other symbols starting with TEST are symbols used for Aster's INTERNAL TESTING ONLY. Please DO NOT trade on these symbols starting with TEST. Aster does not hold any accountability for loss of funds due to trading on these symbols. However, if you run into issues, you may contact support about this any time, we will try to help you recover your funds. + +### V3 Nonce Mechanism + +* **Nonce** is used to validate the **validity, uniqueness, and replay-protection** of requests. Clients should use the **current timestamp (microsecond precision)** as the nonce, and the difference from server time must not exceed **10 seconds**. + +* Request processing flow: + + 1. If the nonce **has already been used** → rejected as a **duplicate request** + 2. Otherwise, the system checks whether it is **too old** + +* To improve performance, each user maintains only the **most recent 100 nonces**: + + * If the list is full and the new nonce is **smaller than the current minimum** → rejected as **expired** + * Otherwise, the **oldest nonce is removed** and the new one is added + +* Overall effect: **prevents duplicates and stale requests, retaining only recent valid requests** + +### HTTP return codes + +* HTTP `4XX` status codes are used to indicate errors in the request content, behavior, or format. The problem lies with the requester. +* HTTP `403` status code indicates a violation of WAF restrictions (Web Application Firewall). +* HTTP `429` error code indicates a warning that the access frequency limit has been exceeded and the IP is about to be blocked. +* HTTP `418` indicates that after receiving a 429 you continued to access, so the IP has been blocked. +* HTTP `5XX` error codes are used to indicate issues on the Aster service side. + +### API error codes + +* When using the endpoint `/api/v3`, any endpoint may throw exceptions; + +The API error codes are returned in the following format: + +```javascript +{ + "code": -1121, + "msg": "Invalid symbol." +} +``` + +### Basic information about the endpoint + +* Endpoints with the `GET` method must send parameters in the `query string`. +* For `POST`, `PUT`, and `DELETE` endpoints, parameters can be sent in the `query string` with content type `application/x-www-form-urlencoded` , or in the `request body`. +* The order of parameters is not required. + +--- + +## Access restrictions + +### Basic information on access restrictions + +* The `rateLimits` array in `/api/v3/prediction/exchangeInfo` contains objects related to REQUEST\_WEIGHT and ORDERS rate limits for trading. These are further defined in the `enum definitions` section under `rateLimitType`. +* A 429 will be returned when any of the rate limits are violated. + +### IP access limits + +* Each request will include a header named `X-MBX-USED-WEIGHT-(intervalNum)(intervalLetter)` that contains the used weight of all requests from the current IP. +* Each endpoint has a corresponding weight, and some endpoints may have different weights depending on their parameters. The more resources an endpoint consumes, the higher its weight will be. +* Upon receiving a 429, you are responsible for stopping requests and must not abuse the API. +* **If you continue to violate access limits after receiving a 429, your IP will be banned and you will receive a 418 error code.** +* Repeated violations of the limits will result in progressively longer bans, **from a minimum of 2 minutes up to a maximum of 3 days**. +* The `Retry-After` header will be sent with responses bearing 418 or 429, and will give the wait time **in seconds** (if 429\) to avoid the ban, or, if 418, until the ban ends. +* **Access restrictions are based on IP, not API Key** + +You are advised to use WebSocket messages to obtain the corresponding data as much as possible to reduce the load and rate-limit pressure from requests. + +### Order rate limits + +* Each successful order response will include a `X-MBX-ORDER-COUNT-(intervalNum)(intervalLetter)` header containing the number of order limit units currently used by the account. +* When the number of orders exceeds the limit, you will receive a response with status 429 but without the `Retry-After` header. Please check the order rate limits in `GET api/v3/exchangeInfo` (rateLimitType \= ORDERS) and wait until the ban period ends. +* Rejected or unsuccessful orders are not guaranteed to include the above header in the response. +* **Order placement rate limits are counted per account.** + +### WebSocket connection limits + +* The WebSocket server accepts a maximum of 5 messages per second. Messages include: + * PING frame + * PONG frame + * Messages in JSON format, such as subscribe and unsubscribe. +* If a user sends messages that exceed the limit, the connection will be terminated. IPs that are repeatedly disconnected may be blocked by the server. +* A single connection can subscribe to up to **1024** Streams. + +--- + +## API authentication types + +* Each API has its own authentication type, which determines what kind of authentication should be performed when accessing it. +* The authentication type will be indicated next to each endpoint name in this document; if not specifically stated, it defaults to `NONE`. + +| Security Type | Description | +| ------------- | ----------------------------------------- | +| NONE | API that does not require authentication | +| PREDICTION_TRADE | A valid signer and signature are required | +| USER_DATA | A valid signer and signature are required | +| USER_STREAM | A valid signer and signature are required | +| MARKET_DATA | API that does not require authentication | + +--- + +## SIGNED (TRADE AND USER\_DATA) Endpoint security +* Security Type: PREDICTION_TRADE, USER_DATA, USER_STREAM + + +## Example of POST /api/v3/order + + +#### The following parameters are API registration details. The values for user, signer, and privateKey are for demonstration purposes only (the privateKey corresponds to the signer). + +| Key | Value | Desc +| ---------- | ------------------------------------------------------------------ | ---------- | +| user | 0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e |Login wallet address | +| signer | 0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0 |[Click Here](https://www.asterdex.com/en/api-wallet) | +| privateKey | 0x4fd0a42218f3eae43a6ce26d22544e986139a01e5b34a62db53757ffca81bae1 |[Click Here](https://www.asterdex.com/en/api-wallet) | + +#### The nonce parameter is the current system time in microseconds. If it exceeds the system time or lags behind it by more than 10 seconds, the request is considered invalid. +```python +#python +nonce = math.trunc(time.time()*1000000) +print(nonce) +#1748310859508867 +``` +```java +#python +//java +Instant now = Instant.now(); +long microsecond = now.getEpochSecond() * 1000000 + now.getNano() / 1000; +``` + +#### Example: Post an order (using Python as an example). + + +```python +import time +import urllib +import threading + +import requests +from eth_account.messages import encode_structured_data +from eth_account import Account + +typed_data = { + "types": { + "EIP712Domain": [ + {"name": "name", "type": "string"}, + {"name": "version", "type": "string"}, + {"name": "chainId", "type": "uint256"}, + {"name": "verifyingContract", "type": "address"} + ], + "Message": [ + { "name": "msg", "type": "string" } + ] + }, + "primaryType": "Message", + "domain": { + "name": "AsterSignTransaction", + "version": "1", + "chainId": 714, + "verifyingContract": "0x0000000000000000000000000000000000000000" + }, + "message": { + "msg": "$msg" + } +} + +headers = { + 'Content-Type': 'application/x-www-form-urlencoded', + 'User-Agent': 'PythonApp/1.0' +} +host = 'https://papi.asterdex-testnet.com' + +# config your user and agent info here +user = '*' +signer = '*' +private_key = "*" + +place_order = {"url":"/api/v3/order","method":"POST","params":{"symbol": "ASTERUSDT", "type": "LIMIT", "side": "BUY", + "timeInForce": "GTC", "quantity": "100", "price": "0.4"}} +_last_ms = 0 +_i = 0 +_nonce_lock = threading.Lock() + +def get_nonce(): + global _last_ms, _i + with _nonce_lock: + now_ms = int(time.time()) + + if now_ms == _last_ms: + _i += 1 + else: + _last_ms = now_ms + _i = 0 + + return now_ms * 1_000_000 + _i + +def send_by_url(api) : + my_dict = api['params'] + url = host + api['url'] + + my_dict['nonce'] = str(get_nonce()) + my_dict['signer'] = signer + + param = urllib.parse.urlencode(my_dict) + print(param) + typed_data['message']['msg'] = param + message = encode_structured_data(typed_data) + signed = Account.sign_message(message, private_key=private_key) + + url = url + '?' + param + '&signature=' + signed.signature.hex() + print(url) + res = requests.post(url, headers=headers) + + print(res.text) + +def send_by_body(api) : + my_dict = api['params'] + url = host +api['url'] + my_dict['nonce'] = str(get_nonce()) + my_dict['signer'] = signer + + param = urllib.parse.urlencode(my_dict) + typed_data['message']['msg'] = param + message = encode_structured_data(typed_data) + + signed = Account.sign_message(message, private_key=private_key) + print(signed.signature.hex()) + + my_dict['signature'] = signed.signature.hex() + + print(my_dict) + res = requests.post(url, data=my_dict, headers=headers) + + print(res.text) + +if __name__ == '__main__': + send_by_url(place_order) + # send_by_body(place_order) + +``` + +## Public API parameters + +### Terminology + +The terminology in this section applies throughout the document. New users are encouraged to read it carefully for better understanding. + +* `base asset` refers to the asset being traded in a trading pair, i.e., the asset name written first; for example, in `BTCUSDT`, `BTC` is the `base asset`. +* `quote asset` refers to the pricing asset of a trading pair, i.e., the asset name written at the latter part; for example, in `BTCUSDT`, `USDT` is the `quote asset`. + +### Enumeration definition + +**Trading pair status (status):** + +* TRADING \- after trade + +**Trading pair type:** + +* PREDICTION \- prediction + +**Order status (status):** + +| Status | Description | +| :---- | :---- | +| NEW | Order accepted by the matching engine | +| PARTIALLY\_FILLED | Part of the order was filled | +| FILLED | The order was fully filled | +| CANCELED | The user canceled the order | +| REJECTED | The order was not accepted by the matching engine and was not processed | +| EXPIRED | Order canceled by the trading engine, for example: Limit FOK order not filled, Market order not fully filled, orders canceled during exchange maintenance | + +**Order types (orderTypes, type):** + +* LIMIT \- Limit Order +* MARKET \- Market Order + +**Order response type (newOrderRespType):** + +* ACK +* RESULT +* FULL + +**Order direction (direction side):** + +* BUY \- Buy +* SELL \- Sell + +**Valid types (timeInForce):** + +This defines how long an order can remain valid before expiring. + +| Status | Description | +| :---- | :---- | +| GTC (Good 'Til Canceled) | The order remains active until it is fully executed or manually canceled. | +| IOC (Immediate or Cancel) | The order will execute immediately for any amount available. Any unfilled portion is automatically canceled. | +| FOK (Fill or Kill) | The order must be fully executed immediately. If it cannot be filled in full, it is canceled right away. | +| GTX (Good till crossing, Post only) | The post-only limit order will only be placed if it can be added as a maker order and not as a taker order. | + +**K-line interval:** + +m (minutes), h (hours), d (days), w (weeks), M (months) + +* 1s (added) +* 1m +* 3m +* 5m +* 15m +* 30m +* 1h +* 2h +* 4h +* 6h +* 8h +* 12h +* 1d +* 3d +* 1w +* 1M + +**Rate limit type (rateLimitType)** + +REQUEST\_WEIGHT + +```json + { + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200 + } +``` + +ORDERS + +```json + { + "rateLimitType": "ORDERS", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 100 + } +``` + +* REQUEST\_WEIGHT \- The maximum sum of request weights allowed within a unit time + +* ORDERS \- Order placement frequency limit per time unit + +**Interval restriction (interval)** + +* MINUTE \- Minute + +--- + +## Filters + +Filters, i.e. Filter, define a set of trading rules. There are two types: filters for trading pairs `symbol filters`, and filters for the entire exchange `exchange filters` (not supported yet) + +### Trading pair filters + +#### PRICE\_FILTER Price filter + +**Format in the /exchangeInfo response:** + +```javascript + { + "minPrice": "0.0001", + "maxPrice": "0.9999", + "filterType": "PRICE_FILTER", + "tickSize": "0.01" + } +``` + +The `Price Filter` checks the validity of the `price` parameter in an order. It consists of the following three parts: + +* `minPrice` defines the minimum allowed value for `price`/`stopPrice`. +* `maxPrice` defines the maximum allowed value for `price`/`stopPrice`. +* `tickSize` defines the step interval for `price`/`stopPrice`, meaning the price must equal minPrice plus an integer multiple of tickSize. + +Each of the above items can be 0; when 0 it means that item is not constrained. + +The logical pseudocode is as follows: + +* `price` \>= `minPrice` +* `price` \<= `maxPrice` +* (`price`\-`minPrice`) % `tickSize` \== 0 + +#### PERCENT\_PRICE price amplitude filter + +**Format in the /exchangeInfo response:** + +```javascript + { + "multiplierDown": "0.9500", + "multiplierUp": "1.0500", + "multiplierDecimal": "4", + "filterType": "PERCENT_PRICE" + } +``` + +The `PERCENT_PRICE` filter defines the valid range of prices based on the index price. + +For the "price percentage" to apply, the "price" must meet the following conditions: + +* `price` \<=`indexPrice` \*`multiplierUp` +* `price`\> \=`indexPrice` \*`multiplierDown` + +#### LOT\_SIZE order size + +**Format in the /exchangeInfo response:** + +```javascript + { + "stepSize": "0.00100000", + "filterType": "LOT_SIZE", + "maxQty": "100000.00000000", + "minQty": "0.00100000" + } +``` + +Lots is an auction term. The `LOT_SIZE` filter validates the `quantity` (i.e., the amount) parameter in orders. It consists of three parts: + +* `minQty` indicates the minimum allowed value for `quantity`. +* `maxQty` denotes the maximum allowed value for `quantity`. +* `stepSize` denotes the allowed step increment for `quantity`. + +The logical pseudocode is as follows: + +* `quantity` \>= `minQty` +* `quantity` \<= `maxQty` +* (`quantity`\-`minQty`) % `stepSize` \== 0 + +#### MARKET\_LOT\_SIZE \- Market order size + +\***/exchangeInfo response format:** + +```javascript + { + "stepSize": "0.00100000", + "filterType": "MARKET_LOT_SIZE" + "maxQty": "100000.00000000", + "minQty": "0.00100000" + } +``` + +The `MARKET_LOT_SIZE` filter defines the `quantity` (i.e., the "lots" in an auction) rules for `MARKET` orders on a trading pair. There are three parts: + +* `minQty` defines the minimum allowed `quantity`. +* `maxQty` defines the maximum allowed quantity. +* `stepSize` defines the increments by which the quantity can be increased or decreased. + +In order to comply with the `market lot size`, the `quantity` must satisfy the following conditions: + +* `quantity` \>= `minQty` +* `quantity` \<= `maxQty` +* (`quantity`\-`minQty`) % `stepSize` \== 0 + +#### predictionEvents \- Prediction Events + +**Format in the /exchangeInfo response:** + +```javascript +"predictionEvents": [ + { + "eventName": "ETH_UP_DOWN_7D", // Prediction event name + "oracleSymbol": "ETHUSDT", // Predicted symbol + "predictionType": "UP_DOWN", // Prediction type + "sides": [ + "UP", + "DOWN" + ], // Prediction directions + "period": "10080M", // Prediction period in minutes + "startTime": 1778476080000, // Event start time + "endTime": 1780376880000, // Event end time + "status": "LIVE", // Event status + "currentRoundId": 3, // Current round ID + "orderTypes": [ + "LIMIT", + "MARKET" + ], // Supported order types + "timeInForce": [ + "GTC", + "IOC", + "FOK", + "GTX" + ], // Supported TIF values + "liveRound":{ + "marketName": "USD1_UP_DOWN_5M_1778483280", // Prediction market name + "symbols": [ + "USD1_UP_DOWN_5M_1778483280_YUSDT", + "USD1_UP_DOWN_5M_1778483280_NUSDT" + ], // Two symbols for the market; Y = up, N = down + "assets": [ + "USD1_UP_DOWN_5M_1778483280_Y", + "USD1_UP_DOWN_5M_1778483280_N" + ], // Two assets for the market; Y = up, N = down + "roundId": 2, // Round ID + "tradingStartTime": 1778482970000, // Trading start time + "tradingEndTime": 1778483520000, // Trading end time + "windowStartTime": 1778483280000, // Window start time + "windowEndTime": 1778483580000, // Window end time + "roundStatus": "SETTLED", // Market status + "openPrice": "0.99920000", // Opening price + "endPrice": "0.99910000", // Ending price + "winAsset": "USD1_UP_DOWN_5M_1778483280_N", // Winning asset: Y if up, N if down + "settleTime": 1778483582057, // Settlement time + "settleHash": "0x3bc0aff52472dafd4b70d3423386a2dabf675fe7cd604e92391e2a4702cf0980" // On-chain settlement hash + }, + "rounds": [ + { + "marketName": "USD1_UP_DOWN_5M_1778483280", // Prediction market name + "symbols": [ + "USD1_UP_DOWN_5M_1778483280_YUSDT", + "USD1_UP_DOWN_5M_1778483280_NUSDT" + ], // Two symbols for the market; Y = up, N = down + "assets": [ + "USD1_UP_DOWN_5M_1778483280_Y", + "USD1_UP_DOWN_5M_1778483280_N" + ], // Two assets for the market; Y = up, N = down + "roundId": 2, // Round ID + "tradingStartTime": 1778482970000, // Trading start time + "tradingEndTime": 1778483520000, // Trading end time + "windowStartTime": 1778483280000, // Window start time + "windowEndTime": 1778483580000, // Window end time + "roundStatus": "SETTLED", // Market status + "openPrice": "0.99920000", // Opening price + "endPrice": "0.99910000", // Ending price + "winAsset": "USD1_UP_DOWN_5M_1778483280_N", // Winning asset: Y if up, N if down + "settleTime": 1778483582057, // Settlement time + "settleHash": "0x3bc0aff52472dafd4b70d3423386a2dabf675fe7cd604e92391e2a4702cf0980" // On-chain settlement hash + } + ] + } +] +``` + +`status` is the event status: + +| Status | Description | +| :---- | :---- | +| `LIVE` | Running | +| `CLOSED` | Closed | +| `INVALID` | Invalid | + +`roundStatus` is the market status: + +| RoundStatus | Description | +| :---- | :---- | +| `PREMARKET` | Pre-market ready (trading available in advance) | +| `TRADING` | Market is open for trading | +| `SETTLED` | Market has been settled | + +* After settlement, the market will be automatically delisted after a period (24H). Delisted markets are no longer displayed. +* For events with `status` of `CLOSED` or `INVALID`, only `reduceOnly` Market Sell orders can be placed. + +# Market data API + +## Noop + +> **Response:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +``POST /api/v3/noop`` + +By using this request, it is possible to efficiently cancel previously sent transactions that are still in the queue and have not completed the on chain operation (Nonce should be equal to this request,no guarantee of success +) + +**Weight:** +1 + +## Test server connectivity + +**Response** + +```javascript +{} +``` + +`GET /api/v3/ping` + +Test whether the REST API can be reached. + +**Weight:** 1 + +**Parameters:** NONE + +## Get server time + +**Response** + +```javascript +{ + "serverTime": 1499827319559 +} +``` + +`GET /api/v3/time` + +Test if the REST API can be reached and retrieve the server time. + +**Weight:** 1 + +**Parameters:** NONE + +## Trading specification information + +**Response** + +```javascript +{ + "timezone": "UTC", + "serverTime": 1756197279679, + "rateLimits": [{ + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 6000 + }, + { + "rateLimitType": "ORDERS", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 6000 + }, + { + "rateLimitType": "ORDERS", + "interval": "SECOND", + "intervalNum": 10, + "limit": 300 + } + ], + "exchangeFilters": [], + "assets": [{ + "asset": "USD" + }, { + "asset": "USDT" + }, + { + "asset": "BNB" + } + ], + "symbols": [{ + "status": "TRADING", + "baseAsset": "BNB", + "quoteAsset": "USDT", + "pricePrecision": 8, + "quantityPrecision": 8, + "baseAssetPrecision": 8, + "quotePrecision": 8, + "filters": [{ + "minPrice": "0.0001", + "maxPrice": "0.9999", + "filterType": "PRICE_FILTER", + "tickSize": "0.01000000" + }, + { + "stepSize": "0.00100000", + "filterType": "LOT_SIZE", + "maxQty": "1000", + "minQty": "1" + }, + { + "stepSize": "0.00100000", + "filterType": "MARKET_LOT_SIZE", + "maxQty": "900000", + "minQty": "0.00100000" + }, + { + "limit": 200, + "filterType": "MAX_NUM_ORDERS" + }, + { + "minNotional": "5", + "filterType": "MIN_NOTIONAL" + }, + { + "maxNotional": "100", + "filterType": "MAX_NOTIONAL" + }, + { + "maxNotional": "100", + "minNotional": "5", + "avgPriceMins": 5, + "applyMinToMarket": true, + "filterType": "NOTIONAL", + "applyMaxToMarket": true + }, + { + "multiplierDown": "0", + "multiplierUp": "5", + "multiplierDecimal": "0", + "filterType": "PERCENT_PRICE" + }, + { + "bidMultiplierUp": "5", + "askMultiplierUp": "5", + "bidMultiplierDown": "0", + "avgPriceMins": 5, + "multiplierDecimal": "0", + "filterType": "PERCENT_PRICE_BY_SIDE", + "askMultiplierDown": "0" + } + ], + "orderTypes": [ + "LIMIT", + "MARKET" + ], + "timeInForce": [ + "GTC", + "IOC", + "FOK", + "GTX" + ], + "symbol": "BTC_UP_DOWN_5M_1778483280_YUSDT", + "ocoAllowed": false + }] +} +``` + +`GET /api/v3/prediction/exchangeInfo` + +Retrieve trading rules and trading pair information. + +**Weight:** 1 + +**Parameters:** None + +## Depth information + +**Response** + +```javascript +{ + "lastUpdateId": 1027024, + "E":1589436922972, // Message output time + "T":1589436922959, // Transaction time + "bids": [ + [ + "4.00000000", // PRICE + "431.00000000" // QTY + ] + ], + "asks": [ + [ + "4.00000200", + "12.00000000" + ] + ] +} +``` + +`GET /api/v3/depth` + +**Weight:** + +Based on limit adjustments: + +| Limitations | Weight | +| :---- | :---- | +| 5, 10, 20, 50 | 2 | +| 100 | 5 | +| 500 | 10 | +| 1000 | 20 | + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| limit | INT | NO | Default 100\. Optional values: \[5, 10, 20, 50, 100, 500, 1000\] | + +## Recent trades list + +**Response** + +```javascript +[ + { + "id": 657, + "price": "1.01000000", + "qty": "5.00000000", + "baseQty": "4.95049505", + "time": 1755156533943, + "isBuyerMaker": false + } +] +``` + +`GET /api/v3/trades` + +Get recent trades + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| limit | INT | NO | Default 500; maximum 1000 | + +## Query historical trades (MARKET\_DATA) + +**Response** + +```javascript +[ + { + "id": 1140, + "price": "1.10000000", + "qty": "7.27200000", + "baseQty": "6.61090909", + "time": 1756094288700, + "isBuyerMaker": false + } +] +``` + +`GET /api/v3/historicalTrades` + +Retrieve historical trades + +**Weight:** 20 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| limit | INT | NO | Default 500; maximum 1000\. | +| fromId | LONG | NO | Return starting from which trade id. Defaults to returning the most recent trade records. | + +## Recent trades (aggregated) + +**Response** + +```javascript +[ + { + "a": 26129, // Aggregate tradeId + "p": "0.01633102", // Price + "q": "4.70443515", // Quantity + "f": 27781, // First tradeId + "l": 27781, // Last tradeId + "T": 1498793709153, // Timestamp + "m": true, // Was the buyer the maker? + } +] +``` + +`GET /api/v3/aggTrades` + +The difference between aggregated trades and individual trades is that trades with the same price, same side, and same time are combined into a single entry. + +**Weight:** 20 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| fromId | LONG | NO | Return results starting from the trade ID that includes fromId | +| startTime | LONG | NO | Return results starting from trades after that time | +| endTime | LONG | NO | Return the trade records up to that moment | +| limit | INT | NO | Default 500; maximum 1000\. | + +* If you send startTime and endTime, the interval must be less than one hour. +* If no filter parameters (fromId, startTime, endTime) are sent, the most recent trade records are returned by default + +## K-line data + +**Response** + +```javascript +[ + [ + 1499040000000, // Open time + "0.01634790", // Open + "0.80000000", // High + "0.01575800", // Low + "0.01577100", // Close + "148976.11427815", // Volume + 1499644799999, // Close time + "2434.19055334", // Quote asset volume + 308, // Number of trades + "1756.87402397", // Taker buy base asset volume + "28.46694368", // Taker buy quote asset volume + ] +] +``` + +`GET /api/v3/klines` + +Each K-line represents a trading pair. The open time of each K-line can be regarded as a unique ID. + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| interval | ENUM | YES | See the enumeration definition: K-line interval | +| startTime | LONG | NO | | +| endTime | LONG | NO | | +| limit | INT | NO | Default 500; maximum 1500\. | + +* If startTime and endTime are not sent, the most recent trades are returned by default + +## 24h price change + +**Response** + +```javascript +{ + "symbol": "BTC_UP_DOWN_5M_1778483280_YUSDT", //symbol + "priceChange": "-94.99999800", //price change + "priceChangePercent": "-95.960", //price change percent + "weightedAvgPrice": "0.29628482", //weighted avgPrice + "prevClosePrice": "3.89000000", //prev close price + "lastPrice": "4.00000200", //last price + "lastQty": "200.00000000", //last qty + "bidPrice": "0.4999", //first bid price + "bidQty": "431.00", //first bid qty + "askPrice": "0.5001", //first ask price + "askQty": "9.00", //first ask qty + "openPrice": "99.00000000", //open price + "highPrice": "100.00000000", //high price + "lowPrice": "0.10000000", //low price + "volume": "8913.30000000", //volume + "quoteVolume": "15.30000000", //quote volume + "openTime": 1499783499040, //open time + "closeTime": 1499869899040, //close time + "firstId": 28385, // first id + "lastId": 28460, // last id + "count": 76, // count + "baseAsset": "BTC", //base asset + "quoteAsset": "USDT" //quote asset +} +``` + +`GET /api/v3/ticker/24hr` + +24-hour rolling window price change data. Please note that omitting the symbol parameter will return data for all trading pairs; in that case the returned data is an example array for the respective pairs, which is not only large in volume but also has a very high weight. + +**Weight:** 1 \= single trading pair; **40** \= When the trading pair parameter is missing (returns all trading pairs) + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | NO | | + +* Please note that omitting the symbol parameter will return data for all trading pairs + +## Latest price + +**Response** + +```javascript +{ + "symbol": "BTC_UP_DOWN_5M_1778483280_YUSDT", + "price": "1.30000000", + "time": 1649666690902 +} +``` + +OR + +```javascript +[ + { + "symbol": "BTC_UP_DOWN_5M_1778483280_YUSDT", + "price": "1.30000000", + "time": 1649666690902 + } +] +``` + +`GET /api/v3/ticker/price` + +Get the latest price for a trading pair + +**Weight:** 1 \= Single trading pair; **2** \= No symbol parameter (returns all pairs) + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | NO | | + +* If no trading pair parameter is sent, information for all trading pairs will be returned + +## Current best order + +**Response** + +```javascript +{ + "symbol": "BTC_UP_DOWN_5M_1778483280_YUSDT", + "bidPrice": "0.4999", + "bidQty": "431.00", + "askPrice": "0.5001", + "askQty": "9.00" + "time": 1589437530011 // Timestamp +} +``` + +OR + +```javascript +[ + { + "symbol": "BTC_UP_DOWN_5M_1778483280_YUSDT", + "bidPrice": "0.4999", + "bidQty": "431.00", + "askPrice": "0.5001", + "askQty": "9.00", + "time": 1589437530011 // Timestamp + } +] +``` + +`GET /api/v3/ticker/bookTicker` + +Return the current best orders (highest bid, lowest ask) + +**Weight:** 1 \= Single trading pair; **2** \= No symbol parameter (returns all pairs) + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | NO | | + +* If no trading pair parameter is sent, information for all trading pairs will be returned + +## Get symbol fees + +**Response** + +```javascript +{ + "symbol": "BTC_UP_DOWN_5M_1778483280_YUSDT", + "makerCommissionRate": "0.000200", + "takerCommissionRate": "0.000700", + "settleCommissionRate": "0.000100" +} +``` + +`GET /api/v3/commissionRate` + +Get symbol fees + +**Weight:** 20 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | + +# Spot account and trading API + +## Place order (TRADE) + +**Response ACK:** + +```javascript +{ + "symbol": "BTC_UP_DOWN_5M_1778483280_YUSDT", + "orderId": 28, + "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP", + "updateTime": 1507725176595, + "price": "0.00000000", + "avgPrice": "0.0000000000000000", + "origQty": "10.00000000", + "cumQty": "0", + "executedQty": "10.00000000", + "cumQuote": "10.00000000", + "status": "FILLED", + "timeInForce": "GTC", + "stopPrice": "0", + "origType": "LIMIT", + "type": "LIMIT", + "side": "SELL", +} +``` + +`POST /api/v3/order` + +Send order + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| side | ENUM | YES | See enum definition: Order direction | +| type | ENUM | YES | See enumeration definition: Order type | +| timeInForce | ENUM | NO | See enum definition: Time in force | +| quantity | DECIMAL | NO | | +| quoteOrderQty | DECIMAL | NO | | +| price | DECIMAL | NO | | +| newClientOrderId | STRING | NO | Client-customized unique order ID. If not provided, one will be generated automatically. | +| stopPrice | DECIMAL | NO | Only STOP, STOP\_MARKET, TAKE\_PROFIT, TAKE\_PROFIT\_MARKET require this parameter | + +Depending on the order `type`, certain parameters are mandatory: + +| Type | Mandatory parameters | +| :---- | :---- | +| LIMIT | timeInForce, quantity, price | +| MARKET | quantity or quoteOrderQty | +| STOP and TAKE\_PROFIT | quantity, price, stopPrice | +| STOP\_MARKET and TAKE\_PROFIT\_MARKET | quantity, stopPrice | + +Other information: + +* Place a `MARKET` `SELL` market order; the user controls the amount of base assets to sell with the market order via `QUANTITY`. + * For example, when placing a `MARKET` `SELL` market order on the `BTC_UP_DOWN_5M_1778483280_YUSDT` pair, use `QUANTITY` to let the user specify how much BTC they want to sell. +* For a `MARKET` `BUY` market order, the user controls how much of the quote asset they want to spend with `quoteOrderQty`; `QUANTITY` will be calculated by the system based on market liquidity. For example, when placing a `MARKET` `BUY` market order on the `BTC_UP_DOWN_5M_1778483280_YUSDT` pair, use `quoteOrderQty` to let the user choose how much USDT to use to buy BTC. +* A `MARKET` order using `quoteOrderQty` will not violate the `LOT_SIZE` limit rules; the order will be executed as closely as possible to the given `quoteOrderQty`. +* Unless a previous order has already been filled, orders set with the same `newClientOrderId` will be rejected. + +## Cancel order (TRADE) + +**Response** + +```javascript +{ + "symbol": "BTC_UP_DOWN_5M_1778483280_YUSDT", + "orderId": 28, + "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP", + "updateTime": 1507725176595, + "price": "0.00000000", + "avgPrice": "0.0000000000000000", + "origQty": "10.00000000", + "cumQty": "0", + "executedQty": "10.00000000", + "cumQuote": "10.00000000", + "status": "CANCELED", + "timeInForce": "GTC", + "stopPrice": "0", + "origType": "LIMIT", + "type": "LIMIT", + "side": "SELL", +} +``` + +`DELETE /api/v3/order` + +Cancel active orders + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| orderId | LONG | NO | | +| origClientOrderId | STRING | NO | | + +At least one of `orderId` or `origClientOrderId` must be sent. + +## Query order (USER\_DATA) + +**Response** + +```javascript +{ + "orderId": 38, + "symbol": "BTC_UP_DOWN_5M_1778483280_YUSDT", + "status": "FILLED", + "clientOrderId": "afMd4GBQyHkHpGWdiy34Li", + "price": "20", + "avgPrice": "12.0000000000000000", + "origQty": "10", + "executedQty": "10", + "cumQuote": "120", + "timeInForce": "GTC", + "type": "LIMIT", + "side": "BUY", + "stopPrice": "0", + "origType": "LIMIT", + "time": 1649913186270, + "updateTime": 1649913186297 +} +``` + +`GET /api/v3/order` + +Query order status + +* Please note that orders meeting the following conditions will not be returned: + * The final status of the order is `CANCELED` or `EXPIRED`, **and** + * The order has no trade records, **and** + * Order creation time \+ 7 days \< current time + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| orderId | LONG | NO | | +| origClientOrderId | STRING | NO | | + +Note: + +* You must send at least one of `orderId` or `origClientOrderId`. + +## Query Current Open Order (USER\_DATA) + +**Response** + +```javascript +{ + "orderId": 38, + "symbol": "BTC_UP_DOWN_5M_1778483280_YUSDT", + "status": "NEW", + "clientOrderId": "afMd4GBQyHkHpGWdiy34Li", + "price": "20", + "avgPrice": "12.0000000000000000", + "origQty": "10", + "executedQty": "10", + "cumQuote": "120", + "timeInForce": "GTC", + "type": "LIMIT", + "side": "BUY", + "stopPrice": "0", + "origType": "LIMIT", + "time": 1649913186270, + "updateTime": 1649913186297 +} +``` + +`GET /api/v3/openOrder` + +Query current open order status. + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| orderId | LONG | NO | | +| origClientOrderId | STRING | NO | | + +Note: + +* You must send at least one of `orderId` or `origClientOrderId`. + +## Current open orders (USER\_DATA) + +**Response** + +```javascript +[ + { + "orderId": 349661, + "symbol": "BTC_UP_DOWN_5M_1778483280_YUSDT", + "status": "NEW", + "clientOrderId": "LzypgiMwkf3TQ8wwvLo8RA", + "price": "1.10000000", + "avgPrice": "0.0000000000000000", + "origQty": "5", + "executedQty": "0", + "cumQuote": "0", + "timeInForce": "GTC", + "type": "LIMIT", + "side": "BUY", + "stopPrice": "0", + "origType": "LIMIT", + "time": 1756252940207, + "updateTime": 1756252940207, + } +] +``` + +`GET /api/v3/openOrders` + +Retrieve all current open orders for trading pairs. Use calls without a trading pair parameter with caution. + +**Weight:** + +* With symbol ***1*** +* Without ***40*** + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | NO | | + +* If the symbol parameter is not provided, it will return the order books for all trading pairs. + +## Cancel All Open Orders (TRADE) + +> **Response** + +```javascript +{ + "code": 200, + "msg": "The operation of cancel all open order is done." +} +``` + +`` +DEL /api/v3/allOpenOrders `` + +**Weight:** +- ***1*** + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +orderIdList | STRING | NO | orderid array string +origClientOrderIdList | STRING | NO | clientOrderId array string + + +## Query all orders (USER\_DATA) + +**Response** + +```javascript +[ + { + "orderId": 349661, + "symbol": "BTC_UP_DOWN_5M_1778483280_YUSDT", + "status": "NEW", + "clientOrderId": "LzypgiMwkf3TQ8wwvLo8RA", + "price": "1.10000000", + "avgPrice": "0.0000000000000000", + "origQty": "5", + "executedQty": "0", + "cumQuote": "0", + "timeInForce": "GTC", + "type": "LIMIT", + "side": "BUY", + "stopPrice": "0", + "origType": "LIMIT", + "time": 1756252940207, + "updateTime": 1756252940207, + } +] +``` + +`GET /api/v3/allOrders` + +Retrieve all account orders; active, canceled, or completed. + +* Please note that orders meeting the following conditions will not be returned: + * Order creation time \+ 7 days \< current time + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| orderId | LONG | NO | | +| startTime | LONG | NO | | +| endTime | LONG | NO | | +| limit | INT | NO | Default 500; maximum 1000 | + +* The maximum query time range must not exceed 7 days. +* By default, query data is from the last 7 days. + + +`` +GET /api/v3/prediction/transactionHistory`` +> **Response** + +```javascript +[ + { + "tranId": 1759115482304540227, + "tradeId": null, + "asset": "ASTER", + "symbol": "BTC_UP_DOWN_5M_1778483280_YUSDT", + "balanceDelta": "-500.00000000", + "balanceInfo": "TRADE_SOURCE", + "time": 1759115482000, + "type": "TRADE_SOURCE" + } +] +``` + +Query transaction records + +**Weight:** +30 + +**Parameters:** + +| Name | Type | Is it required? | Description | +------------ | ------------ | ------------ | ------------ +asset | STRING | NO | asset +type | STRING | NO | type +startTime | LONG | NO | startTime +endTime | LONG | NO | endTime +limit | LONG | NO | default:100 max:1000 + +**Note:** + +* `type`: `TRADE_TARGET`,`TRADE_SOURCE`,`TRANSFER_SPOT_TO_FUTURE`,`TRANSFER_FUTURE_TO_SPOT`,`TRANSFER_SPOT_TO_SPOT`,`AIRDROP`,`DIVIDEND`,`TRANSFER_REFUND`,`INTERNAL_TRANSFER`,`TRANSFER`,`SWAP`,`COMMISSION_REBATE`,`CASH_BACK`,`STAKING_WITHDRAW`, `STAKING_CLAIM`, `STAKING_DELEGATE`,`PREDICTION_CLAIM`,`PREDICTION_USER_REBATE`,`PREDICTION_SETTLE`,`PREDICTION_SETTLE_FEE`,`PREDICTION_MINT`,`PREDICTION_BURN` +* If startTime and endTime are not provided, only data from the most recent 7 days will be returned. + +## Perp-spot transfer (TRADE) + +**Response:** + +```javascript +{ + "tranId": 21841, //Tran Id + "status": "SUCCESS" //Status +} +``` + +`POST /api/v3/asset/wallet/transfer ` + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| amount | DECIMAL | YES | Quantity | +| asset | STRING | YES | Asset | +| clientTranId | STRING | YES | Transaction ID | +| kindType | STRING | YES | Transaction type | + +* kindType FUTURE_SPOT(future to spot)/SPOT_FUTURE(spot to future) + +## Prediction market mint (TRADE) + +**Response** + +```javascript +{ + "clientOrderId": "xxx", // Client order ID + "quoteAmount": "10.00000000", // Total quote asset spent + "yesPrice": "0.55000000", // YES token price at mint time + "noPrice": "0.45000000", // NO token price at mint time (yesPrice + noPrice = 1) + "pairCount": "10.00000000" // Number of YES+NO pairs minted +} +``` + +`POST /api/v3/prediction/mint` + +Mint YES+NO token pairs for a prediction market. The system deducts an equivalent amount of quote asset at the current market price and credits equal quantities of YES and NO tokens to the account. + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | The YES token trading pair of the prediction market | +| quantity | DECIMAL | YES | Number of YES+NO token pairs to mint | +| newClientOrderId | STRING | NO | Client-customized unique order ID. If not provided, one will be generated automatically. | + +Notes: +* `symbol` must be a valid prediction market token trading pair with status `TRADING` or `PENDING_TRADING` +* `quantity` represents the number of pairs to mint simultaneously; the account will receive equal amounts of YES and NO tokens +* `yesPrice` + `noPrice` = 1 (in quote asset units) + + +## Prediction market burn (TRADE) + +**Response** + +```javascript +{ + "clientOrderId": "xxx", // Client order ID + "quoteAmount": "9.80000000", // Total quote asset returned after burn + "yesPrice": null, // Not returned for burn operations + "noPrice": null, // Not returned for burn operations + "pairCount": "10.00000000" // Number of YES+NO pairs burned +} +``` + +`POST /api/v3/prediction/burn` + +Burn equal quantities of YES+NO token pairs to redeem the corresponding quote asset. The account must hold equal amounts of YES and NO tokens to perform a burn. + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | The YES token trading pair of the prediction market | +| quantity | DECIMAL | YES | Number of YES+NO token pairs to burn | +| newClientOrderId | STRING | NO | Client-customized unique order ID. If not provided, one will be generated automatically. | + +Notes: +* `symbol` must be a valid prediction market token trading pair with status `TRADING`, `PENDING_TRADING`, or `CLOSED` +* `quantity` represents the number of pairs to burn simultaneously; the account must hold the corresponding amounts of both YES and NO tokens +* `yesPrice` and `noPrice` are `null` in the burn response +* Burn operations are still available after the market is `CLOSED` + + +## Query prediction market current positions (USER\_DATA) + +**Response** + +```javascript +[ + { + "marketName": "BTC_UP_DOWN_20260512", // Prediction market name + "symbol": "BTC_UP_DOWN_5M_1778483280_YUSDT", // Trading pair + "assetName": "USDT", // Settlement asset + "type": "YES", // Position direction: "YES" or "NO" + "openAvgPrice": "0.65000000", // Average open price + "cumQty": "100.00000000", // Total position quantity + "closeAvgPrice": "0.00000000", // Average close price (0 if not closed) + "realizedPnl": "0.00000000", // Realized PnL + "closeQty": "0.00000000", // Closed quantity + "insertTime": 1747000000000, // Position open time (millisecond timestamp) + "commissionFee": "0.10000000", // Commission fee paid + "commissionAsset": "USDT", // Commission fee asset + "balance": "65.00000000", // Position value (quantity × average open price) + "availableBalance": "65.00000000", // Available balance + } +] +``` + +`GET /api/v3/prediction/positions` + +Query the current account's prediction market position list. + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | NO | Trading pair; if not provided, returns all positions | +| signer | STRING | YES | API wallet address | +| nonce | STRING | YES | Current time in microseconds | +| signature | STRING | YES | Signature | + +## Query prediction market position history (USER\_DATA) + +**Response** + +```javascript +[ + { + "marketName": "BTC_UP_DOWN_20260501", // Prediction market name + "symbol": "BTC_UP_DOWN_5M_1778483280_YUSDT", // Trading pair + "assetName": "USDT", // Settlement asset + "type": "YES", // Position direction: "YES" or "NO" + "openAvgPrice": "0.72000000", // Average open price + "cumQty": "200.00000000", // Total position quantity + "closeAvgPrice": "1.00000000", // Average close price + "realizedPnl": "56.00000000", // Realized PnL + "closeQty": "200.00000000", // Closed quantity + "insertTime": 1746000000000, // Position open time (millisecond timestamp) + "closeTime": 1746086400000, // Close/settlement time (millisecond timestamp) + "status": "settled", // Position status: "close" (manually closed) or "settled" (market settled) + "commissionFee": "0.10000000", // Commission fee paid + "commissionAsset": "USDT", // Commission fee asset + "settleFee": "2.00000000", // Settlement fee (only present when status is "settled") + "settleAsset": "USDT", // Settlement fee asset + } +] +``` + +`GET /api/v3/prediction/positionHistories` + +Query the current account's prediction market historical position list (closed or settled). + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | NO | Trading pair; if not provided, returns all historical positions | +| startTime | LONG | NO | Start time (millisecond timestamp) | +| endTime | LONG | NO | End time (millisecond timestamp) | +| limit | INT | NO | Number of results; default 100, maximum 1000 | +| signer | STRING | YES | API wallet address | +| nonce | STRING | YES | Current time in microseconds | +| signature | STRING | YES | Signature | + +Notes: +* When both `startTime` and `endTime` are provided, `startTime` must not be greater than `endTime` +* `limit` range is 1 to 1000, default is 100 +* `status` field: `close` means the user manually closed the position; `settled` means the prediction market expired and settled + +## Query prediction market settlement histories (USER\_DATA) + +**Response** + +```javascript +[ + { + "marketName": "BTC_UP_DOWN_20260501", // Prediction market name + "asset": "BTC_UP_DOWN_20260501YES", // Token asset (YES or NO token) + "symbol": "BTC_UP_DOWN_20260501YES", // Trading pair + "marketStartTime": 1746000000000, // Market start time (millisecond timestamp) + "marketEndTime": 1746086400000, // Market end time / settlement time (millisecond timestamp) + "shareAmount": "200.00000000", // Share quantity held at settlement + "settleAsset": "USDT", // Settlement asset + "settleAmount": "200.00000000", // Settlement amount received + "settleFeeAmount": "2.00000000", // Settlement fee charged + "entryPrice": "0.72000000", // Average entry price + "settlePrice": "1.00000000", // Final settlement price + "realizedPnl": "56.00000000", // Realized PnL after settlement + "status": "settled" // Settlement status + } +] +``` + +`GET /api/v3/prediction/settlementHistories` + +Query the current account's prediction market settlement history (markets that have expired and settled). + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | NO | Trading pair; if not provided, returns all settlement records | +| startTime | LONG | NO | Filter by market start time (millisecond timestamp) | +| endTime | LONG | NO | Filter by market end time (millisecond timestamp) | +| limit | INT | NO | Number of results; default 100, maximum 1000 | +| signer | STRING | YES | API wallet address | +| nonce | STRING | YES | Current time in microseconds | +| signature | STRING | YES | Signature | + +Notes: +* When both `startTime` and `endTime` are provided, `startTime` must not be greater than `endTime` +* `limit` range is 1 to 1000, default is 100 +* `settleAmount` is the gross payout; `realizedPnl` equals `settleAmount` minus the cost basis +* `settleFeeAmount` is deducted from the settlement payout + +## Get withdraw fee (NONE) +> **Response:** +```javascript +{ + "tokenPrice": 1.00019000, + "gasCost": 0.5000, + "gasUsdValue": 0.5 +} +``` + +`` +GET /api/v3/aster/withdraw/estimateFee +`` + +**Weight:** +1 + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +chainId | STRING | YES | +asset | STRING | YES | + +**Notes:** +* chainId: 1(ETH),56(BSC),42161(Arbi) +* gasCost: The minimum fee required for a withdrawal + +## Withdraw (USER_DATA) +> **Response:** +```javascript +{ + "withdrawId": "1014729574755487744", + "hash":"0xa6d1e617a3f69211df276fdd8097ac8f12b6ad9c7a49ba75bbb24f002df0ebb" +} +``` + +`` +POST /api/v3/aster/user-withdraw`` + +**Weight:** +5 + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +chainId | STRING | YES | 1(ETH),56(BSC),42161(Arbi) +asset | STRING | YES | +amount | STRING | YES | +fee | STRING | YES | +receiver | STRING | YES | The address of the current account +nonce | STRING | YES | The current time in microseconds +userSignature | STRING | YES | + + +**Note:** +* chainId: 1(ETH),56(BSC),42161(Arbi) +* receiver: The address of the current account +* If the futures account balance is insufficient, funds will be transferred from the spot account to the perp account for withdrawal. +* userSignature demo + +```shell +const domain = { + name: 'Aster', + version: '1', + chainId: 56, + verifyingContract: ethers.ZeroAddress, + } + +const currentTime = Date.now() * 1000 + +const types = { + Action: [ + {name: "type", type: "string"}, + {name: "destination", type: "address"}, + {name: "destination Chain", type: "string"}, + {name: "token", type: "string"}, + {name: "amount", type: "string"}, + {name: "fee", type: "string"}, + {name: "nonce", type: "uint256"}, + {name: "aster chain", type: "string"}, + ], + } + const value = { + 'type': 'Withdraw', + 'destination': '0xD9cA6952F1b1349d27f91E4fa6FB8ef67b89F02d', + 'destination Chain': 'BSC', + 'token': 'USDT', + 'amount': '10.123400', + 'fee': '1.234567891', + 'nonce': currentTime, + 'aster chain': 'Mainnet', + } + + +const signature = await signer.signTypedData(domain, types, value) +``` + +## Account information (USER\_DATA) + +**Response** + +```javascript +{ + "feeTier": 0, + "canTrade": true, + "canDeposit": true, + "canWithdraw": true, + "canBurnAsset": true, + "updateTime": 0, + "balances": [ + { + "asset": "BTC", + "free": "4723846.89208129", + "locked": "0.00000000" + }, + { + "asset": "LTC", + "free": "4763368.68006011", + "locked": "0.00000000" + } + ] +} +``` + +`GET /api/v3/account` + +Retrieve current account information + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | + +## Account trade history (USER\_DATA) + +**Response** + +```javascript +[ + { + "symbol": "BTC_UP_DOWN_5M_1778483280_YUSDT", + "id": 1002, + "orderId": 266358, + "side": "BUY", + "price": "1", + "qty": "2", + "quoteQty": "2", + "commission": "0.00105000", + "commissionAsset": "BNB", + "time": 1755656788798, + "counterpartyId": 19, + "createUpdateId": null, + "maker": false, + "buyer": true + } +] +``` + +`GET /api/v3/userTrades` + +Retrieve the trade history for a specified trading pair of an account + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | NO | | +| orderId | LONG | NO | Must be used together with the parameter symbol | +| startTime | LONG | NO | | +| endTime | LONG | NO | | +| fromId | LONG | NO | Starting trade ID. Defaults to fetching the most recent trade. | +| limit | INT | NO | Default 500; maximum 1000 | + +* If both `startTime` and `endTime` are not sent, only data from the last 7 days will be returned. +* The maximum interval between startTime and endTime is 7 days. +* `fromId` cannot be sent together with `startTime` or `endTime`. + +--- + +# WebSocket market data feed + +* The base URL for all wss endpoints listed in this document is: **wss://sstream.asterdex.com** +* Streams have either a single raw stream or a combined stream +* Single raw streams format is \*\*/ws/\*\* +* The URL format for combined streams is \*\*/stream?streams=//\*\* +* When subscribing to combined streams, the event payload is wrapped in this format: \*\*{"stream":"","data":}\*\* +* All trading pairs in stream names are **lowercase** +* Each link to **sstream.asterdex.com** is valid for no more than 24 hours; please handle reconnections appropriately +* Every 3 minutes the server sends a ping frame; the client must reply with a pong frame within 10 minutes, otherwise the server will close the connection. The client is allowed to send unpaired pong frames (i.e., the client may send pong frames at a frequency higher than once every 10 minutes to keep the connection alive). + +## Real-time subscribe/unsubscribe data streams + +* The following messages can be sent via WebSocket to subscribe or unsubscribe to data streams. Examples are shown below. +* The `id` in the response content is an unsigned integer that serves as the unique identifier for exchanges of information. +* If the `result` in the response content is `null`, it indicates the request was sent successfully. + +### Subscribe to a stream + +**Response** + +```javascript +{ + "result": null, + "id": 1 +} +``` + +* **Request** { "method": "SUBSCRIBE", "params": \[ "btc_up_dowm_5m_1778483280_yusdt@aggTrade", "btc_up_dowm_5m_1778483280_yusdt@depth" \], "id": 1 } + +### Unsubscribe from a stream + +**Response** + +```javascript +{ + "result": null, + "id": 312 +} +``` + +* **Request** { "method": "UNSUBSCRIBE", "params": \[ "btc_up_dowm_5m_1778483280_yusdt@depth" \], "id": 312 } + +### Subscribed to the feed + +**Response** + +```javascript +{ + "result": [ + "btc_up_dowm_5m_1778483280_yusdt@aggTrade" + ], + "id": 3 +} +``` + +* **Request** + + { "method": "LIST\_SUBSCRIPTIONS", "id": 3 } + +### Set properties + +Currently, the only configurable property is whether to enable the `combined` ("combined") stream. When connecting using `/ws/` ("raw stream"), the combined property is set to `false`, while connecting using `/stream/` sets the property to `true`. + +**Response** + +```javascript +{ +"result": null, +"id": 5 +} +``` + +* **Request** { "method": "SET\_PROPERTY" "params": \[ "combined", true \], "id": 5 } + +### Retrieve properties + +**Response** + +```javascript +{ + "result": true, // Indicates that combined is set to true. + "id": 2 +} +``` + +* **Request** + + { "method": "GET\_PROPERTY", "params": \[ "combined" \], "id": 2 } + +\#\#\# Error message + +| Error message | Description | +| :---- | :---- | +| {"code": 0, "msg": "Unknown property"} | Parameters applied in SET\_PROPERTY or GET\_PROPERTY are invalid | +| {"code": 1, "msg": "Invalid value type: expected Boolean", "id": '%s'} | Only true or false are accepted | +| {"code": 2, "msg": "Invalid request: property name must be a string"} | The provided attribute name is invalid | +| {"code": 2, "msg": "Invalid request: request ID must be an unsigned integer"} | Parameter ID not provided or ID has an invalid type | +| {"code": 2, "msg": "Invalid request: unknown variant %s, expected one of SUBSCRIBE, UNSUBSCRIBE, LIST\_SUBSCRIPTIONS, SET\_PROPERTY, GET\_PROPERTY at line 1 column 28"} | Typo warning, or the provided value is not of the expected type | +| {"code": 2, "msg": "Invalid request: too many parameters"} | Unnecessary parameters were provided in the data | +| {"code": 2, "msg": "Invalid request: property name must be a string"} | Property name not provided | +| {"code": 2, "msg": "Invalid request: missing field method at line 1 column 73"} | Data did not provide method | +| {"code":3,"msg":"Invalid JSON: expected value at line %s column %s"} | JSON syntax error | + +## Collection transaction flow + +**Payload:** + +```javascript +{ + "e": "aggTrade", // Event type + "E": 123456789, // Event time + "s": "BTC_UP_DOWN_5M_1778483280_YUSDT", // Symbol + "a": 12345, // Aggregate trade ID + "p": "0.001", // Price + "q": "100", // Quantity + "f": 100, // First trade ID + "l": 105, // Last trade ID + "T": 123456785, // Trade time + "m": true, // Is the buyer the market maker? + "M": true // Ignore +} +``` + +The collection transaction stream pushes transaction information and is an aggregation of a single order. + +**Stream name:** `@aggTrade` + +**Update speed:** real-time + +## Tick-by-tick trades + +**Payload:** + +```javascript +{ + "e": "trade", // Event type + "E": 123456789, // Event time + "s": "BTC_UP_DOWN_5M_1778483280_YUSDT", // Symbol + "t": 12345, // Trade ID + "p": "0.001", // Price + "q": "100", // Quantity + "T": 123456785, // Trade time + "m": true, // Is the buyer the market maker? +} +``` + +**Stream name:** `@trade` + +Each trade stream pushes the details of every individual trade. A **trade**, also called a transaction, is defined as a match between exactly one taker and one maker. + +## K-line streams + +**Payload:** + +```javascript +{ + "e": "kline", // Event type + "E": 123456789, // Event time + "s": "BTC_UP_DOWN_5M_1778483280_YUSDT", // Symbol + "k": { + "t": 123400000, // Kline start time + "T": 123460000, // Kline close time + "s": "BTC_UP_DOWN_5M_1778483280_YUSDT", // Symbol + "i": "1m", // Interval + "f": 100, // First trade ID + "L": 200, // Last trade ID + "o": "0.0010", // Open price + "c": "0.0020", // Close price + "h": "0.0025", // High price + "l": "0.0015", // Low price + "v": "1000", // Base asset volume + "n": 100, // Number of trades + "x": false, // Is this kline closed? + "q": "1.0000", // Quote asset volume + "V": "500", // Taker buy base asset volume + "Q": "0.500", // Taker buy quote asset volume + "B": "123456" // Ignore + } +} +``` + +The K-line stream pushes per-second updates for the requested type of K-line (the latest candle). + +**Stream name:** `@kline_` + +**Update speed:** 2000ms + +**K-line interval parameter:** + +m (minutes), h (hours), d (days), w (weeks), M (months) + +* 1m +* 3m +* 5m +* 15m +* 30m +* 1h +* 2h +* 4h +* 6h +* 8h +* 12h +* 1d +* 3d +* 1w +* 1M + +## Simplified ticker by symbol + +**Payload:** + +```javascript + { + "e": "24hrMiniTicker", // Event type + "E": 123456789, // Event time + "s": "BTC_UP_DOWN_5M_1778483280_YUSDT", // Symbol + "c": "0.0025", // Close price + "o": "0.0010", // Open price + "h": "0.0025", // High price + "l": "0.0010", // Low price + "v": "10000", // Total traded base asset volume + "q": "18" // Total traded quote asset volume + } +``` + +Refreshed simplified 24-hour ticker information by symbol + +**Stream name:** `@miniTicker` + +**Update speed:** 1000ms + +## Compact tickers for all symbols in the entire market + +**Payload:** + +```javascript +[ + { + // Same as @miniTicker payload + } +] +``` + +Same as above, but pushes all trading pairs. Note that only updated tickers will be pushed. + +**Stream name:** \!miniTicker@arr + +**Update speed:** 1000ms + +## Full ticker per symbol + +**Payload:** + +```javascript +{ + "e": "24hrTicker", // Event type + "E": 123456789, // Event time + "s": "BTC_UP_DOWN_5M_1778483280_YUSDT", // Symbol + "p": "0.0015", // Price change + "P": "250.00", // Price change percent + "w": "0.0018", // Weighted average price + "c": "0.0025", // Last price + "Q": "10", // Last quantity + "o": "0.0010", // Open price + "h": "0.0025", // High price + "l": "0.0010", // Low price + "v": "10000", // Total traded base asset volume + "q": "18", // Total traded quote asset volume + "O": 0, // Statistics open time + "C": 86400000, // Statistics close time + "F": 0, // First trade ID + "L": 18150, // Last trade Id + "n": 18151 // Total number of trades +} +``` + +Pushes per-second tag statistics for a single trading pair over a rolling 24-hour window. + +**Stream name:** `@ticker` + +**Update speed:** 1000ms + +## Complete ticker for all trading pairs on the entire market + +**Payload:** + +```javascript +[ + { + // Same as @ticker payload + } +] +``` + +Pushes the full 24-hour refreshed ticker information for all trading pairs across the entire market. Note that tickers without updates will not be pushed. + +**Stream name:** `!ticker@arr` + +**Update speed:** 1000ms + +## Best order book information by symbol + +**Payload:** + +```javascript +{ + "u":400900217, // order book updateId + "s": "BTC_UP_DOWN_5M_1778483280_YUSDT", // symbol + "b":"25.35190000", // best bid price + "B":"31.21000000", // best bid qty + "a":"25.36520000", // best ask price + "A":"40.66000000" // best ask qty +} +``` + +Real-time push of best order book information for the specified trading pair + +**Stream name:** `@bookTicker` + +**Update speed:** Real-time + +## Best order book information across the entire market + +**Payload:** + +```javascript +{ + // Same as @bookTicker payload +} +``` + +Real-time push of the best order information for all trading pairs + +**Stream name:** `!bookTicker` + +**Update speed:** Real-time + +## Limited depth information + +**Payload:** + +```javascript +{ + "e": "depthUpdate", // Event type + "E": 123456789, // Event time + "T": 123456788, // Transaction time + "s": "BTC_UP_DOWN_5M_1778483280_YUSDT", // Symbol + "U": 100, // First update ID in event + "u": 120, // Final update ID in event + "pu": 99, // Final update Id in last stream(ie `u` in last stream) + "bids": [ // Bids to be updated + [ + "0.0024", // Price level to be updated + "10" // Quantity + ] + ], + "asks": [ // Asks to be updated + [ + "0.0026", // Price level to be updated + "100" // Quantity + ] + ] +} +``` + +Limited depth information pushed every second or every 100 milliseconds. Levels indicate how many levels of bid/ask information, optional 5/10/20 levels. + +**Stream names:** `@depth` or `@depth@100ms`. + +**Update speed:** 1000ms or 100ms + +## Incremental depth information + +**Payload:** + +```javascript +{ + "e": "depthUpdate", // Event type + "E": 123456789, // Event time + "T": 123456788, // Transaction time + "s": "BTC_UP_DOWN_5M_1778483280_YUSDT", // Symbol + "U": 100, // First update ID in event + "u": 120, // Final update ID in event + "pu": 99, // Final update Id in last stream(ie `u` in last stream) + "b": [ // Bids to be updated + [ + "5.4", // Price level to be updated + "10" // Quantity + ] + ], + "a": [ // Asks to be updated + [ + "5.6", // Price level to be updated + "100" // Quantity + ] + ] +} +``` + +Pushes the changed parts of the orderbook (if any) every second or every 100 milliseconds + +**Stream name:** `@depth` or `@depth@100ms` + +**Update speed:** 1000ms or 100ms + +## How to correctly maintain a local copy of an order book + +1. Subscribe to **wss://sstream.asterdex.com/ws/btc_up_dowm_5m_1778483280_yusdt@depth** +2. Start caching the received updates. For the same price level, later updates overwrite earlier ones. +3. Fetch the REST endpoint [**https://papi.asterdex-testnet.com/api/v3/depth?symbol=BTC_UP_DOWN_5M_1778483280_YUSDT\&limit=1000**](https://papi.asterdex-testnet.com/api/v3/depth?symbol=BTC_UP_DOWN_5M_1778483280_YUSDT&limit=1000) to obtain a 1000-level depth snapshot +4. Discard from the currently cached messages those with `u` \<= the `lastUpdateId` obtained in step 3 (drop older, expired information) +5. Apply the depth snapshot to your local order book copy, and resume updating the local copy from the first WebSocket event whose `U` \<= `lastUpdateId`\+1 **and** `u` \>= `lastUpdateId`\+1 +6. Each new event's `U` should equal exactly the previous event's `u`\+1; otherwise packets may have been lost \- restart initialization from step 3 +7. The order quantity in each event represents the current order quantity at that price as an **absolute value**, not a relative change +8. If the order quantity at a given price is 0, it means the orders at that price have been canceled or filled, and that price level should be removed + +# WebSocket account information push + +* The base URL for the API endpoints listed in this document is: [**https://papi.asterdex-testnet.com**](https://papi.asterdex-testnet.com) +* The `listenKey` used to subscribe to account data is valid for 60 minutes from the time of creation +* You can extend the 60-minute validity of a `listenKey` by sending a `PUT` request +* You can immediately close the current data stream and invalidate the `listenKey` by sending a `DELETE` for a `listenKey` +* Sending a `POST` on an account with a valid `listenKey` will return the currently valid `listenKey` and extend its validity by 60 minutes +* The WebSocket interface baseurl: **wss://sstream.asterdex.com** +* The stream name for subscribing to the user account data stream is \*\*/ws/\*\* +* Each connection is valid for no more than 24 hours; please handle disconnections and reconnections appropriately + +## Listen Key (spot account) + +### Generate Listen Key (USER\_STREAM) + +**Response** + +```javascript +{ + "listenKey": "pqia91ma19a5s61cv6a81va65sdf19v8a65a1a5s61cv6a81va65sdf19v8a65a1" +} +``` + +`POST /api/v3/listenKey` + +Start a new data stream. The data stream will be closed after 60 minutes unless a keepalive is sent. If the account already has a valid `listenKey`, that `listenKey` will be returned and its validity extended by 60 minutes. + +**Weight:** 1 + +**Parameters:** NONE + +### Extend Listen Key validity period (USER\_STREAM) + +**Response** + +```javascript +{} +``` + +`PUT /api/v3/listenKey` + +Validity extended to 60 minutes after this call. It is recommended to send a ping every 30 minutes. + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| listenKey | STRING | YES | | + +### Close Listen Key (USER\_STREAM) + +**Response** + +```javascript +{} +``` + +`DELETE /api/v3/listenKey` + +Close user data stream + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| listenKey | STRING | YES | | + +## Payload: ACCOUNT\_UPDATE + +An `outboundAccountPosition` event is sent whenever an account balance changes; it contains the assets that may have changed due to the event that generated the balance update. + +**Payload** + +```javascript +{ + "B":[ //Balance + { + "a":"SLP25", //Asset + "f":"10282.42029415", //Free + "l":"653.00000001" //Locked + }, + { + "a":"ADA25", + "f":"9916.96229880", + "l":"34.00510000" + } + ], + "e":"outboundAccountPosition", //Event type + "T":1649926447190, //Time of last account update + "E":1649926447205 //Event Time + "m":"WITHDRAW" // Event reason type +} +``` + +## Payload: Order Update + +Orders are updated via the `executionReport` event + +**Payload** + +```javascript +{ + "s": "BTC_UP_DOWN_5M_1778483280_YUSDT", // symbol + "c":"Xzh0gnxT41PStbwqOtXnjD", // client order id + "S":"SELL", // order direction + "o":"LIMIT", // order type + "f":"GTC", // Time in force + "q":"10.001000", // Order quantity + "p":"19.1000000000", // Order price + "ap":"19.0999999955550656", //average price + "P":"0", //stop price + "x":"TRADE", // Current execution type + "X":"PARTIALLY_FILLED", // Current order status + "i":27, // Order ID + "l":"1", // Last executed quantity + "z":"8.999000", // Cumulative filled quantity + "L":"19.1000000000", // Last executed price + "n":"0.00382000", // Commission amount + "N":"SLP25", // Commission asset + "T":1649926447190, //Transaction Time + "t":18, // transaction id + "m":true, // is this trade the maker side? + "ot":"LIMIT", //original order type + "O":0, // Order creation time + "Z":"171.88089996", // Cumulative quote asset transacted quantity + "Y":"19.1000000000000000", // Last quote asset transacted quantity (i.e. lastPrice * lastQty) + "Q":"0", // Quote Order Qty + "e":"executionReport", // event + "E":1649926447209 // event time +} +``` + +**Execution type:** + +* NEW \- New Order +* CANCELED \- Order canceled +* REJECTED \- New order was rejected +* TRADE \- Order had a new fill +* EXPIRED \- Order expired (based on the order's Time In Force parameter) + +## Event: TradePro + +> **Topic Subscribe:** + +```javascript +{ + "method": "SUBSCRIBE", + "params": [ + "btc_up_dowm_5m_1778483280_yusdt@tradepro" + ], + "id": 3 +} +``` + +> **Payload:** + +```javascript +{ + "stream": "btc_up_dowm_5m_1778483280_yusdt@tradepro", + "data": { + "e": "tradepro", + "E": 1773751963081, + "T": 1773751963079, + "s": "BTC_UP_DOWN_5M_1778483280_YUSDT", + "t": 128884613, + "p": "73685.5", + "q": "0.297", + "h": "0X0000000000000000000000000000000000000000000000000000000000000000", + "m": [ + "hidden", + "hidden" + ] + } +} +``` + +* h: Transaction hash of the trade. + +* m: Array containing the participant addresses: + + * m[0]: Taker address + + * m[1]: Maker address + + +\#错误代码 + +error JSON payload: + +```javascript +{ + "code":-1121, + "msg":"Invalid symbol." +} +``` + +Errors consist of two parts: an error code and a message. The code is standardized, but the message may vary. + +## 10xx \- General server or network issues + +### \-1000 UNKNOWN + +* An unknown error occurred while processing the request. + +### \-1001 DISCONNECTED + +* Internal error; unable to process your request. Please try again. + +### \-1002 UNAUTHORIZED + +* You are not authorized to execute this request. + +### \-1003 TOO\_MANY\_REQUESTS + +* Too many requests queued. +* Too many requests; please use the WebSocket for live updates. +* Too many requests; current limit is %s requests per minute. Please use the WebSocket for live updates to avoid polling the API. +* Too many request weights; IP banned until %s. Please use the WebSocket for live updates to avoid bans. + +### \-1004 DUPLICATE\_IP + +* This IP is already on the white list. + +### \-1005 NO\_SUCH\_IP + +* No such IP has been whitelisted. + +### \-1006 UNEXPECTED\_RESP + +* An unexpected response was received from the message bus. Execution status unknown. + +### \-1007 TIMEOUT + +* Timeout waiting for response from backend server. Send status unknown; execution status unknown. + +### \-1014 UNKNOWN\_ORDER\_COMPOSITION + +* The current order parameter combination is not supported. + +### \-1015 TOO\_MANY\_ORDERS + +* Too many new orders. +* Too many new orders; the current limit is %s orders per %s. + +### \-1016 SERVICE\_SHUTTING\_DOWN + +* This service is no longer available. + +### \-1020 UNSUPPORTED\_OPERATION + +* This operation is not supported. + +### \-1022 INVALID\_SIGNATURE + +* The signature for this request is invalid. + +### \-1023 START\_TIME\_GREATER\_THAN\_END\_TIME + +* The start time in the parameters is after the end time. + +## 11xx \- Request issues + +### \-1100 ILLEGAL\_CHARS + +* Illegal characters found in a parameter. +* Illegal characters found in parameter %s; legal range is %s. + +### \-1101 TOO\_MANY\_PARAMETERS + +* Too many parameters sent for this endpoint. +* Too many parameters; expected %s and received %s. +* Duplicate values for a parameter detected. + +### \-1102 MANDATORY\_PARAM\_EMPTY\_OR\_MALFORMED + +* A mandatory parameter was not sent, was empty/null, or malformed. +* Mandatory parameter %s was not sent, was empty/null, or malformed. +* Param %s or %s must be sent, but both were empty/null. + +### \-1103 UNKNOWN\_PARAM + +* An unknown parameter was sent. + +### \-1104 UNREAD\_PARAMETERS + +* Not all sent parameters were read. +* Not all sent parameters were read; read %s parameter(s) but %s parameter(s) were sent. + +### \-1105 PARAM\_EMPTY + +* A parameter was empty. +* Parameter %s was empty. + +### \-1106 PARAM\_NOT\_REQUIRED + +* A parameter was sent when not required. + +### \-1111 BAD\_PRECISION + +* The precision exceeds the maximum defined for this asset. + +### \-1112 NO\_DEPTH + +* No open orders for the trading pair. + +### \-1114 TIF\_NOT\_REQUIRED + +* TimeInForce parameter sent when not required. + +### \-1115 INVALID\_TIF + +* Invalid timeInForce. + +### \-1116 INVALID\_ORDER\_TYPE + +* Invalid orderType. + +### \-1117 INVALID\_SIDE + +* Invalid order side. + +### \-1118 EMPTY\_NEW\_CL\_ORD\_ID + +* New client order ID was empty. + +### \-1119 EMPTY\_ORG\_CL\_ORD\_ID + +* The client's custom order ID is empty. + +### \-1120 BAD\_INTERVAL + +* Invalid time interval. + +### \-1121 BAD\_SYMBOL + +* Invalid trading pair. + +### \-1125 INVALID\_LISTEN\_KEY + +* This listenKey does not exist. + +### \-1127 MORE\_THAN\_XX\_HOURS + +* The query interval is too large. +* More than %s hours between startTime and endTime. + +### \-1128 OPTIONAL\_PARAMS\_BAD\_COMBO + +* Combination of optional parameters invalid. + +### \-1130 INVALID\_PARAMETER + +* The parameter sent contains invalid data. +* Data sent for parameter %s is not valid. + +### \-1136 INVALID\_NEW\_ORDER\_RESP\_TYPE + +* Invalid newOrderRespType. + +## 20xx \- Processing Issues + +### \-2010 NEW\_ORDER\_REJECTED + +* New order rejected. + +### \-2011 CANCEL\_REJECTED + +* Order cancellation rejected. + +### \-2013 NO\_SUCH\_ORDER + +* Order does not exist. + +### \-2014 BAD\_API\_KEY\_FMT + +* API-key format invalid. + +### \-2015 REJECTED\_MBX\_KEY + +* Invalid API key, IP, or permissions for action. + +### \-2016 NO\_TRADING\_WINDOW + +* No trading window could be found for the symbol. Try ticker/24hrs instead. + +### \-2018 BALANCE\_NOT\_SUFFICIENT + +* Balance is insufficient. + +### \-2020 UNABLE\_TO\_FILL + +* Unable to fill. + +### \-2021 ORDER\_WOULD\_IMMEDIATELY\_TRIGGER + +* Order would immediately trigger. + +### \-2022 REDUCE\_ONLY\_REJECT + +* ReduceOnly Order is rejected. + +### \-2024 POSITION\_NOT\_SUFFICIENT + +* Position is not sufficient. + +### \-2025 MAX\_OPEN\_ORDER\_EXCEEDED + +* Reached max open order limit. + +### \-2026 REDUCE\_ONLY\_ORDER\_TYPE\_NOT\_SUPPORTED + +* This OrderType is not supported when reduceOnly. + +## 40xx \- Filters and other Issues + +### \-4000 INVALID\_ORDER\_STATUS + +* Invalid order status. + +### \-4001 PRICE\_LESS\_THAN\_ZERO + +* Price less than 0\. + +### \-4002 PRICE\_GREATER\_THAN\_MAX\_PRICE + +* Price greater than max price. + +### \-4003 QTY\_LESS\_THAN\_ZERO + +* Quantity less than zero. + +### \-4004 QTY\_LESS\_THAN\_MIN\_QTY + +* Quantity less than minimum quantity. + +### \-4005 QTY\_GREATER\_THAN\_MAX\_QTY + +* Quantity greater than maximum quantity. + +### \-4006 STOP\_PRICE\_LESS\_THAN\_ZERO + +* Stop price less than zero. + +### \-4007 STOP\_PRICE\_GREATER\_THAN\_MAX\_PRICE + +* Stop price greater than max price. + +### \-4008 TICK\_SIZE\_LESS\_THAN\_ZERO + +* Tick size less than zero. + +### \-4009 MAX\_PRICE\_LESS\_THAN\_MIN\_PRICE + +* Max price less than min price. + +### \-4010 MAX\_QTY\_LESS\_THAN\_MIN\_QTY + +* Maximum quantity less than minimum quantity. + +### \-4011 STEP\_SIZE\_LESS\_THAN\_ZERO + +* Step size less than zero. + +### \-4012 MAX\_NUM\_ORDERS\_LESS\_THAN\_ZERO + +* Maximum order quantity less than 0\. + +### \-4013 PRICE\_LESS\_THAN\_MIN\_PRICE + +* Price less than minimum price. + +### \-4014 PRICE\_NOT\_INCREASED\_BY\_TICK\_SIZE + +* Price not increased by tick size. + +### \-4015 INVALID\_CL\_ORD\_ID\_LEN + +* Client order ID is not valid. +* Client order ID length should not be more than 36 characters. + +### \-4016 PRICE\_HIGHTER\_THAN\_MULTIPLIER\_UP + +* Price is higher than mark price multiplier cap. + +### \-4017 MULTIPLIER\_UP\_LESS\_THAN\_ZERO + +* Multiplier up less than zero. + +### \-4018 MULTIPLIER\_DOWN\_LESS\_THAN\_ZERO + +* Multiplier down less than zero. + +### \-4019 COMPOSITE\_SCALE\_OVERFLOW + +* Composite scale too large. + +### \-4020 TARGET\_STRATEGY\_INVALID + +* Target strategy invalid for orderType %s, reduceOnly %b' + +### \-4021 INVALID\_DEPTH\_LIMIT + +* Invalid depth limit. +* %s is not a valid depth limit. + +### \-4022 WRONG\_MARKET\_STATUS + +* Market status sent is not valid. + +### \-4023 QTY\_NOT\_INCREASED\_BY\_STEP\_SIZE + +* The increment of the quantity is not a multiple of the step size. + +### \-4024 PRICE\_LOWER\_THAN\_MULTIPLIER\_DOWN + +* Price is lower than mark price multiplier floor. + +### \-4025 MULTIPLIER\_DECIMAL\_LESS\_THAN\_ZERO + +* Multiplier decimal less than zero. + +### \-4026 COMMISSION\_INVALID + +* Commission invalid. +* Incorrect profit value. +* `%s` less than zero. +* `%s` absolute value greater than `%s`. + +### \-4027 INVALID\_ACCOUNT\_TYPE + +* Invalid account type. + +### \-4029 INVALID\_TICK\_SIZE\_PRECISION + +* Tick size precision is invalid. +* Price decimal precision is incorrect. + +### \-4030 INVALID\_STEP\_SIZE\_PRECISION + +* The number of decimal places for the step size is incorrect. + +### \-4031 INVALID\_WORKING\_TYPE + +* Invalid parameter working type: `%s` + +### \-4032 EXCEED\_MAX\_CANCEL\_ORDER\_SIZE + +* Exceeds the maximum order quantity that can be canceled. +* Invalid parameter working type: `%s` + +### \-4044 INVALID\_BALANCE\_TYPE + +* The balance type is incorrect. + +### \-4045 MAX\_STOP\_ORDER\_EXCEEDED + +* Reached the stop-loss order limit. + +### \-4055 AMOUNT\_MUST\_BE\_POSITIVE + +* The quantity must be a positive integer. + +### \-4056 INVALID\_API\_KEY\_TYPE + +* The API key type is invalid. + +### \-4057 INVALID\_RSA\_PUBLIC\_KEY + +* The API key is invalid. + +### \-4058 MAX\_PRICE\_TOO\_LARGE + +* maxPrice and priceDecimal too large, please check. + +### \-4060 INVALID\_POSITION\_SIDE + +* Invalid position side. + +### \-4061 POSITION\_SIDE\_NOT\_MATCH + +* The order's position direction does not match the user's settings. + +### \-4062 REDUCE\_ONLY\_CONFLICT + +* Invalid or improper reduceOnly value. + +### \-4084 UPCOMING\_METHOD + +* Method is not allowed currently. Coming soon. + +### \-4086 INVALID\_PRICE\_SPREAD\_THRESHOLD + +* Invalid price spread threshold. + +### \-4087 REDUCE\_ONLY\_ORDER\_PERMISSION + +* Users can only place reduce-only orders. + +### \-4088 NO\_PLACE\_ORDER\_PERMISSION + +* User cannot place orders currently. + +### \-4114 INVALID\_CLIENT\_TRAN\_ID\_LEN + +* clientTranId is not valid. +* The customer's tranId length should be less than 64 characters. + +### \-4115 DUPLICATED\_CLIENT\_TRAN\_ID + +* clientTranId is duplicated. +* The client's tranId should be unique within 7 days. + +### \-4118 REDUCE\_ONLY\_MARGIN\_CHECK\_FAILED + +* ReduceOnly Order failed. Please check your existing position and open orders + +### \-4131 MARKET\_ORDER\_REJECT + +* The counterparty's best price does not meet the PERCENT\_PRICE filter limit. + +### \-4135 INVALID\_ACTIVATION\_PRICE + +* Invalid activation price. + +### \-4137 QUANTITY\_EXISTS\_WITH\_CLOSE\_POSITION + +* Quantity must be zero when closePosition is true. + +### \-4138 REDUCE\_ONLY\_MUST\_BE\_TRUE + +* Reduce only must be true when closePosition is true. + +### \-4139 ORDER\_TYPE\_CANNOT\_BE\_MKT + +* Order type cannot be a market order if it cannot be canceled. + +### \-4140 INVALID\_OPENING\_POSITION\_STATUS + +* Invalid symbol status for opening position. + +### \-4141 SYMBOL\_ALREADY\_CLOSED + +* Trading pair has been delisted. + +### \-4142 STRATEGY\_INVALID\_TRIGGER\_PRICE + +* Rejected: Take Profit or Stop order would be triggered immediately. + +### \-4164 MIN\_NOTIONAL + +* Order notional must be at least 5.0 (unless you select Reduce Only) +* Order notional must be no smaller than %s (unless you choose Reduce Only) + +### \-4165 INVALID\_TIME\_INTERVAL + +* Invalid time interval +* Maximum time interval is %s days + +### \-4183 PRICE\_HIGHTER\_THAN\_STOP\_MULTIPLIER\_UP + +* Limit price cannot be higher than the cap of %s. +* Take-Profit/Stop-Loss price cannot be higher than the cap of %s. + +### \-4184 PRICE\_LOWER\_THAN\_STOP\_MULTIPLIER\_DOWN + +* Price is below the stop price limit. +* Take-Profit/Stop-Loss price must be above the trigger price × multiplier floor. +* Order price (limit or TP/SL) can't be below %s. diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-prediction-api-testnet.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-prediction-api-testnet.md" new file mode 100644 index 0000000..2faf56d --- /dev/null +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-prediction-api-testnet.md" @@ -0,0 +1,3073 @@ +# 基本信息 +## API 基本信息 +* 本篇列出接口的baseurl: **https://papi.asterdex-testnet.com** +* 所有接口的响应都是 JSON 格式。 +* 所有时间、时间戳均为UNIX时间,单位为**毫秒**。 + +## API Agent Address 设置 +* 很多接口需要API Key才可以访问. +* 设置API Key的同时,为了安全,建议设置IP访问白名单. +* **永远不要把你的API Agent Address/Private Key告诉给任何人** + + + +### 注意事项 +* TESTUSDT 或任何其他以 TEST 开头的交易对仅用于 Aster 的内部测试。请不要在这些以 TEST 开头的交易品种上进行交易。Aster 对因交易这些交易对而造成的资金损失不承担任何责任。但是,如果您遇到问题,您可以随时联系支持人员,我们将尽力帮助您收回资金。 + + +### HTTP 返回代码 +* HTTP `4XX` 错误码用于指示错误的请求内容、行为、格式。问题在于请求者。 +* HTTP `403` 错误码表示违反WAF限制(Web应用程序防火墙)。 +* HTTP `429` 错误码表示警告访问频次超限,即将被封IP。 +* HTTP `418` 表示收到429后继续访问,IP已经被封禁。 +* HTTP `5XX` 错误码用于指示Aster服务侧的问题。 + +### 接口错误代码 +* 使用接口 `/api/v3`, 每个接口都有可能抛出异常; +> API的错误代码返回形式如下: +```javascript +{ + "code": -1121, + "msg": "Invalid symbol." +} +``` + +### 接口的基本信息 + +* `GET` 方法的接口, 参数必须在 `query string`中发送。 +* `POST`, `PUT`, 和 `DELETE` 方法的接口,参数可以在内容形式为`application/x-www-form-urlencoded`的 `query string` 中发送,也可以在 `request body` 中发送。 +* 对参数的顺序不做要求。 + +### V3 Nonce 机制 + +* **Nonce** 用于校验请求的**有效性、唯一性和防重放**。客户端应使用**当前时间戳(微秒级)****作为 nonce**,且与服务端时间误差不超过 **10 秒**。 + +* 请求处理流程: + + 1. 若 nonce **已使用过** → 判定为**重复请求并拒绝** + 2. 否则判断是否**过旧** + +* 为提升性能,每个用户仅维护**最近 100 个 nonce**: + + * 若已满且新 nonce **小于当前最小值** → 判定为**过期并拒绝** + * 否则**移除最旧的 nonce**,加入新的 + +* 总体效果:**防重复、防过期,仅保留近期有效请求** + +--- +## 访问限制 +### 访问限制基本信息 + +* 在 `/api/v3/prediction/exchangeInfo` `rateLimits` 数组中包含与交易的有关REQUEST_WEIGHT和ORDERS速率限制相关的对象。这些在 `限制种类 (rateLimitType)` 下的 `枚举定义` 部分中进一步定义。 +* 违反任何一个速率限制时,将返回429。 + +### IP 访问限制 +* 每个请求的回报中包含一个`X-MBX-USED-WEIGHT-(intervalNum)(intervalLetter)`的头,其中包含当前IP所有请求的已使用权重。 +* 每一个接口均有一个相应的权重(weight),有的接口根据参数不同可能拥有不同的权重。越消耗资源的接口权重就会越大。 +* 收到429时,您有责任停止发送请求,不得滥用API。 +* **收到429后仍然继续违反访问限制,会被封禁IP,并收到418错误码** +* 频繁违反限制,封禁时间会逐渐延长,**从最短2分钟到最长3天**。 +* `Retry-After`的头会与带有418或429的响应发送,并且会给出**以秒为单位**的等待时长(如果是429)以防止禁令,或者如果是418,直到禁令结束。 +* **访问限制是基于IP的,而不是API Key** + + + + +### 下单频率限制 +* 每个成功的下单回报将包含一个`X-MBX-ORDER-COUNT-(intervalNum)(intervalLetter)`的头,其中包含当前账户已用的下单限制数量。 +* 当下单数超过限制时,会收到带有429但不含`Retry-After`头的响应。请检查 `GET api/v3/exchangeInfo` 的下单频率限制 (rateLimitType = ORDERS) 并等待封禁时间结束。 +* 被拒绝或不成功的下单并不保证回报中包含以上头内容。 +* **下单频率限制是基于每个账户计数的。** + +### WEB SOCKET 连接限制 + +* Websocket服务器每秒最多接受5个消息。消息包括: + * PING帧 + * PONG帧 + * JSON格式的消息, 比如订阅, 断开订阅. +* 如果用户发送的消息超过限制,连接会被断开连接。反复被断开连接的IP有可能被服务器屏蔽。 +* 单个连接最多可以订阅 **1024** 个Streams。 + + +## 接口鉴权类型 +* 每个接口都有自己的鉴权类型,鉴权类型决定了访问时应当进行何种鉴权 +* 如果需要使用API_WALLET鉴权,应当在请求体中添加signer +* 如果需要使用主地址鉴权,应当在请求体中添加user + +鉴权类型 | 描述 +------------ | ------------ +NONE | 不需要鉴权的接口 +SPOT_TRADE | 需要有效的signer和签名 +USER_DATA | 需要有效的signer和签名 +USER_STREAM | 需要有效的signer和签名 +MARKET_DATA | 不需要鉴权的接口 + + +### POST /api/v3/order 的示例 + +#### 示例 : 以下参数为api注册信息,user,signer,privateKey仅供示范(privateKey为signer的私钥) + + +Key | Value | Desc +------------ | ------------ | ------------ +user | 0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e | 登陆钱包地址 +signer | 0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0 | [点击这里获取](https://www.asterdex.com/zh-CN/api-wallet) +privateKey | 0x4fd0a42218f3eae43a6ce26d22544e986139a01e5b34a62db53757ffca81bae1 | [点击这里获取](https://www.asterdex.com/zh-CN/api-wallet) + +#### 示例 : nonce参数为当前系统微秒值,超过系统时间,或者落后系统时间超过10s为非法请求 +```python +#python +nonce = math.trunc(time.time()*1000000) +print(nonce) +#1748310859508867 +``` +```java +//java +Instant now = Instant.now(); +long microsecond = now.getEpochSecond() * 1000000 + now.getNano() / 1000; +``` + +#### 示例 : 下单 (方法以python为例) + +```python +import time +import urllib +import threading + +import requests +from eth_account.messages import encode_structured_data +from eth_account import Account + +typed_data = { + "types": { + "EIP712Domain": [ + {"name": "name", "type": "string"}, + {"name": "version", "type": "string"}, + {"name": "chainId", "type": "uint256"}, + {"name": "verifyingContract", "type": "address"} + ], + "Message": [ + { "name": "msg", "type": "string" } + ] + }, + "primaryType": "Message", + "domain": { + "name": "AsterSignTransaction", + "version": "1", + "chainId": 714, + "verifyingContract": "0x0000000000000000000000000000000000000000" + }, + "message": { + "msg": "$msg" + } +} + +headers = { + 'Content-Type': 'application/x-www-form-urlencoded', + 'User-Agent': 'PythonApp/1.0' +} +host = 'https://papi.asterdex-testnet.com' + +# config your user and agent info here +user = '*' +signer = '*' +private_key = "*" + +place_order = {"url":"/api/v3/order","method":"POST","params":{"symbol": "ASTERUSDT", "type": "LIMIT", "side": "BUY", + "timeInForce": "GTC", "quantity": "100", "price": "0.4"}} +_last_ms = 0 +_i = 0 +_nonce_lock = threading.Lock() + +def get_nonce(): + global _last_ms, _i + with _nonce_lock: + now_ms = int(time.time()) + + if now_ms == _last_ms: + _i += 1 + else: + _last_ms = now_ms + _i = 0 + + return now_ms * 1_000_000 + _i + +def send_by_url(api) : + my_dict = api['params'] + url = host + api['url'] + + my_dict['nonce'] = str(get_nonce()) + my_dict['signer'] = signer + + param = urllib.parse.urlencode(my_dict) + print(param) + typed_data['message']['msg'] = param + message = encode_structured_data(typed_data) + signed = Account.sign_message(message, private_key=private_key) + + url = url + '?' + param + '&signature=' + signed.signature.hex() + print(url) + res = requests.post(url, headers=headers) + + print(res.text) + +def send_by_body(api) : + my_dict = api['params'] + url = host +api['url'] + my_dict['nonce'] = str(get_nonce()) + my_dict['signer'] = signer + + param = urllib.parse.urlencode(my_dict) + typed_data['message']['msg'] = param + message = encode_structured_data(typed_data) + + signed = Account.sign_message(message, private_key=private_key) + print(signed.signature.hex()) + + my_dict['signature'] = signed.signature.hex() + + print(my_dict) + res = requests.post(url, data=my_dict, headers=headers) + + print(res.text) + +if __name__ == '__main__': + send_by_url(place_order) + # send_by_body(place_order) + +``` + +## 公开 API 参数 +### 术语 + +这里的术语适用于全部文档,建议特别是新手熟读,也便于理解。 + +* `base asset` 指一个交易对的交易对象,即写在靠前部分的资产名, 比如`BTCUSDT`, `BTC`是`base asset`。 +* `quote asset` 指一个交易对的定价资产,即写在靠后部分的资产名, 比如`BTCUSDT`, `USDT`是`quote asset`。 + +### 枚举定义 +**交易对状态 (状态 status):** + +* TRADING 交易中 + + +**交易对类型:** + +* SPOT 现货 + +**订单状态 (状态 status):** + +状态 | 描述 +-----------| -------------- +`NEW` | 订单被交易引擎接受 +`PARTIALLY_FILLED`| 部分订单被成交 +`FILLED` | 订单完全成交 +`CANCELED` | 用户撤销了订单 +`REJECTED` | 订单没有被交易引擎接受,也没被处理 +`EXPIRED` | 订单被交易引擎取消, 比如
LIMIT FOK 订单没有成交
市价单没有完全成交
交易所维护期间被取消的订单 + + +**订单类型 (orderTypes, type):** + +* LIMIT 限价单 +* MARKET 市价单 + +**订单返回类型 (newOrderRespType):** + +* ACK +* RESULT +* FULL + +**订单方向 (方向 side):** + +* BUY 买入 +* SELL 卖出 + +**有效方式 (timeInForce):** + +这里定义了订单多久能够失效 + +Status | Description +-----------| -------------- +`GTC` | 成交为止
订单会一直有效,直到被成交或者取消。 +`IOC` | 无法立即成交的部分就撤销
订单在失效前会尽量多的成交。 +`FOK` | 无法全部立即成交就撤销
如果无法全部成交,订单会失效。 +`GTX` | 直到挂单成交
限价只挂单。 + +**K线间隔:** + +m -> 分钟; h -> 小时; d -> 天; w -> 周; M -> 月 + +* 1s +* 1m +* 3m +* 5m +* 15m +* 30m +* 1h +* 2h +* 4h +* 6h +* 8h +* 12h +* 1d +* 3d +* 1w +* 1M + +新增了1s参数 + +**限制种类 (rateLimitType)** + +> REQUEST_WEIGHT +```json + { + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200 + } +``` + +> ORDERS +```json + { + "rateLimitType": "ORDERS", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 100 + } +``` + + +* REQUEST_WEIGHT 单位时间请求权重之和上限 + +* ORDERS 单位时间下单次数限制 + + +**限制间隔 (interval)** + +* MINUTE 分 + +--- +## 过滤器 +过滤器,即Filter,定义了一系列交易规则。 +共有两类,分别是针对交易对的过滤器`symbol filters`,和针对整个交易所的过滤器`exchange filters`(暂不支持) + +### 交易对过滤器   + +#### PRICE_FILTER 价格过滤器 + +> **/exchangeInfo 响应中的格式:** +```javascript + { + "minPrice": "556.72", + "maxPrice": "4529764", + "filterType": "PRICE_FILTER", + "tickSize": "0.01"   + } +``` + +`价格过滤器` 用于检测订单中 `price` 参数的合法性。包含以下三个部分: + +* `minPrice` 定义了 `price`/`stopPrice` 允许的最小值。 +* `maxPrice` 定义了 `price`/`stopPrice` 允许的最大值。 +* `tickSize` 定义了 `price`/`stopPrice` 的步进间隔,即price必须等于minPrice+(tickSize的整数倍) + +以上每一项均可为0,为0时代表这一项不再做限制。 + +逻辑伪代码如下: + +* `price` >= `minPrice` +* `price` <= `maxPrice` +* (`price`-`minPrice`) % `tickSize` == 0 + + +#### PERCENT_PRICE 价格振幅过滤器 + +> **/exchangeInfo 响应中的格式:** +```javascript + { + "multiplierDown": "0.9500", + "multiplierUp": "1.0500", + "multiplierDecimal": "4", + "filterType": "PERCENT_PRICE" +  } +``` + +`PERCENT_PRICE`过滤器基于指数价格来定义价格的有效范围。 + +为了通过"价格百分比","价格"必须符合以下条件: + +* `price` <=`indexPrice` *`multiplierUp` +* `price`> =`indexPrice` *`multiplierDown` + + +#### LOT_SIZE 订单尺寸 + +> **/exchangeInfo 响应中的格式:** +```javascript + { + "stepSize": "0.00100000", +   "filterType": "LOT_SIZE", + "maxQty": "100000.00000000", +   "minQty": "0.00100000" + } +``` + +Lots是拍卖术语,`LOT_SIZE` 过滤器对订单中的 `quantity` 也就是数量参数进行合法性检查。包含三个部分: + +* `minQty` 表示 `quantity` 允许的最小值。 +* `maxQty` 表示 `quantity` 允许的最大值。 +* `stepSize` 表示 `quantity` 允许的步进值。 + +逻辑伪代码如下: + +* `quantity` >= `minQty` +* `quantity` <= `maxQty` +* (`quantity`-`minQty`) % `stepSize` == 0 + + + + +#### MARKET_LOT_SIZE 市价订单尺寸 + +> ***/exchangeInfo 响应中的格式:** +```javascript + { + "stepSize": "0.00100000", +   "filterType": "MARKET_LOT_SIZE" + "maxQty": "100000.00000000", + "minQty": "0.00100000" + } +``` + + +`MARKET_LOT_SIZE`过滤器为交易对上的`MARKET`订单定义了`数量`(即拍卖中的"手数")规则。 共有3部分: + +* `minQty`定义了允许的最小`quantity`。 +* `maxQty`定义了允许的最大数量。 +* `stepSize`定义了可以增加/减少数量的间隔。 + +为了通过`market lot size`,`quantity`必须满足以下条件: + +* `quantity` >= `minQty` +* `quantity` <= `maxQty` +* (`quantity`-`minQty`) % `stepSize` == 0 + + +#### predictionEvents 预测事件 + +> ***/exchangeInfo 响应中的格式:** +```javascript +"predictionEvents": [ + { + "eventName": "ETH_UP_DOWN_7D", //预测事件 + "oracleSymbol": "ETHUSDT", //预测的SYMBOL + "predictionType": "UP_DOWN", //预测类型 + "sides": [ + "UP", + "DOWN" + ], //预测方向 + "period": "10080M", //预测周期 单位分钟 + "startTime": 1778476080000, //预测事件的开始时间 + "endTime": 1780376880000, //预测事件的结束时间 + "status": "LIVE", //预测事件的状态 + "currentRoundId": 3, //预测事件当前轮次 + "orderTypes": [ + "LIMIT", + "MARKET" + ], //预测事件的订单类型 + "timeInForce": [ + "GTC", + "IOC", + "FOK", + "GTX" + ], //预测事件的TIF + "liveRound":{ + "marketName": "USD1_UP_DOWN_5M_1778483280", //预测市场的名字 + "symbolIds": [ + "USD1_UP_DOWN_5M_1778483280_YUSDT", + "USD1_UP_DOWN_5M_1778483280_NUSDT" + ], // 预测市场的2个SYMBOL,Y代表上涨,N代表下跌 + "assetIds": [ + "USD1_UP_DOWN_5M_1778483280_Y", + "USD1_UP_DOWN_5M_1778483280_N" + ], // 预测市场的2个Asset,Y代表上涨,N代表下跌 + "roundId": 2, //预测市场的轮次ID + "tradingStartTime": 1778482970000, //预测市场的开始交易时间 + "tradingEndTime": 1778483520000, //预测市场的结束交易时间 + "windowStartTime": 1778483280000, //预测市场的窗口开始时间 + "windowEndTime": 1778483580000, //预测市场的窗口结束时间 + "roundStatus": "SETTLED", //预测市场的状态 + "openPrice": "0.99920000", //预测市场的开始价格 + "endPrice": "0.99910000", //预测市场的结束价格 + "winAsset": "USD1_UP_DOWN_5M_1778483280_N", //预测市场的获胜资产 如果上涨则是Y,如果下跌是N + "settleTime": 1778483582057, //预测市场的结算时间 + "settleHash": "0x3bc0aff52472dafd4b70d3423386a2dabf675fe7cd604e92391e2a4702cf0980" //预测市场的结算链上Hash + }, + "rounds": [ + { + "marketName": "USD1_UP_DOWN_5M_1778483280", //预测市场的名字 + "symbolIds": [ + "USD1_UP_DOWN_5M_1778483280_YUSDT", + "USD1_UP_DOWN_5M_1778483280_NUSDT" + ], // 预测市场的2个SYMBOL,Y代表上涨,N代表下跌 + "assetIds": [ + "USD1_UP_DOWN_5M_1778483280_Y", + "USD1_UP_DOWN_5M_1778483280_N" + ], // 预测市场的2个Asset,Y代表上涨,N代表下跌 + "roundId": 2, //预测市场的轮次ID + "tradingStartTime": 1778482970000, //预测市场的开始交易时间 + "tradingEndTime": 1778483520000, //预测市场的结束交易时间 + "windowStartTime": 1778483280000, //预测市场的窗口开始时间 + "windowEndTime": 1778483580000, //预测市场的窗口结束时间 + "roundStatus": "SETTLED", //预测市场的状态 + "openPrice": "0.99920000", //预测市场的开始价格 + "endPrice": "0.99910000", //预测市场的结束价格 + "winAsset": "USD1_UP_DOWN_5M_1778483280_N", //预测市场的获胜资产 如果上涨则是Y,如果下跌是N + "settleTime": 1778483582057, //预测市场的结算时间 + "settleHash": "0x3bc0aff52472dafd4b70d3423386a2dabf675fe7cd604e92391e2a4702cf0980" //预测市场的结算链上Hash + } + ] + } +] +``` + +`status` 为事件的状态 + +Status | Description +-----------| -------------- +`LIVE` | 正在运行。 +`CLOSED` | INVALID。 +`INVALID` | 无效。 + +`roundStatus` 为市场的状态 + +RoundStatus | Description +-----------| -------------- +`PREMARKET` | 预先准备好的市场(可以提前交易) +`TRADING` | 交易中的市场 +`SETTLED` | 已结算的市场 + +* 结算完成一段时间(24H)后,会自动下架,下架后的市场不再展示 +* `status` 为`CLOSED`或者`INVALID`的事件对应的市场,只能下reduceOnly的Market Sell订单 + +# 行情接口 + +## Noop + +> **Response:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +``POST /api/v3/noop`` + +通过此请求,可以高效取消已发送但仍在队列中且尚未完成链上操作的交易(Nonce需与该请求一致,不保证成功) + +**Weight:** +1 + +## 测试服务器连通性 +> **响应** +```javascript +{} +``` +`` +GET /api/v3/ping +`` + +测试能否联通 Rest API。 + +**权重:** +1 + +**参数:** +NONE + + +## 获取服务器时间 +> **响应** +```javascript +{ + "serverTime": 1499827319559 +} +``` +`` +GET /api/v3/time +`` + +测试能否联通 Rest API 并获取服务器时间。 + +**权重:** +1 + +**参数:** +NONE + + +## 交易规范信息 + +> **响应** + +```javascript     +{ + "timezone": "UTC", + "serverTime": 1756197279679, + "rateLimits": [{ + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 6000 + }, + { + "rateLimitType": "ORDERS", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 6000 + }, + { + "rateLimitType": "ORDERS", + "interval": "SECOND", + "intervalNum": 10, + "limit": 300 + } + ], + "exchangeFilters": [], + "assets": [{ + "asset": "USD" + }, { + "asset": "USDT" + }, + { + "asset": "BNB" + } + ], + "symbols": [{ + "status": "TRADING", + "baseAsset": "BNB", + "quoteAsset": "USDT", + "pricePrecision": 8, + "quantityPrecision": 8, + "baseAssetPrecision": 8, + "quotePrecision": 8, + "filters": [{ + "minPrice": "0.01000000", + "maxPrice": "100000", + "filterType": "PRICE_FILTER", + "tickSize": "0.01000000" + }, + { + "stepSize": "0.00100000", + "filterType": "LOT_SIZE", + "maxQty": "1000", + "minQty": "1" + }, + { + "stepSize": "0.00100000", + "filterType": "MARKET_LOT_SIZE", + "maxQty": "900000", + "minQty": "0.00100000" + }, + { + "limit": 200, + "filterType": "MAX_NUM_ORDERS" + }, + { + "minNotional": "5", + "filterType": "MIN_NOTIONAL" + }, + { + "maxNotional": "100", + "filterType": "MAX_NOTIONAL" + }, + { + "maxNotional": "100", + "minNotional": "5", + "avgPriceMins": 5, + "applyMinToMarket": true, + "filterType": "NOTIONAL", + "applyMaxToMarket": true + }, + { + "multiplierDown": "0", + "multiplierUp": "5", + "multiplierDecimal": "0", + "filterType": "PERCENT_PRICE" + }, + { + "bidMultiplierUp": "5", + "askMultiplierUp": "5", + "bidMultiplierDown": "0", + "avgPriceMins": 5, + "multiplierDecimal": "0", + "filterType": "PERCENT_PRICE_BY_SIDE", + "askMultiplierDown": "0" + } + ], + "orderTypes": [ + "LIMIT", + "MARKET", + "STOP", + "STOP_MARKET", + "TAKE_PROFIT", + "TAKE_PROFIT_MARKET" + ], + "timeInForce": [ + "GTC", + "IOC", + "FOK", + "GTX", + "HIDDEN" + ], + "symbol": "BNBUSDT", + "ocoAllowed": false + }] +} +``` + +`` +GET /api/v3/prediction/exchangeInfo +`` + +获取交易规则和交易对信息。 + +**权重:** +1 + +**参数:** +无 + + +## 深度信息 + +> **响应** + +```javascript +{ + "lastUpdateId": 1027024, + "E":1589436922972, // 消息时间 + "T":1589436922959, // 撮合引擎时间 + "bids": [ + [ + "4.00000000", // 价位 + "431.00000000" // 挂单量 + ] + ], + "asks": [ + [ + "4.00000200", + "12.00000000" + ] + ] +} +``` +`` +GET /api/v3/depth +`` + +**权重:** + +基于限制调整: + +限制 | 权重 +------------ | ------------ +5, 10, 20, 50 | 2 +100 | 5 +500 | 10 +1000 | 20 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +limit | INT | NO | 默认 100. 可选值:[5, 10, 20, 50, 100, 500, 1000] + + +## 近期成交列表 + +> **响应** + +```javascript +[ + { + "id": 657, + "price": "1.01000000", + "qty": "5.00000000", + "baseQty": "4.95049505", + "time": 1755156533943, + "isBuyerMaker": false + } +] +``` +`` +GET /api/v3/trades +`` + +获取近期成交 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +limit | INT | NO | 默认 500;最大1000 + + +## 查询历史成交 (MARKET_DATA) + +> **响应** + +```javascript +[ + { + "id": 1140, + "price": "1.10000000", + "qty": "7.27200000", + "baseQty": "6.61090909", + "time": 1756094288700, + "isBuyerMaker": false + } +] +``` +`` +GET /api/v3/historicalTrades +`` + +获取历史成交。 + +**权重:** +20 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +limit | INT | NO | 默认 500; 最大值 1000. +fromId | LONG | NO | 从哪一条成交id开始返回. 缺省返回最近的成交记录。 + + +## 近期成交(归集) + +> **响应** + +```javascript +[ + { + "a": 26129, // 归集成交ID + "p": "0.01633102", // 成交价 + "q": "4.70443515", // 成交量 + "f": 27781, // 被归集的首个成交ID + "l": 27781, // 被归集的末个成交ID + "T": 1498793709153, // 成交时间 + "m": true, // 是否为主动卖出单 + } +] +``` +`` +GET /api/v3/aggTrades +`` + +归集交易与逐笔交易的区别在于,同一价格、同一方向、同一时间的trade会被聚合为一条 + +**权重:** +20 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +fromId | LONG | NO | 从包含fromId的成交id开始返回结果 +startTime | LONG | NO | 从该时刻之后的成交记录开始返回结果 +endTime | LONG | NO | 返回该时刻为止的成交记录 +limit | INT | NO | 默认 500; 最大 1000. +* 如果发送startTime和endTime,间隔必须小于一小时。 +* 如果没有发送任何筛选参数(fromId, startTime,endTime),默认返回最近的成交记录 + + +## K线数据 + +> **响应** +```javascript +[ + [ + 1499040000000, // 开盘时间 + "0.01634790", // 开盘价 + "0.80000000", // 最高价 + "0.01575800", // 最低价 + "0.01577100", // 收盘价(当前K线未结束的即为最新价) + "148976.11427815", // 成交量 + 1499644799999, // 收盘时间 + "2434.19055334", // 成交额 + 308, // 成交笔数 + "1756.87402397", // 主动买入成交量 + "28.46694368", // 主动买入成交额 + ] +] +``` +`` +GET /api/v3/klines +`` + +每根K线代表一个交易对。 +每根K线的开盘时间可视为唯一ID + + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +interval | ENUM | YES | 详见枚举定义:K线间隔 +startTime | LONG | NO | +endTime | LONG | NO | +limit | INT | NO | 默认 500; 最大 1500. +* 如果未发送 startTime 和 endTime ,默认返回最近的交易。 + + + +## 24hr 价格变动情况 + +> **响应** + +```javascript +{ + "symbol": "BTCUSDT", + "priceChange": "-94.99999800", //24小时价格变动 + "priceChangePercent": "-95.960", //24小时价格变动百分比 + "weightedAvgPrice": "0.29628482", //加权平均价 + "prevClosePrice": "3.89000000", //上一次结束价格 + "lastPrice": "4.00000200", //最近一次成交价 + "lastQty": "200.00000000", //最近一次成交额 + "bidPrice": "866.66000000", //最高的买入价格 + "bidQty": "72.05100000", //最高的买入价格的数量 + "askPrice": "866.73000000", //最低的卖出价 + "askQty": "1.21700000", //最低的卖出价格的数量 + "openPrice": "99.00000000", //24小时内第一次成交的价格 + "highPrice": "100.00000000", //24小时最高价 + "lowPrice": "0.10000000", //24小时最低价 + "volume": "8913.30000000", //24小时成交量 + "quoteVolume": "15.30000000", //24小时成交额 + "openTime": 1499783499040, //24小时内,第一笔交易的发生时间 + "closeTime": 1499869899040, //24小时内,最后一笔交易的发生时间 + "firstId": 28385, // 首笔成交id + "lastId": 28460, // 末笔成交id + "count": 76, // 成交笔数 + "baseAsset": "BTC", //基础代币 + "quoteAsset": "USDT" //报价代币 +} +``` + +`` +GET /api/v3/ticker/24hr +`` + +24 小时滚动窗口价格变动数据。 请注意,不携带symbol参数会返回全部交易对数据,此时返回的数据为示例相应的数组,不仅数据庞大,而且权重极高 + +**权重:** +1 单一交易对; +**40** 交易对参数缺失; + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | NO | +* 请注意,不携带symbol参数会返回全部交易对数据 + +## 最新价格 + +> **响应** + +```javascript +{ + "symbol": "ADAUSDT", + "price": "1.30000000", + "time": 1649666690902 +} +``` + +> OR + +```javascript +[ + { + "symbol": "ADAUSDT", + "price": "1.30000000", + "time": 1649666690902 + } +] +``` + +`` +GET /api/v3/ticker/price +`` + +获取交易对最新价格 + +**权重:** +1 单一交易对; +**2** 交易对参数缺失; + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | NO | +* 不发送交易对参数,则会返回所有交易对信息 + + +## 当前最优挂单 +> **响应** +```javascript +{ + "symbol": "LTCBTC", + "bidPrice": "4.00000000", + "bidQty": "431.00000000", + "askPrice": "4.00000200", + "askQty": "9.00000000" + "time": 1589437530011 // 交易时间 +} +``` +> OR +```javascript +[ + { + "symbol": "LTCBTC", + "bidPrice": "4.00000000", + "bidQty": "431.00000000", + "askPrice": "4.00000200", + "askQty": "9.00000000", + "time": 1589437530011 // 交易时间 + } +] +``` + +`` +GET /api/v3/ticker/bookTicker +`` + +返回当前最优的挂单(最高买单,最低卖单) + +**权重:** +1 单一交易对; +**2** 交易对参数缺失; + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | NO | +* 不发送交易对参数,则会返回所有交易对信息 + +## 获取Symbol手续费 + +> **响应** + +```javascript +{ + "symbol": "APXUSDT", + "makerCommissionRate": "0.000200",     + "takerCommissionRate": "0.000700", + "settlementFeeRate": "0.000700" +} +``` +`` +GET /api/v3/commissionRate +`` + +获取Symbol手续费。 + +**权重:** +20 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | + + + + + +# 现货账户和交易接口 + + +## 下单 (TRADE) + +> **Response ACK:** + +```javascript +{ + "symbol": "BTCUSDT", // 交易对 + "orderId": 28, // 系统的订单ID + "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP", // 客户自己设置的ID + "updateTime": 1507725176595, // 交易的时间戳 + "price": "0.00000000", // 订单价格 + "avgPrice": "0.0000000000000000", //平均价格 + "origQty": "10.00000000", // 用户设置的原始订单数量 + "cumQty": "0", //累计数量 + "executedQty": "10.00000000", // 交易的订单数量 + "cumQuote": "10.00000000", // 累计交易的金额 + "status": "FILLED", // 订单状态 + "timeInForce": "GTC", // 订单的时效方式 + "stopPrice": "0", //触发价格 + "origType": "LIMIT", //触发前订单类型 + "type": "LIMIT", // 订单类型, 比如市价单,现价单等 + "side": "SELL", // 订单方向,买还是卖 +} +``` + +`` +POST /api/v3/order `` + +发送下单。 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +side | ENUM | YES | 详见枚举定义:订单方向 +type | ENUM | YES | 详见枚举定义:订单类型 +timeInForce | ENUM | NO | 详见枚举定义:有效方式 +quantity | DECIMAL | NO | +quoteOrderQty|DECIMAL|NO| +price | DECIMAL | NO | +newClientOrderId | STRING | NO | 客户自定义的唯一订单ID。 如果未发送,则自动生成 +stopPrice | DECIMAL | NO | 仅 `STOP`, `STOP_MARKET` , `TAKE_PROFIT`,`TAKE_PROFIT_MARKET` 需要此参数。 + +基于订单 `type`不同,强制要求某些参数: + +类型 | 强制要求的参数 +------------ | ------------ +`LIMIT` | `timeInForce`, `quantity`, `price` +`MARKET` | `quantity` 或 `quoteOrderQty` +`STOP`和`TAKE_PROFIT` | `quantity`, `price`, `stopPrice` +`STOP_MARKET`和`TAKE_PROFIT_MARKET` | `quantity`, `stopPrice` + +其他信息: + +* 下`MARKET` `SELL`市价单,用户通过`QUANTITY`控制想用市价单卖出的基础资产数量。 + * 比如在`BTCUSDT`交易对上下一个`MARKET` `SELL`市价单, 通过`QUANTITY`让用户指明想卖出多少BTC。 +* 下`MARKET` `BUY`的市价单,用户使用 `quoteOrderQty` 控制想用市价单买入的报价资产数量,`QUANTITY`将由系统根据市场流动性计算出来。 +  * 比如在`BTCUSDT`交易对上下一个`MARKET` `BUY`市价单, 通过`quoteOrderQty`让用户选择想使用多少USDT买入BTC。 +* 使用 `quoteOrderQty` 的市价单`MARKET`不会突破`LOT_SIZE`的限制规则; 报单会按给定的`quoteOrderQty`尽可能接近地被执行。 +* 除非之前的订单已经成交, 不然设置了相同的`newClientOrderId`订单会被拒绝。 + + + +## 撤销订单 (TRADE) + +> **响应** + +```javascript +{ + "symbol": "BTCUSDT", // 交易对 + "orderId": 28, // 系统的订单ID + "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP", // 客户自己设置的ID + "updateTime": 1507725176595, // 交易的时间戳 + "price": "0.00000000", // 订单价格 + "avgPrice": "0.0000000000000000", //平均价格 + "origQty": "10.00000000", // 用户设置的原始订单数量 + "cumQty": "0", //累计数量 + "executedQty": "10.00000000", // 交易的订单数量 + "cumQuote": "10.00000000", // 累计交易的金额 + "status": "CANCELED", // 订单状态 + "timeInForce": "GTC", // 订单的时效方式 + "stopPrice": "0", //触发价格 + "origType": "LIMIT", //触发前订单类型 + "type": "LIMIT", // 订单类型, 比如市价单,现价单等 + "side": "SELL", // 订单方向,买还是卖 +} +``` + +`` +DELETE /api/v3/order `` + +取消有效订单。 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +orderId | LONG | NO | +origClientOrderId | STRING | NO | + +`orderId` 或 `origClientOrderId` 必须至少发送一个 + +## 查询订单 (USER_DATA) + +> **响应** +```javascript +{ + "orderId": 38,   // 系统订单号 + "symbol": "ADA25SLP25",  // 交易对 + "status": "FILLED",  // 订单状态 + "clientOrderId": "afMd4GBQyHkHpGWdiy34Li",  // 用户自定义的订单号 + "price": "20",  // 委托价格 + "avgPrice": "12.0000000000000000",  // 平均成交价 + "origQty": "10",  // 原始委托数量 + "executedQty": "10",  // 成交量 + "cumQuote": "120",  // 成交金额 + "timeInForce": "GTC",  // 有效方法 + "type": "LIMIT",  // 订单类型 + "side": "BUY",  // 买卖方向 + "stopPrice": "0",  // 触发价 + "origType": "LIMIT",  // 触发前订单类型 + "time": 1649913186270,  // 订单时间 + "updateTime": 1649913186297  // 更新时间 +} +``` + +`` +GET /api/v3/order`` + +查询订单状态。 + +* 请注意,如果订单满足如下条件,不会被查询到: + * 订单的最终状态为 `CANCELED` 或者 `EXPIRED`, **并且** + * 订单没有任何的成交记录, **并且** + * 订单生成时间 + 7天 < 当前时间 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +orderId | LONG | NO | +origClientOrderId | STRING | NO | + +注意: + +* 至少需要发送 `orderId` 与 `origClientOrderId`中的一个 + + +## 查询当前挂单 (USER_DATA) + +> **响应** +```javascript +{ + "orderId": 38,   // 系统订单号 + "symbol": "ADA25SLP25",  // 交易对 + "status": "NEW",  // 订单状态 + "clientOrderId": "afMd4GBQyHkHpGWdiy34Li",  // 用户自定义的订单号 + "price": "20",  // 委托价格 + "avgPrice": "12.0000000000000000",  // 平均成交价 + "origQty": "10",  // 原始委托数量 + "executedQty": "10",  // 成交量 + "cumQuote": "120",  // 成交金额 + "timeInForce": "GTC",  // 有效方法 + "type": "LIMIT",  // 订单类型 + "side": "BUY",  // 买卖方向 + "stopPrice": "0",  // 触发价 + "origType": "LIMIT",  // 触发前订单类型 + "time": 1649913186270,  // 订单时间 + "updateTime": 1649913186297  // 更新时间 +} +``` + +`` +GET /api/v3/openOrder`` + +查询订单状态。 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +orderId | LONG | NO | +origClientOrderId | STRING | NO | + +注意: + +* 至少需要发送 `orderId` 与 `origClientOrderId`中的一个 + + +## 当前所有挂单 (USER_DATA) + +> **响应** + +```javascript +[ + { + "orderId": 349661, // 系统订单号 + "symbol": "BNBUSDT", // 交易对 + "status": "NEW", // 订单状态 + "clientOrderId": "LzypgiMwkf3TQ8wwvLo8RA", // 用户自定义的订单号 + "price": "1.10000000", // 委托价格 + "avgPrice": "0.0000000000000000", // 平均成交价 + "origQty": "5",  // 原始委托数量 + "executedQty": "0", // 成交量 + "cumQuote": "0", // 成交金额 + "timeInForce": "GTC", // 有效方法 + "type": "LIMIT", // 订单类型 + "side": "BUY", // 买卖方向 + "stopPrice": "0", // 触发价 + "origType": "LIMIT", // 触发前订单类型 + "time": 1756252940207, // 订单时间 + "updateTime": 1756252940207, // 更新时间 + } +] +``` + +`` +GET /api/v3/openOrders `` + +获取交易对的所有当前挂单, 请小心使用不带交易对参数的调用。 + +**权重:** +- 带symbol ***1*** +- 不带 ***40***   + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | NO | + +* 不带symbol参数,会返回所有交易对的挂单 + + + +## 取消当前所有挂单 (USER_DATA) + +> **响应** + +```javascript +{ + "code": 200, + "msg": "The operation of cancel all open order is done." +} +``` + +`` +DEL /api/v3/allOpenOrders `` + +**权重:** +- ***1*** + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +orderIdList | STRING | NO | id数组字符串 +origClientOrderIdList | STRING | NO | clientOrderId数组字符串 + + +## 查询所有订单 (USER_DATA) +> **响应** +```javascript +[ + { + "orderId": 349661, // 系统订单号 + "symbol": "BNBUSDT", // 交易对 + "status": "NEW", // 订单状态 + "clientOrderId": "LzypgiMwkf3TQ8wwvLo8RA", // 用户自定义的订单号 + "price": "1.10000000", // 委托价格 + "avgPrice": "0.0000000000000000", // 平均成交价 + "origQty": "5",  // 原始委托数量 + "executedQty": "0", // 成交量 + "cumQuote": "0", // 成交金额 + "timeInForce": "GTC", // 有效方法 + "type": "LIMIT", // 订单类型 + "side": "BUY", // 买卖方向 + "stopPrice": "0", // 触发价 + "origType": "LIMIT", // 触发前订单类型 + "time": 1756252940207, // 订单时间 + "updateTime": 1756252940207, // 更新时间 + } +] +``` + +`` +GET /api/v3/allOrders`` + +获取所有帐户订单; 有效,已取消或已完成。 + +* 请注意,如果订单满足如下条件,不会被查询到: + * 订单生成时间 + 7天 < 当前时间 + +**权重:** +5 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +orderId | LONG | NO | +startTime | LONG | NO | +endTime | LONG | NO | +limit | INT | NO | 默认 500; 最大 1000. + +* 查询时间范围最大不得超过7天 +* 默认查询最近7天内的数据 + + + +`` +GET /api/v3/prediction/transactionHistory`` +> **响应** + +```javascript +[ + { + "tranId": 1759115482304540227, //划转ID + "tradeId": null, //流水ID + "asset": "ASTER", //资产 + "symbol": "", //交易对 + "balanceDelta": "-500.00000000", //资金流数量,正数代表流入,负数代表流出 + "balanceInfo": "TRADE_SOURCE", //流水描述 + "time": 1759115482000, // 时间 + "type": "TRADE_SOURCE" //资金流类型 + } +] +``` + +查询交易流水 + +**权重:** +30 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +asset | STRING | NO | 资产 +type | STRING | NO | 类别 +startTime | LONG | NO | 开始时间 +endTime | LONG | NO | 结束时间 +limit | LONG | NO | 返回的结果集数量 默认值:100 最大值:1000 + +注意: + +* `type` 取值 `TRADE_TARGET`,`TRADE_SOURCE`,`TRANSFER_SPOT_TO_FUTURE`,`TRANSFER_FUTURE_TO_SPOT`,`TRANSFER_SPOT_TO_SPOT`,`AIRDROP`,`DIVIDEND`,`TRANSFER_REFUND`,`INTERNAL_TRANSFER`,`TRANSFER`,`SWAP`,`COMMISSION_REBATE`,`CASH_BACK`,`STAKING_WITHDRAW`, `STAKING_CLAIM`, `STAKING_DELEGATE`,`PREDICTION_CLAIM`,`PREDICTION_USER_REBATE`,`PREDICTION_SETTLE`,`PREDICTION_SETTLE_FEE`,`PREDICTION_MINT`,`PREDICTION_BURN` 中的一种 +* 如果`startTime` 和 `endTime` 均未发送, 只会返回最近7天的数据。 + +## 期货现货互转 (TRADE) + +> **响应:** + +```javascript +{ + "tranId": 21841, //交易id + "status": "SUCCESS" //状态 +} +``` + +`` +POST /api/v3/asset/wallet/transfer `` + +**权重:** +5 + +**参数:** + + +名称 | 类型 | 是否必需 | 描述 +---------------- | ------- | -------- | ---- +amount | DECIMAL | YES | 数量 +asset | STRING | YES | 资产 +clientTranId | STRING | YES | 交易id +kindType | STRING | YES | 交易类型 + +注意: +* kindType 取值为FUTURE_SPOT(期货转现货),SPOT_FUTURE(现货转期货) + +## 预测市场铸造 (TRADE) + +> **响应** + +```javascript +{ + "clientOrderId": "xxx", // 客户自定义订单ID + "quoteAmount": "10.00000000", // 花费的报价资产总量 + "yesPrice": "0.55000000", // 铸造时YES代币的价格 + "noPrice": "0.45000000", // 铸造时NO代币的价格(yesPrice + noPrice = 1) + "pairCount": "10.00000000" // 已铸造的YES+NO代币对数量 +} +``` + +`` +POST /api/v3/prediction/mint`` + +为预测市场铸造 YES+NO 代币对。铸造时系统按当前市场价格扣除等值报价资产,同时向账户发放等量的 YES 和 NO 代币。 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | 预测市场的 YES 代币交易对 +quantity | DECIMAL | YES | 铸造的 YES+NO 代币对数量 +newClientOrderId | STRING | NO | 客户自定义的唯一订单ID,若不填则自动生成 + +注意: +* `symbol` 必须是有效的预测市场代币交易对,且状态为 `TRADING` 或 `PENDING_TRADING` +* `quantity` 表示同时铸造的 YES 和 NO 代币对数量,铸造后账户将获得等量的 YES 代币和 NO 代币 +* `yesPrice` + `noPrice` = 1(报价资产单位) + + +## 预测市场销毁 (TRADE) + +> **响应** + +```javascript +{ + "clientOrderId": "xxx", // 客户自定义订单ID + "quoteAmount": "9.80000000", // 销毁后返还的报价资产总量 + "yesPrice": null, // 销毁操作不返回价格 + "noPrice": null, // 销毁操作不返回价格 + "pairCount": "10.00000000" // 已销毁的YES+NO代币对数量 +} +``` + +`` +POST /api/v3/prediction/burn`` + +销毁等量的 YES+NO 代币对,赎回相应的报价资产。账户需同时持有等量的 YES 代币和 NO 代币才可销毁。 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | 预测市场的 YES 代币交易对 +quantity | DECIMAL | YES | 销毁的 YES+NO 代币对数量 +newClientOrderId | STRING | NO | 客户自定义的唯一订单ID,若不填则自动生成 + +注意: +* `symbol` 必须是有效的预测市场代币交易对,且状态为 `TRADING`、`PENDING_TRADING` 或 `CLOSED` +* `quantity` 表示同时销毁的 YES 和 NO 代币对数量,账户需同时持有对应数量的 YES 代币和 NO 代币 +* 销毁操作响应中 `yesPrice` 和 `noPrice` 为 null +* 市场关闭(`CLOSED`)后仍可进行销毁操作 + + +## 查询预测市场当前仓位 (USER_DATA) + +> **响应** +```javascript +[ + { + "marketName": "BTC_UP_DOWN_20260512", // 预测市场名称 + "symbol": "BTC_UP_DOWN_20260512YES", // 交易对 + "assetName": "USDT", // 结算资产 + "type": "YES", // 持仓方向: "YES" 或 "NO" + "openAvgPrice": "0.65000000", // 开仓均价 + "cumQty": "100.00000000", // 持仓总数量 + "closeAvgPrice": "0.00000000", // 平仓均价(尚未平仓则为0) + "realizedPnl": "0.00000000", // 已实现盈亏 + "closeQty": "0.00000000", // 已平仓数量 + "insertTime": 1747000000000, // 开仓时间(毫秒时间戳) + "commissionFee": "0.10000000", // 手续费 + "commissionAsset": "USDT", // 手续费资产 + "balance": "65.00000000", // 仓位价值(持仓数量 × 开仓均价) + "availableBalance": "65.00000000", // 可用余额 + } +] +``` + +`` +GET /api/v3/prediction/positions +`` + +查询当前账户的预测市场持仓列表。 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | NO | 交易对,不传则返回所有持仓 +signer | STRING | YES | API钱包地址 +nonce | STRING | YES | 当前时间的微秒值 +signature | STRING | YES | 签名 + + +## 查询预测市场历史仓位 (USER_DATA) + +> **响应** +```javascript +[ + { + "marketName": "BTC_UP_DOWN_20260501", // 预测市场名称 + "symbol": "BTC_UP_DOWN_20260501YES", // 交易对 + "asset": "USDT", // 结算资产 + "type": "YES", // 持仓方向: "YES" 或 "NO" + "openAvgPrice": "0.72000000", // 开仓均价 + "cumQty": "200.00000000", // 持仓总数量 + "closeAvgPrice": "1.00000000", // 平仓均价 + "realizedPnl": "56.00000000", // 已实现盈亏 + "closeQty": "200.00000000", // 已平仓数量 + "insertTime": 1746000000000, // 开仓时间(毫秒时间戳) + "closeTime": 1746086400000, // 平仓/结算时间(毫秒时间戳) + "status": "settled", // 仓位状态: "close"(手动平仓)或 "settled"(市场结算) + "commissionFee": "0.10000000", // 手续费 + "commissionAsset": "USDT", // 手续费资产 + "settleFee": "2.00000000", // 结算手续费(仅 status 为 "settled" 时存在) + "settleAsset": "USDT", // 结算手续费资产 + } +] +``` + +`` +GET /api/v3/prediction/positionHistories +`` + +查询当前账户的预测市场历史仓位列表(已平仓或已结算)。 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | NO | 交易对,不传则返回所有历史仓位 +startTime | LONG | NO | 开始时间(毫秒时间戳) +endTime | LONG | NO | 结束时间(毫秒时间戳) +limit | INT | NO | 返回数量,默认100,最大1000 +signer | STRING | YES | API钱包地址 +nonce | STRING | YES | 当前时间的微秒值 +signature | STRING | YES | 签名 + +注意: +* `startTime` 与 `endTime` 同时传入时,`startTime` 不得大于 `endTime` +* `limit` 取值范围为 1 ~ 1000,默认值为 100 +* `status` 字段说明: `close` 表示用户手动平仓,`settled` 表示预测市场到期结算 + +## 查询预测市场结算历史 (USER_DATA) + +> **响应** +```javascript +[ + { + "marketName": "BTC_UP_DOWN_20260501", // 预测市场名称 + "asset": "BTC_UP_DOWN_20260501YES", // 代币资产(YES 或 NO 代币) + "symbol": "BTC_UP_DOWN_20260501YES", // 交易对 + "marketStartTime": 1746000000000, // 市场开始时间(毫秒时间戳) + "marketEndTime": 1746086400000, // 市场结束/结算时间(毫秒时间戳) + "shareAmount": "200.00000000", // 结算时持有的份额数量 + "settleAsset": "USDT", // 结算资产 + "settleAmount": "200.00000000", // 结算获得金额 + "settleFeeAmount": "2.00000000", // 结算手续费 + "entryPrice": "0.72000000", // 平均入场价格 + "settlePrice": "1.00000000", // 最终结算价格 + "realizedPnl": "56.00000000", // 结算后已实现盈亏 + "status": "settled" // 结算状态 + } +] +``` + +`` +GET /api/v3/prediction/settlementHistories +`` + +查询当前账户的预测市场结算历史(已到期结算的市场)。 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | NO | 交易对,不传则返回所有结算记录 +startTime | LONG | NO | 按市场开始时间过滤(毫秒时间戳) +endTime | LONG | NO | 按市场结束时间过滤(毫秒时间戳) +limit | INT | NO | 返回数量,默认100,最大1000 +signer | STRING | YES | API钱包地址 +nonce | STRING | YES | 当前时间的微秒值 +signature | STRING | YES | 签名 + +注意: +* `startTime` 与 `endTime` 同时传入时,`startTime` 不得大于 `endTime` +* `limit` 取值范围为 1 ~ 1000,默认值为 100 +* `settleAmount` 为结算总收入,`realizedPnl` = `settleAmount` 减去成本 +* `settleFeeAmount` 从结算收入中扣除 + +## 现货提现手续费 (NONe) +> **响应** +```javascript +{ + "tokenPrice": 1.00019000, + "gasCost": 0.5000, + "gasUsdValue": 0.5 +} +``` + +`` +GET /api/v3/aster/withdraw/estimateFee +`` + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +chainId | STRING | YES | +asset | STRING | YES | + +注意: +* chainId: 1(ETH),56(BSC),42161(Arbi) +* gasCost: 提现所需的最少数量的手续费 + +## 现货提现 (USER_DATA) +> **响应** +```javascript +{ + "withdrawId": "1014729574755487744", + "hash":"0xa6d1e617a3f69211df276fdd8097ac8f12b6ad9c7a49ba75bbb24f002df0ebb" +} +``` + +`` +POST /api/v3/aster/user-withdraw`` + +**权重:** +5 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +chainId | STRING | YES | +asset | STRING | YES | +amount | STRING | YES | +fee | STRING | YES | +receiver | STRING | YES | +nonce | STRING | YES | 当前时间的微秒值 +userSignature | STRING | YES | + +注意: +* chainId: 1(ETH),56(BSC),42161(Arbi) +* receiver : 当前账户的地址 +* 如果期货余额不足,会从spot账户划转到期货账户,进行提现 +* userSignature demo + +```shell +const domain = { + name: 'Aster', + version: '1', + chainId: 56, + verifyingContract: ethers.ZeroAddress, + } + +const currentTime = Date.now() * 1000 + +const types = { + Action: [ + {name: "type", type: "string"}, + {name: "destination", type: "address"}, + {name: "destination Chain", type: "string"}, + {name: "token", type: "string"}, + {name: "amount", type: "string"}, + {name: "fee", type: "string"}, + {name: "nonce", type: "uint256"}, + {name: "aster chain", type: "string"}, + ], + } + const value = { + 'type': 'Withdraw', + 'destination': '0xD9cA6952F1b1349d27f91E4fa6FB8ef67b89F02d', + 'destination Chain': 'BSC', + 'token': 'USDT', + 'amount': '10.123400', + 'fee': '1.234567891', + 'nonce': currentTime, + 'aster chain': 'Mainnet', + } + + +const signature = await signer.signTypedData(domain, types, value) +``` + +## 账户信息 (USER_DATA) +> **响应** +```javascript +{ + "feeTier": 0, + "canTrade": true, + "canDeposit": true, + "canWithdraw": true, + "canBurnAsset": true, + "updateTime": 0, +   "balances": [ + { + "asset": "BTC", + "free": "4723846.89208129", + "locked": "0.00000000" + }, + { + "asset": "LTC", + "free": "4763368.68006011", + "locked": "0.00000000" + } + ] +} +``` + +`` +GET /api/v3/account`` + +获取当前账户信息。 + +**权重:** +5 + +**参数:** + +名称 | 类型 | 是否必需| 描述 +------------ | ------------ | ------------ | ------------ + + +## 账户成交历史 (USER_DATA) +> **响应** +```javascript +[ + { + "symbol": "BNBUSDT", + "id": 1002, + "orderId": 266358, + "side": "BUY", + "price": "1", + "qty": "2", + "quoteQty": "2", + "commission": "0.00105000", + "commissionAsset": "BNB", + "time": 1755656788798, + "counterpartyId": 19, + "createUpdateId": null, + "maker": false, + "buyer": true + } +] +``` + +`` +GET /api/v3/userTrades `` + +获取账户指定交易对的成交历史 + +**权重:** +5 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | NO | +orderId|LONG|NO| 必须要和参数`symbol`一起使用. +startTime | LONG | NO | +endTime | LONG | NO | +fromId | LONG | NO | 起始Trade id。 默认获取最新交易。 +limit | INT | NO | 默认 500; 最大 1000. + +* 如果`startTime` 和 `endTime` 均未发送, 只会返回最近7天的数据。 +* startTime 和 endTime 的最大间隔为7天 +* 不能同时传`fromId`与`startTime` 或 `endTime` +       + + + + +--- +# Websocket 行情推送 + +* 本篇所列出的所有wss接口的baseurl为: **wss://sstream.asterdex.com** +* Streams有单一原始 stream 或组合 stream +* 单一原始 streams 格式为 **/ws/\** +* 组合streams的URL格式为 **/stream?streams=\/\/\** +* 订阅组合streams时,事件payload会以这样的格式封装: **{"stream":"\","data":\}** +* stream名称中所有交易对均为 **小写** +* 每个到 **sstream.asterdex.com** 的链接有效期不超过24小时,请妥善处理断线重连。 +* 每3分钟,服务端会发送ping帧,客户端应当在10分钟内回复pong帧,否则服务端会主动断开链接。允许客户端发送不成对的pong帧(即客户端可以以高于10分钟每次的频率发送pong帧保持链接)。 + +## 实时订阅/取消数据流 + +* 以下数据可以通过websocket发送以实现订阅或取消订阅数据流。示例如下。 +* 响应内容中的`id`是无符号整数,作为往来信息的唯一标识。 +* 如果相应内容中的 `result` 为 `null`,表示请求发送成功。 + + +### 订阅一个信息流 +> **响应** + ```javascript + { + "result": null, + "id": 1 + } + ``` +* **请求** + { + "method": "SUBSCRIBE", + "params": + [ + "btcusdt@aggTrade", + "btcusdt@depth" + ], + "id": 1 + } + + +### 取消订阅一个信息流 + +> **响应** + + ```javascript + { + "result": null, + "id": 312 + } + ``` + +* **请求** + { + "method": "UNSUBSCRIBE", + "params": + [ + "btcusdt@depth" + ], + "id": 312 + } + + +### 已订阅信息流 + +> **响应** + + ```javascript + { + "result": [ + "btcusdt@aggTrade" + ], + "id": 3 + } + ``` + +* **请求** + + { + "method": "LIST_SUBSCRIPTIONS", + "id": 3 + } + + +### 设定属性 +当前,唯一可以设置的属性是设置是否启用`combined`("组合")信息流。 +当使用`/ws/`("原始信息流")进行连接时,combined属性设置为`false`,而使用 `/stream/`进行连接时则将属性设置为`true`。 + +> **响应** + + ```javascript +{ + "result": null, + "id": 5 +} + ``` + +* **请求** + { + "method": "SET_PROPERTY", + "params": + [ + "combined", + true + ], + "id": 5 + } + + +### 检索属性 + +> **响应** + ```javascript + { + "result": true, // Indicates that combined is set to true. + "id": 2 + } + ``` + +* **请求** + + { + "method": "GET_PROPERTY", + "params": + [ + "combined" + ], + "id": 2 + } + + +###错误信息 + +错误信息 | 描述 +---|--- +{"code": 0, "msg": "Unknown property"} | `SET_PROPERTY` 或 `GET_PROPERTY`中应用的参数无效 +{"code": 1, "msg": "Invalid value type: expected Boolean", "id": '%s'} | 仅接受`true`或`false` +{"code": 2, "msg": "Invalid request: property name must be a string"}| 提供的属性名无效 +{"code": 2, "msg": "Invalid request: request ID must be an unsigned integer"}| 参数`id`未提供或`id`值是无效类型 +{"code": 2, "msg": "Invalid request: unknown variant %s, expected one of `SUBSCRIBE`, `UNSUBSCRIBE`, `LIST_SUBSCRIPTIONS`, `SET_PROPERTY`, `GET_PROPERTY` at line 1 column 28"} | 错字提醒,或提供的值不是预期类型 +{"code": 2, "msg": "Invalid request: too many parameters"}| 数据中提供了不必要参数 +{"code": 2, "msg": "Invalid request: property name must be a string"} | 未提供属性名 +{"code": 2, "msg": "Invalid request: missing field `method` at line 1 column 73"} | 数据未提供`method` +{"code":3,"msg":"Invalid JSON: expected value at line %s column %s"} | JSON 语法有误. + + +## 归集交易流 + + +> **Payload:** +```javascript +{ + "e": "aggTrade", // 事件类型 + "E": 123456789, // 事件时间 + "s": "BNBBTC", // 交易对 + "a": 12345, // 归集交易ID + "p": "0.001", // 成交价格 + "q": "100", // 成交数量 + "f": 100, // 被归集的首个交易ID + "l": 105, // 被归集的末次交易ID + "T": 123456785, // 成交时间 + "m": true, // 买方是否是做市方。如true,则此次成交是一个主动卖出单,否则是一个主动买入单。 +} +``` + +归集交易 stream 推送交易信息,是对单一订单的集合。 + +**Stream 名称:** `@aggTrade` + +**Update Speed:** 实时 + + +## 逐笔交易 + + +> **Payload:** +```javascript +{ + "e": "trade", // 事件类型 + "E": 123456789, // 事件时间 + "s": "BNBBTC", // 交易对 + "t": 12345, // 交易ID + "p": "0.001", // 成交价格 + "q": "100", // 成交数量 + "T": 123456785, // 成交时间 + "m": true, // 买方是否是做市方。如true,则此次成交是一个主动卖出单,否则是一个主动买入单。 +} +``` + +**Stream Name:** `@trade` + +逐笔交易推送每一笔成交的信息。**成交**,或者说交易的定义是仅有一个吃单者与一个挂单者相互交易 + + +## K线 Streams +> **Payload:** +```javascript +{ + "e": "kline", // 事件类型 + "E": 123456789, // 事件时间 + "s": "BNBBTC", // 交易对 + "k": { + "t": 123400000, // 这根K线的起始时间 + "T": 123460000, // 这根K线的结束时间 + "s": "BNBBTC", // 交易对 + "i": "1m", // K线间隔 + "f": 100, // 这根K线期间第一笔成交ID + "L": 200, // 这根K线期间末一笔成交ID + "o": "0.0010", // 这根K线期间第一笔成交价 + "c": "0.0020", // 这根K线期间末一笔成交价 + "h": "0.0025", // 这根K线期间最高成交价 + "l": "0.0015", // 这根K线期间最低成交价 + "v": "1000", // 这根K线期间成交量 + "n": 100, // 这根K线期间成交笔数 + "x": false, // 这根K线是否完结(是否已经开始下一根K线) + "q": "1.0000", // 这根K线期间成交额 + "V": "500", // 主动买入的成交量 + "Q": "0.500", // 主动买入的成交额 + "B": "123456" // 忽略此参数 + } +} +``` + +K线stream逐秒推送所请求的K线种类(最新一根K线)的更新。 + +**Stream Name:** `@kline_` + +**Update Speed:** 2000ms + +**K线图间隔参数:** + +m -> 分钟; h -> 小时; d -> 天; w -> 周; M -> 月 + +* 1m +* 3m +* 5m +* 15m +* 30m +* 1h +* 2h +* 4h +* 6h +* 8h +* 12h +* 1d +* 3d +* 1w +* 1M + + +## 按 Symbol 的精简Ticker + +> **Payload:** +```javascript + { + "e": "24hrMiniTicker", // 事件类型 + "E": 123456789, // 事件时间 + "s": "BNBBTC", // 交易对 + "c": "0.0025", // 最新成交价格 + "o": "0.0010", // 24小时前开始第一笔成交价格 + "h": "0.0025", // 24小时内最高成交价 + "l": "0.0010", // 24小时内最低成交价 + "v": "10000", // 成交量 + "q": "18" // 成交额 + } +``` + +按Symbol刷新的最近24小时精简ticker信息 + +**Stream 名称:** `@miniTicker` + +**Update Speed:** 1000ms + + +## 全市场所有Symbol的精简Ticker + +> **Payload:** +```javascript +[ + { + // 数组每一个元素对应一个交易对,内容与 \@miniTicker相同 + } +] +``` + +同上,只是推送所有交易对.需要注意的是,只有更新的ticker才会被推送. + +**Stream名称:** !miniTicker@arr + +**Update Speed:** 1000ms + +## 按Symbol的完整Ticker + +> **Payload:** +```javascript +{ + "e": "24hrTicker", // 事件类型 + "E": 123456789, // 事件时间 + "s": "BNBBTC", // 交易对 + "p": "0.0015", // 24小时价格变化 + "P": "250.00", // 24小时价格变化(百分比) + "w": "0.0018", // 平均价格 + "c": "0.0025", // 最新成交价格 + "Q": "10", // 最新成交交易的成交量 + "o": "0.0010", // 整整24小时前,向后数的第一次成交价格 + "h": "0.0025", // 24小时内最高成交价 + "l": "0.0010", // 24小时内最低成交价 + "v": "10000", // 24小时内成交量 + "q": "18", // 24小时内成交额 + "O": 0, // 统计开始时间 + "C": 86400000, // 统计结束时间 + "F": 0, // 24小时内第一笔成交交易ID + "L": 18150, // 24小时内最后一笔成交交易ID + "n": 18151 // 24小时内成交数 +} +``` + +每秒推送单个交易对的过去24小时滚动窗口标签统计信息。 + +**Stream 名称:** `@ticker` + +**Update Speed:** 1000ms + +## 全市场所有交易对的完整Ticker + +> **Payload:** +```javascript +[ + { + // Same as @ticker payload + } +] +``` + +推送全市场所有交易对刷新的24小时完整ticker信息。需要注意的是,没有更新的ticker不会被推送。 + +**Stream Name:** `!ticker@arr` + +**Update Speed:** 1000ms + + +## 按Symbol的最优挂单信息 + +> **Payload:** +```javascript +{ + "u":400900217, // order book updateId + "s":"BNBUSDT", // 交易对 + "b":"25.35190000", // 买单最优挂单价格 + "B":"31.21000000", // 买单最优挂单数量 + "a":"25.36520000", // 卖单最优挂单价格 + "A":"40.66000000" // 卖单最优挂单数量 +} +``` + +实时推送指定交易对最优挂单信息 + +**Stream Name:** `@bookTicker` + +**Update Speed:** 实时 + +## 全市场最优挂单信息 +> **Payload:** +```javascript +{ + // 同 @bookTicker payload +} +``` + +实时推送所有交易对最优挂单信息 + +**Stream Name:** `!bookTicker` + +**Update Speed:** 实时 + + +## 有限档深度信息 + +> **Payload:** +```javascript +{ + "e": "depthUpdate", // Event type + "E": 123456789, // Event time + "T": 123456788, // Transaction time + "s": "BTCUSDT", // Symbol + "U": 100, // First update ID in event + "u": 120, // Final update ID in event + "pu": 99, // Final update Id in last stream(ie `u` in last stream) +  "bids": [ // Bids to be updated + [ + "0.0024", // Price level to be updated + "10" // Quantity + ] + ], + "asks": [ // Asks to be updated + [ + "0.0026", // Price level to be updated + "100" // Quantity + ] + ] +} +``` + +每秒或每100毫秒推送有限档深度信息。levels表示几档买卖单信息, 可选 5/10/20档 + +**Stream Names:** `@depth` 或 `@depth@100ms`. + +**Update Speed:** 1000ms 或 100ms + + +## 增量深度信息 +> **Payload:** +```javascript +{ + "e": "depthUpdate", // Event type + "E": 123456789, // Event time + "T": 123456788, // Transaction time + "s": "BTCUSDT", // Symbol + "U": 100, // First update ID in event + "u": 120, // Final update ID in event + "pu": 99, // Final update Id in last stream(ie `u` in last stream) + "b": [ // Bids to be updated + [ + "5.4", // Price level to be updated + "10" // Quantity + ] + ], + "a": [ // Asks to be updated + [ + "5.6", // Price level to be updated + "100" // Quantity + ] + ] +} +``` + +每秒或每100毫秒推送orderbook的变化部分(如果有) + +**Stream Name:** `@depth` 或 `@depth@100ms` + +**Update Speed:** 1000ms 或 100ms + +## 如何正确在本地维护一个orderbook副本 +1. 订阅 **wss://sstream.asterdex.com/ws/bnbbtc@depth** +2. 开始缓存收到的更新。同一个价位,后收到的更新覆盖前面的。 +3. 访问Rest接口 **https://papi.asterdex-testnet.com/api/v3/depth?symbol=BNBBTC&limit=1000** 获得一个1000档的深度快照 +4. 将目前缓存到的信息中`u` <= 步骤3中获取到的快照中的`lastUpdateId`的部分丢弃(丢弃更早的信息,已经过期)。 +5. 将深度快照中的内容更新到本地orderbook副本中,并从websocket接收到的第一个`U` <= `lastUpdateId`+1 **且** `u` >= `lastUpdateId`+1 的event开始继续更新本地副本。 +6. 每一个新event的`U`应该恰好等于上一个event的`u`+1,否则可能出现了丢包,请从step3重新进行初始化。 +7. 每一个event中的挂单量代表这个价格目前的挂单量**绝对值**,而不是相对变化。 +8. 如果某个价格对应的挂单量为0,表示该价位的挂单已经撤单或者被吃,应该移除这个价位。 + + + + + + +# Websocket账户信息推送 + +* 本篇所列出API接口的base url : **https://papi.asterdex-testnet.com** +* 用于订阅账户数据的 `listenKey` 从创建时刻起有效期为60分钟 +* 可以通过 `PUT` 一个 `listenKey` 延长60分钟有效期 +* 可以通过`DELETE`一个 `listenKey` 立即关闭当前数据流,并使该`listenKey` 无效 +* 在具有有效`listenKey`的帐户上执行`POST`将返回当前有效的`listenKey`并将其有效期延长60分钟 +* websocket接口的baseurl: **wss://sstream.asterdex.com** +* U订阅账户数据流的stream名称为 **/ws/\** +* 每个链接有效期不超过24小时,请妥善处理断线重连。 + + +## Listen Key(现货账户) + +### 生成 Listen Key (USER_STREAM) + +> **响应** +```javascript +{ + "listenKey": "pqia91ma19a5s61cv6a81va65sdf19v8a65a1a5s61cv6a81va65sdf19v8a65a1" +} +``` + +`` +POST /api/v3/listenKey +`` + +开始一个新的数据流。除非发送 keepalive,否则数据流于60分钟后关闭。如果该帐户具有有效的`listenKey`,则将返回该`listenKey`并将其有效期延长60分钟。 + +**权重:** +1 + +**参数:** +NONE + +### 延长 Listen Key 有效期 (USER_STREAM) + +> **响应** +```javascript +{} +``` + +`` +PUT /api/v3/listenKey +`` + +有效期延长至本次调用后60分钟,建议每30分钟发送一个 ping 。 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +listenKey | STRING | YES + + +### 关闭 Listen Key (USER_STREAM) + +> **响应** +```javascript +{} +``` + +`` +DELETE /api/v3/listenKey +`` + +关闭用户数据流。 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +listenKey | STRING | YES + + +## Payload: 账户更新 + +每当帐户余额发生更改时,都会发送一个事件`outboundAccountPosition`,其中包含可能由生成余额变动的事件而变动的资产。 + +> **Payload** +```javascript +{ + "B":[// 余额 + { + "a":"SLP25",   // 资产名称 + "f":"10282.42029415",   // 可用余额 + "l":"653.00000001"   // 冻结余额 + }, + { + "a":"ADA25", + "f":"9916.96229880", + "l":"34.00510000" + } + ], + "e":"outboundAccountPosition",   // 事件类型 + "T":1649926447190,   // 账户末次更新时间戳 + "E":1649926447205   // 事件时间 + "m":"WITHDRAW" // 事件推出原因 +} +``` + + +## Payload: 订单更新 + +订单通过`executionReport`事件进行更新。 + +> **Payload** + +```javascript +{ + "s":"ADA25SLP25",   // 交易对 + "c":"Xzh0gnxT41PStbwqOtXnjD",  // 客户端自定订单ID + "S":"SELL",   // 订单方向 + "o":"LIMIT",   // 订单类型 + "f":"GTC",   // 有效方式 + "q":"10.001000",   // 订单原始数量 + "p":"19.1000000000",   // 订单原始价格 + "ap":"19.0999999955550656", //平均价格 + "P":"0",  // 条件订单触发价格 + "x":"TRADE",   // 本次事件的具体执行类型 + "X":"PARTIALLY_FILLED",   // 订单的当前状态 + "i":27,   // 订单ID + "l":"1",     // 订单末次成交量 + "z":"8.999000",   // 订单累计已成交量 + "L":"19.1000000000",   // 订单末次成交价格 + "n":"0.00382000",   // 手续费数量 + "N":"SLP25",   // 手续费资产类型 + "T":1649926447190,   // 成交时间 + "t":18,   // 成交ID + "m":true,   // 该成交是作为挂单成交吗? + "ot":"LIMIT", //初始订单类型 + "O":0,   // 订单时间 + "Z":"171.88089996",   // 累计报价资产交易数量 + "Y":"19.1000000000000000",   // 最近报价交易数量 + "Q":"0",   // 报价数量 + "e":"executionReport",   // 事件类型 + "E":1649926447209  // 事件时间 +} +``` + + +**执行类型:** +* NEW 新订单 +* CANCELED 订单被取消 +* REJECTED 新订单被拒绝 +* TRADE 订单有新成交 +* EXPIRED 订单失效(根据订单的Time In Force参数) + + + +## Event: TradePro + +> **Topic Subscribe:** + +```javascript +{ + "method": "SUBSCRIBE", + "params": [ + "btcusdt@tradepro" + ], + "id": 3 +} +``` + +> **Payload:** + +```javascript +{ + "stream": "btcusdt@tradepro", + "data": { + "e": "tradepro", + "E": 1773751963081, + "T": 1773751963079, + "s": "BTCUSDT", + "t": 128884613, + "p": "73685.5", + "q": "0.297", + "h": "0X0000000000000000000000000000000000000000000000000000000000000000", + "m": [ + "hidden", + "hidden" + ] + } +} +``` + +* h: 该笔交易的交易哈希(Transaction hash) + +* m: 包含交易参与方地址的数组: + + * m[0]: Taker 地址(主动成交方) + + * m[1]: Maker 地址(挂单方) + + + +#错误代码 + +> error JSON payload: + +```javascript +{ + "code":-1121, + "msg":"Invalid symbol." +} +``` + +错误由两部分组成:错误代码和消息。 代码是通用的,但是消息可能会有所不同。 + + +## 10xx - 常规服务器或网络问题 +### -1000 UNKNOWN + * An unknown error occurred while processing the request. + * 处理请求时发生未知错误。 + +### -1001 DISCONNECTED + * Internal error; unable to process your request. Please try again. + * 内部错误; 无法处理您的请求。 请再试一次. + +### -1002 UNAUTHORIZED + * You are not authorized to execute this request. + * 您无权执行此请求。 + +### -1003 TOO_MANY_REQUESTS + * Too many requests queued. + * 排队的请求过多。 + * Too many requests; please use the websocket for live updates. + * 请求权重过多; 请使用websocket获取最新更新。 + * Too many requests; current limit is %s requests per minute. Please use the websocket for live updates to avoid polling the API. + * 请求权重过多; 当前限制为每分钟%s请求权重。 请使用websocket进行实时更新,以避免轮询API。 + * Way too many requests; IP banned until %s. Please use the websocket for live updates to avoid bans. + * 请求权重过多; IP被禁止,直到%s。 请使用websocket进行实时更新,以免被禁。 + +### -1004 DUPLICATE_IP + * This IP is already on the white list + * IP地址已经在白名单 + +### -1005 NO_SUCH_IP + * No such IP has been white listed + * 白名单上没有此IP地址 + +### -1006 UNEXPECTED_RESP + * An unexpected response was received from the message bus. Execution status unknown. + * 从消息总线收到意外的响应。执行状态未知。 + +### -1007 TIMEOUT + * Timeout waiting for response from backend server. Send status unknown; execution status unknown. + * 等待后端服务器响应超时。 发送状态未知; 执行状态未知。 + +### -1014 UNKNOWN_ORDER_COMPOSITION + * Unsupported order combination. + * 不支持当前的下单参数组合 + +### -1015 TOO_MANY_ORDERS + * Too many new orders. + * 新订单太多。 + * Too many new orders; current limit is %s orders per %s. + * 新订单太多; 当前限制为每%s %s个订单。 + +### -1016 SERVICE_SHUTTING_DOWN + * This service is no longer available. + * 该服务不可用。 + +### -1020 UNSUPPORTED_OPERATION + * This operation is not supported. + * 不支持此操作。 + +### -1022 INVALID_SIGNATURE + * Signature for this request is not valid. + * 此请求的签名无效。 + +### -1023 START_TIME_GREATER_THAN_END_TIME + * Start time is greater than end time. + * 参数里面的开始时间在结束时间之后 + + +## 11xx - Request issues +### -1100 ILLEGAL_CHARS + * Illegal characters found in a parameter. + * 在参数中发现非法字符。 + * Illegal characters found in parameter '%s'; legal range is '%s'. + * 在参数`%s`中发现非法字符; 合法范围是`%s`。 + +### -1101 TOO_MANY_PARAMETERS + * Too many parameters sent for this endpoint. + * 为此端点发送的参数太多。 + * Too many parameters; expected '%s' and received '%s'. + * 参数太多;预期为`%s`并收到了`%s`。 + * Duplicate values for a parameter detected. + * 检测到的参数值重复。 + +### -1102 MANDATORY_PARAM_EMPTY_OR_MALFORMED + * A mandatory parameter was not sent, was empty/null, or malformed. + * 未发送强制性参数,该参数为空/空或格式错误。 + * Mandatory parameter '%s' was not sent, was empty/null, or malformed. + * 强制参数`%s`未发送,为空/空或格式错误。 + * Param '%s' or '%s' must be sent, but both were empty/null! + * 必须发送参数`%s`或`%s`,但两者均为空! + +### -1103 UNKNOWN_PARAM + * An unknown parameter was sent. + * 发送了未知参数。 + +### -1104 UNREAD_PARAMETERS + * Not all sent parameters were read. + * 并非所有发送的参数都被读取。 + * Not all sent parameters were read; read '%s' parameter(s) but was sent '%s'. + * 并非所有发送的参数都被读取; 读取了`%s`参数,但被发送了`%s`。 + +### -1105 PARAM_EMPTY + * A parameter was empty. + * 参数为空。 + * Parameter '%s' was empty. + * 参数`%s`为空。 + +### -1106 PARAM_NOT_REQUIRED + * A parameter was sent when not required. + * 发送了不需要的参数。 + * Parameter '%s' sent when not required. + * 发送了不需要参数`%s`。 + +### -1111 BAD_PRECISION + * Precision is over the maximum defined for this asset. + * 精度超过为此资产定义的最大值。 + +### -1112 NO_DEPTH + * No orders on book for symbol. + * 交易对没有挂单。 + +### -1114 TIF_NOT_REQUIRED + * TimeInForce parameter sent when not required. + * 发送的`TimeInForce`参数不需要。 + +### -1115 INVALID_TIF + * Invalid timeInForce. + * 无效的`timeInForce` + +### -1116 INVALID_ORDER_TYPE + * Invalid orderType. + * 无效订单类型。 + +### -1117 INVALID_SIDE + * Invalid side. + * 无效买卖方向。 + +### -1118 EMPTY_NEW_CL_ORD_ID + * New client order ID was empty. + * 新的客户订单ID为空。 + +### -1119 EMPTY_ORG_CL_ORD_ID + * Original client order ID was empty. + * 客户自定义的订单ID为空。 + +### -1120 BAD_INTERVAL + * Invalid interval. + * 无效时间间隔。 + +### -1121 BAD_SYMBOL + * Invalid symbol. + * 无效的交易对。 + +### -1125 INVALID_LISTEN_KEY + * This listenKey does not exist. + * 此`listenKey`不存在。 + +### -1127 MORE_THAN_XX_HOURS + * Lookup interval is too big. + * 查询间隔太大。 + * More than %s hours between startTime and endTime. + * 从开始时间到结束时间之间超过`%s`小时。 + +### -1128 OPTIONAL_PARAMS_BAD_COMBO + * Combination of optional parameters invalid. + * 可选参数组合无效。 + +### -1130 INVALID_PARAMETER + * Invalid data sent for a parameter. + * 发送的参数为无效数据。 + * Data sent for parameter '%s' is not valid. + * 发送参数`%s`的数据无效。 + +### -1136 INVALID_NEW_ORDER_RESP_TYPE + * Invalid newOrderRespType. + * 无效的 newOrderRespType。 + + +## 20xx - Processing Issues +### -2010 NEW_ORDER_REJECTED + * NEW_ORDER_REJECTED + * 新订单被拒绝 + +### -2011 CANCEL_REJECTED + * CANCEL_REJECTED + * 取消订单被拒绝 + +### -2013 NO_SUCH_ORDER + * Order does not exist. + * 订单不存在。 + +### -2014 BAD_API_KEY_FMT + * API-key format invalid. + * API-key 格式无效。 + +### -2015 REJECTED_MBX_KEY + * Invalid API-key, IP, or permissions for action. + * 无效的API密钥,IP或操作权限。 + +### -2016 NO_TRADING_WINDOW + * No trading window could be found for the symbol. Try ticker/24hrs instead. + * 找不到该交易对的交易窗口。 尝试改为24小时自动报价。 + +### -2018 BALANCE_NOT_SUFFICIENT + * Balance is insufficient. + * 余额不足 + +### -2020 UNABLE_TO_FILL + * Unable to fill. + * 无法成交 + +### -2021 ORDER_WOULD_IMMEDIATELY_TRIGGER + * Order would immediately trigger. + * 订单可能被立刻触发 + +### -2022 REDUCE_ONLY_REJECT + * ReduceOnly Order is rejected. + * `ReduceOnly`订单被拒绝 + +### -2024 POSITION_NOT_SUFFICIENT + * Position is not sufficient. + * 持仓不足 + +### -2025 MAX_OPEN_ORDER_EXCEEDED + * Reach max open order limit. + * 挂单量达到上限 + +### -2026 REDUCE_ONLY_ORDER_TYPE_NOT_SUPPORTED + * This OrderType is not supported when reduceOnly. + * 当前订单类型不支持`reduceOnly` + +## 40xx - Filters and other Issues +### -4000 INVALID_ORDER_STATUS + * Invalid order status. + * 订单状态不正确 + +### -4001 PRICE_LESS_THAN_ZERO + * Price less than 0. + * 价格小于0 + +### -4002 PRICE_GREATER_THAN_MAX_PRICE + * Price greater than max price. + * 价格超过最大值 + +### -4003 QTY_LESS_THAN_ZERO + * Quantity less than zero. + * 数量小于0 + +### -4004 QTY_LESS_THAN_MIN_QTY + * Quantity less than min quantity. + * 数量小于最小值 + +### -4005 QTY_GREATER_THAN_MAX_QTY + * Quantity greater than max quantity. + * 数量大于最大值 + +### -4006 STOP_PRICE_LESS_THAN_ZERO + * Stop price less than zero. + * 触发价小于最小值 + +### -4007 STOP_PRICE_GREATER_THAN_MAX_PRICE + * Stop price greater than max price. + * 触发价大于最大值 + +### -4008 TICK_SIZE_LESS_THAN_ZERO + * Tick size less than zero. + * 价格精度小于0 + +### -4009 MAX_PRICE_LESS_THAN_MIN_PRICE + * Max price less than min price. + * 最大价格小于最小价格 + +### -4010 MAX_QTY_LESS_THAN_MIN_QTY + * Max qty less than min qty. + * 最大数量小于最小数量 + +### -4011 STEP_SIZE_LESS_THAN_ZERO + * Step size less than zero. + * 步进值小于0 + +### -4012 MAX_NUM_ORDERS_LESS_THAN_ZERO + * Max num orders less than zero. + * 最大订单量小于0 + +### -4013 PRICE_LESS_THAN_MIN_PRICE + * Price less than min price. + * 价格小于最小价格 + +### -4014 PRICE_NOT_INCREASED_BY_TICK_SIZE + * Price not increased by tick size. + * 价格增量不是价格精度的倍数。 + +### -4015 INVALID_CL_ORD_ID_LEN + * Client order id is not valid. + * 客户订单ID有误。 + * Client order id length should not be more than 36 chars + * 客户订单ID长度应该不多于36字符 + +### -4016 PRICE_HIGHTER_THAN_MULTIPLIER_UP + * Price is higher than mark price multiplier cap. + +### -4017 MULTIPLIER_UP_LESS_THAN_ZERO + * Multiplier up less than zero. + * 价格上限小于0 + +### -4018 MULTIPLIER_DOWN_LESS_THAN_ZERO + * Multiplier down less than zero. + * 价格下限小于0 + +### -4019 COMPOSITE_SCALE_OVERFLOW + * Composite scale too large. + +### -4020 TARGET_STRATEGY_INVALID + * Target strategy invalid for orderType '%s',reduceOnly '%b'. + * 目标策略值不适合`%s`订单状态, 只减仓`%b`。 + +### -4021 INVALID_DEPTH_LIMIT + * Invalid depth limit. + * 深度信息的`limit`值不正确。 + * '%s' is not valid depth limit. + * `%s`不是合理的深度信息的`limit`值。 + +### -4022 WRONG_MARKET_STATUS + * market status sent is not valid. + * 发送的市场状态不正确。 + +### -4023 QTY_NOT_INCREASED_BY_STEP_SIZE + * Qty not increased by step size. + * 数量的递增值不是步进值的倍数。 + +### -4024 PRICE_LOWER_THAN_MULTIPLIER_DOWN + * Price is lower than mark price multiplier floor. + +### -4025 MULTIPLIER_DECIMAL_LESS_THAN_ZERO + * Multiplier decimal less than zero. + +### -4026 COMMISSION_INVALID + * Commission invalid. + * 收益值不正确 + * `%s` less than zero. + * `%s`少于0 + * `%s` absolute value greater than `%s` + * `%s`绝对值大于`%s` + +### -4027 INVALID_ACCOUNT_TYPE + * Invalid account type. + * 账户类型不正确。 + +### -4029 INVALID_TICK_SIZE_PRECISION + * Tick size precision is invalid. + * 价格精度小数点位数不正确。 + +### -4030 INVALID_STEP_SIZE_PRECISION + * Step size precision is invalid. + * 步进值小数点位数不正确。 + +### -4031 INVALID_WORKING_TYPE + * Invalid parameter working type + * 不正确的参数类型 + * Invalid parameter working type: `%s` + * 不正确的参数类型: `%s` + +### -4032 EXCEED_MAX_CANCEL_ORDER_SIZE + * Exceed maximum cancel order size. + * 超过可以取消的最大订单量。 + * Invalid parameter working type: `%s` + * 不正确的参数类型: `%s` + +### -4044 INVALID_BALANCE_TYPE + * Balance Type is invalid. + * 余额类型不正确。 + +### -4045 MAX_STOP_ORDER_EXCEEDED + * Reach max stop order limit. + * 达到止损单的上限。 + +### -4055 AMOUNT_MUST_BE_POSITIVE + * Amount must be positive. + * 数量必须是正整数 + +### -4056 INVALID_API_KEY_TYPE + * Invalid api key type. + * API key的类型不正确 + +### -4057 INVALID_RSA_PUBLIC_KEY + * Invalid api public key + * API key不正确 + +### -4058 MAX_PRICE_TOO_LARGE + * maxPrice and priceDecimal too large,please check. + * maxPrice和priceDecimal太大,请检查。 + +### -4060 INVALID_POSITION_SIDE + * Invalid position side. + * 仓位方向不正确。 + +### -4061 POSITION_SIDE_NOT_MATCH + * Order's position side does not match user's setting. + * 订单的持仓方向和用户设置不一致。 + +### -4062 REDUCE_ONLY_CONFLICT + * Invalid or improper reduceOnly value. + * 仅减仓的设置不正确。 + +### -4084 UPCOMING_METHOD + * Method is not allowed currently. Upcoming soon. + * 方法不支持 + +### -4086 INVALID_PRICE_SPREAD_THRESHOLD + * Invalid price spread threshold + * 无效的价差阀值 + +### -4087 REDUCE_ONLY_ORDER_PERMISSION + * User can only place reduce only order + * 用户只能下仅减仓订单 + +### -4088 NO_PLACE_ORDER_PERMISSION + * User can not place order currently + * 用户当前不能下单 + +### -4114 INVALID_CLIENT_TRAN_ID_LEN + * clientTranId is not valid + * clientTranId不正确 + * Client tran id length should be less than 64 chars + * 客户的tranId长度应该小于64个字符 + +### -4115 DUPLICATED_CLIENT_TRAN_ID + * clientTranId is duplicated + * clientTranId重复 + * Client tran id should be unique within 7 days + * 客户的tranId应在7天内唯一 + +### -4118 REDUCE_ONLY_MARGIN_CHECK_FAILED + * ReduceOnly Order Failed. Please check your existing position and open orders + * 仅减仓订单失败。请检查现有的持仓和挂单 + +### -4131 MARKET_ORDER_REJECT + * The counterparty's best price does not meet the PERCENT_PRICE filter limit + * 交易对手的最高价格未达到PERCENT_PRICE过滤器限制 + +### -4135 INVALID_ACTIVATION_PRICE + * Invalid activation price + * 无效的激活价格 + +### -4137 QUANTITY_EXISTS_WITH_CLOSE_POSITION + * Quantity must be zero with closePosition equals true + * 数量必须为0,当closePosition为true时 + +### -4138 REDUCE_ONLY_MUST_BE_TRUE + * Reduce only must be true with closePosition equals true + * Reduce only 必须为true,当closePosition为true时 + +### -4139 ORDER_TYPE_CANNOT_BE_MKT + * Order type can not be market if it's unable to cancel + * 订单类型不能为市价单如果不能取消 + +### -4140 INVALID_OPENING_POSITION_STATUS + * Invalid symbol status for opening position + * 无效的交易对状态 + +### -4141 SYMBOL_ALREADY_CLOSED + * Symbol is closed + * 交易对已下架 + +### -4142 STRATEGY_INVALID_TRIGGER_PRICE + * REJECT: take profit or stop order will be triggered immediately + * 拒绝:止盈止损单将立即被触发 + +### -4164 MIN_NOTIONAL + * Order's notional must be no smaller than 5.0 (unless you choose reduce only) + * 订单的名义价值不可以小于5,除了使用reduce only + * Order's notional must be no smaller than %s (unless you choose reduce only) + * 订单的名义价值不可以小于`%s`,除了使用reduce only + +### -4165 INVALID_TIME_INTERVAL + * Invalid time interval + * 无效的间隔 + * Maximum time interval is %s days + * 最大的时间间隔为 `%s` 天 + +### -4183 PRICE_HIGHTER_THAN_STOP_MULTIPLIER_UP + * Price is higher than stop price multiplier cap. + * 止盈止损订单价格不应高于触发价与报价乘数上限的乘积 + * Limit price can't be higher than %s. + * 止盈止损订单价格不应高于 `%s` + +### -4184 PRICE_LOWER_THAN_STOP_MULTIPLIER_DOWN + * Price is lower than stop price multiplier floor. + * 止盈止损订单价格不应低于触发价与报价乘数下限的乘积 + * Limit price can't be lower than %s. + * 止盈止损订单价格不应低于 `%s`f From c435a10c963b8474a023c0ee3ec7d6b49bf98b9d Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Tue, 26 May 2026 10:32:49 +0800 Subject: [PATCH 119/131] use prediction --- .../aster-finance-prediction-api-tesetnet.md | 18 ++---------------- .../aster-finance-prediction-api-testnet.md" | 19 +++---------------- 2 files changed, 5 insertions(+), 32 deletions(-) diff --git a/V3(Recommended)/EN/aster-finance-prediction-api-tesetnet.md b/V3(Recommended)/EN/aster-finance-prediction-api-tesetnet.md index ecc9de6..ad99f83 100644 --- a/V3(Recommended)/EN/aster-finance-prediction-api-tesetnet.md +++ b/V3(Recommended)/EN/aster-finance-prediction-api-tesetnet.md @@ -81,7 +81,7 @@ You are advised to use WebSocket messages to obtain the corresponding data as mu ### Order rate limits * Each successful order response will include a `X-MBX-ORDER-COUNT-(intervalNum)(intervalLetter)` header containing the number of order limit units currently used by the account. -* When the number of orders exceeds the limit, you will receive a response with status 429 but without the `Retry-After` header. Please check the order rate limits in `GET api/v3/exchangeInfo` (rateLimitType \= ORDERS) and wait until the ban period ends. +* When the number of orders exceeds the limit, you will receive a response with status 429 but without the `Retry-After` header. Please check the order rate limits in `GET api/v3/prediction/exchangeInfo` (rateLimitType \= ORDERS) and wait until the ban period ends. * Rejected or unsuccessful orders are not guaranteed to include the above header in the response. * **Order placement rate limits are counted per account.** @@ -310,24 +310,10 @@ This defines how long an order can remain valid before expiring. **K-line interval:** -m (minutes), h (hours), d (days), w (weeks), M (months) +m (minutes) * 1s (added) * 1m -* 3m -* 5m -* 15m -* 30m -* 1h -* 2h -* 4h -* 6h -* 8h -* 12h -* 1d -* 3d -* 1w -* 1M **Rate limit type (rateLimitType)** diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-prediction-api-testnet.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-prediction-api-testnet.md" index 2faf56d..35a041e 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-prediction-api-testnet.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-prediction-api-testnet.md" @@ -79,7 +79,7 @@ ### 下单频率限制 * 每个成功的下单回报将包含一个`X-MBX-ORDER-COUNT-(intervalNum)(intervalLetter)`的头,其中包含当前账户已用的下单限制数量。 -* 当下单数超过限制时,会收到带有429但不含`Retry-After`头的响应。请检查 `GET api/v3/exchangeInfo` 的下单频率限制 (rateLimitType = ORDERS) 并等待封禁时间结束。 +* 当下单数超过限制时,会收到带有429但不含`Retry-After`头的响应。请检查 `GET api/v3/prediction/exchangeInfo` 的下单频率限制 (rateLimitType = ORDERS) 并等待封禁时间结束。 * 被拒绝或不成功的下单并不保证回报中包含以上头内容。 * **下单频率限制是基于每个账户计数的。** @@ -300,24 +300,11 @@ Status | Description **K线间隔:** -m -> 分钟; h -> 小时; d -> 天; w -> 周; M -> 月 +m -> 分钟 * 1s * 1m -* 3m -* 5m -* 15m -* 30m -* 1h -* 2h -* 4h -* 6h -* 8h -* 12h -* 1d -* 3d -* 1w -* 1M + 新增了1s参数 From be1179d92092c699a96633b70500153bc33558d2 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Tue, 26 May 2026 11:03:56 +0800 Subject: [PATCH 120/131] use prediction --- V3(Recommended)/EN/aster-finance-prediction-api-tesetnet.md | 6 +++--- .../aster-finance-prediction-api-testnet.md" | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/V3(Recommended)/EN/aster-finance-prediction-api-tesetnet.md b/V3(Recommended)/EN/aster-finance-prediction-api-tesetnet.md index ad99f83..b2d532a 100644 --- a/V3(Recommended)/EN/aster-finance-prediction-api-tesetnet.md +++ b/V3(Recommended)/EN/aster-finance-prediction-api-tesetnet.md @@ -1836,7 +1836,7 @@ Retrieve the trade history for a specified trading pair of an account # WebSocket market data feed -* The base URL for all wss endpoints listed in this document is: **wss://sstream.asterdex.com** +* The base URL for all wss endpoints listed in this document is: **wss://pstream.asterdex-testnet.com** * Streams have either a single raw stream or a combined stream * Single raw streams format is \*\*/ws/\*\* * The URL format for combined streams is \*\*/stream?streams=//\*\* @@ -2242,7 +2242,7 @@ Pushes the changed parts of the orderbook (if any) every second or every 100 mil ## How to correctly maintain a local copy of an order book -1. Subscribe to **wss://sstream.asterdex.com/ws/btc_up_dowm_5m_1778483280_yusdt@depth** +1. Subscribe to **wss://pstream.asterdex-testnet.com/ws/btc_up_dowm_5m_1778483280_yusdt@depth** 2. Start caching the received updates. For the same price level, later updates overwrite earlier ones. 3. Fetch the REST endpoint [**https://papi.asterdex-testnet.com/api/v3/depth?symbol=BTC_UP_DOWN_5M_1778483280_YUSDT\&limit=1000**](https://papi.asterdex-testnet.com/api/v3/depth?symbol=BTC_UP_DOWN_5M_1778483280_YUSDT&limit=1000) to obtain a 1000-level depth snapshot 4. Discard from the currently cached messages those with `u` \<= the `lastUpdateId` obtained in step 3 (drop older, expired information) @@ -2258,7 +2258,7 @@ Pushes the changed parts of the orderbook (if any) every second or every 100 mil * You can extend the 60-minute validity of a `listenKey` by sending a `PUT` request * You can immediately close the current data stream and invalidate the `listenKey` by sending a `DELETE` for a `listenKey` * Sending a `POST` on an account with a valid `listenKey` will return the currently valid `listenKey` and extend its validity by 60 minutes -* The WebSocket interface baseurl: **wss://sstream.asterdex.com** +* The WebSocket interface baseurl: **wss://pstream.asterdex-testnet.com** * The stream name for subscribing to the user account data stream is \*\*/ws/\*\* * Each connection is valid for no more than 24 hours; please handle disconnections and reconnections appropriately diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-prediction-api-testnet.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-prediction-api-testnet.md" index 35a041e..ff8bcb7 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-prediction-api-testnet.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-prediction-api-testnet.md" @@ -1901,7 +1901,7 @@ limit | INT | NO | 默认 500; 最大 1000. --- # Websocket 行情推送 -* 本篇所列出的所有wss接口的baseurl为: **wss://sstream.asterdex.com** +* 本篇所列出的所有wss接口的baseurl为: **wss://pstream.asterdex-testnet.com** * Streams有单一原始 stream 或组合 stream * 单一原始 streams 格式为 **/ws/\** * 组合streams的URL格式为 **/stream?streams=\/\/\** @@ -2339,7 +2339,7 @@ m -> 分钟; h -> 小时; d -> 天; w -> 周; M -> 月 **Update Speed:** 1000ms 或 100ms ## 如何正确在本地维护一个orderbook副本 -1. 订阅 **wss://sstream.asterdex.com/ws/bnbbtc@depth** +1. 订阅 **wss://pstream.asterdex-testnet.com/ws/bnbbtc@depth** 2. 开始缓存收到的更新。同一个价位,后收到的更新覆盖前面的。 3. 访问Rest接口 **https://papi.asterdex-testnet.com/api/v3/depth?symbol=BNBBTC&limit=1000** 获得一个1000档的深度快照 4. 将目前缓存到的信息中`u` <= 步骤3中获取到的快照中的`lastUpdateId`的部分丢弃(丢弃更早的信息,已经过期)。 @@ -2360,7 +2360,7 @@ m -> 分钟; h -> 小时; d -> 天; w -> 周; M -> 月 * 可以通过 `PUT` 一个 `listenKey` 延长60分钟有效期 * 可以通过`DELETE`一个 `listenKey` 立即关闭当前数据流,并使该`listenKey` 无效 * 在具有有效`listenKey`的帐户上执行`POST`将返回当前有效的`listenKey`并将其有效期延长60分钟 -* websocket接口的baseurl: **wss://sstream.asterdex.com** +* websocket接口的baseurl: **wss://pstream.asterdex-testnet.com** * U订阅账户数据流的stream名称为 **/ws/\** * 每个链接有效期不超过24小时,请妥善处理断线重连。 From 6f363bc8abb208fe4453b5f405d0dbaafe727cbd Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Wed, 27 May 2026 12:36:51 +0800 Subject: [PATCH 121/131] stake --- V3(Recommended)/EN/aster-chain.md | 207 ++++++++++++++++++ .../aster-finance-prediction-api-tesetnet.md | 3 + .../aster-chain_CN.md" | 207 ++++++++++++++++++ .../aster-finance-prediction-api-testnet.md" | 3 + 4 files changed, 420 insertions(+) diff --git a/V3(Recommended)/EN/aster-chain.md b/V3(Recommended)/EN/aster-chain.md index 29ba55a..95c2594 100644 --- a/V3(Recommended)/EN/aster-chain.md +++ b/V3(Recommended)/EN/aster-chain.md @@ -9,6 +9,14 @@ - [Get Account Status (USER_DATA)](#get-account-status-user_data) - [Modify Account Status (TRADE)](#modify-account-status-trade) - [Transfer to Address (WITHDRAW)](#transfer-to-address-withdraw) +- [Aster-Chain Staking Endpoints](#aster-chain-staking-endpoints) + - [Get Staking Account Status (USER_DATA)](#get-staking-account-status-user_data) + - [Get My Staking (USER_DATA)](#get-my-staking-user_data) + - [Get Claimable Rewards (USER_DATA)](#get-claimable-rewards-user_data) + - [Create Staking (TRADE)](#create-staking-trade) + - [Deposit Stake (TRADE)](#deposit-stake-trade) + - [Update Lock Period (TRADE)](#update-lock-period-trade) + - [Claim Rewards (TRADE)](#claim-rewards-trade) --- @@ -92,3 +100,202 @@ Transfer assets to another Aster Chain address. The recipient address must belon | nonce | LONG | YES | Microsecond timestamp | | user | STRING | YES | Source account wallet address | | signature | STRING | YES | EIP-712 signature, signed with the `user` account's wallet private key | + +--- + +# Aster-Chain Staking Endpoints + +## Get Staking Account Status (USER_DATA) + +> **Response:** + +```javascript +{ + "stakeAccountStatus": "ACTIVE" // "ACTIVE", "INACTIVE", or "PENDING" +} +``` + +`GET /aster-chain/v3/staking/stakeAccountStatus` + +Query the staking account status of the current user. + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +|------|------|-----------|-------------| +| nonce | LONG | YES | Microsecond timestamp | +| signer | STRING | YES | Agent wallet address (sub-wallet authorized to sign on behalf of the account) | +| signature | STRING | YES | EIP-712 signature, signed with the `signer` wallet private key | + +--- + +## Get My Staking (USER_DATA) + +> **Response:** + +```javascript +{ + "validatorAddress": "0x1a2b3c4d...", + "stakeAmount": "1000.00", + "periodCode": "90D", + "startTime": 1699900800000, + "endTime": 1707676800000, + "status": "ACTIVE" // "ACTIVE", "UNLOCKING", or "COMPLETED" +} +``` + +`GET /aster-chain/v3/staking/myStaking` + +Query the current user's staking position details. + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +|------|------|-----------|-------------| +| nonce | LONG | YES | Microsecond timestamp | +| signer | STRING | YES | Agent wallet address (sub-wallet authorized to sign on behalf of the account) | +| signature | STRING | YES | EIP-712 signature, signed with the `signer` wallet private key | + +--- + +## Get Claimable Rewards (USER_DATA) + +> **Response:** + +```javascript +{ + "claimableAmount": "12.50", + "asset": "ASTER", + "accruedRewards": "25.00", + "lastClaimTime": 1699900800000 +} +``` + +`GET /aster-chain/v3/staking/claimableRewards` + +Query the amount of staking rewards available to claim for the current user. + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Mandatory | Description | +|------|------|-----------|-------------| +| nonce | LONG | YES | Microsecond timestamp | +| signer | STRING | YES | Agent wallet address (sub-wallet authorized to sign on behalf of the account) | +| signature | STRING | YES | EIP-712 signature, signed with the `signer` wallet private key | + +--- + +## Create Staking (TRADE) + +> **Response:** + +```javascript +{ + "result": "SUCCESS" +} +``` + +`POST /aster-chain/v3/staking/create` + +Create a new staking position by delegating tokens to a validator. The on-chain action type is `TokenDelegate` (`Stake`). + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Mandatory | Description | +|------|------|-----------|-------------| +| validatorAddress | STRING | YES | Target validator's on-chain address | +| stakeAmount | DECIMAL | YES | Amount of tokens to stake, must be greater than 0 | +| periodCode | STRING | YES | Lock period code. Allowed values: `"26_WEEKS"`, `"52_WEEKS"`, `"104_WEEKS"`, `"156_WEEKS"`, `"208_WEEKS"` | +| nonce | LONG | YES | Microsecond timestamp | +| user | STRING | YES | Source account wallet address | +| signature | STRING | YES | EIP-712 signature, signed with the `user` account's wallet private key | + +--- + +## Deposit Stake (TRADE) + +> **Response:** + +```javascript +{ + "result": "SUCCESS" +} +``` + +`POST /aster-chain/v3/staking/deposit` + +Add tokens to an existing staking position on the specified validator. The on-chain action type is `TokenDelegate` (`AddStake`). + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Mandatory | Description | +|------|------|-----------|-------------| +| validatorAddress | STRING | YES | Target validator's on-chain address | +| stakeAmount | DECIMAL | YES | Amount of additional tokens to stake, must be greater than 0 | +| nonce | LONG | YES | Microsecond timestamp | +| user | STRING | YES | Source account wallet address | +| signature | STRING | YES | EIP-712 signature, signed with the `user` account's wallet private key | + +--- + +## Update Lock Period (TRADE) + +> **Response:** + +```javascript +{ + "result": "SUCCESS" +} +``` + +`POST /aster-chain/v3/staking/updateLockPeriod` + +Extend the lock period of the current staking position. The on-chain action type is `TokenDelegate` (`ExtendStakingTime`). + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Mandatory | Description | +|------|------|-----------|-------------| +| periodCode | STRING | YES | New lock period code. Allowed values: `"26_WEEKS"`, `"52_WEEKS"`, `"104_WEEKS"`, `"156_WEEKS"`, `"208_WEEKS"`. Must be longer than the current lock period. | +| nonce | LONG | YES | Microsecond timestamp | +| user | STRING | YES | Source account wallet address | +| signature | STRING | YES | EIP-712 signature, signed with the `user` account's wallet private key | + +--- + +## Claim Rewards (TRADE) + +> **Response:** + +```javascript +{ + "result": "SUCCESS" +} +``` + +`POST /aster-chain/v3/staking/claimRewards` + +Claim accumulated staking rewards. The on-chain action type is `TokenDelegate` (`ClaimRewards`). + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Mandatory | Description | +|------|------|-----------|-------------| +| requestedAmount | DECIMAL | YES | Amount of rewards to claim, must be greater than 0 and not exceed the claimable balance | +| nonce | LONG | YES | Microsecond timestamp | +| user | STRING | YES | Source account wallet address | +| signature | STRING | YES | EIP-712 signature, signed with the `user` account's wallet private key | diff --git a/V3(Recommended)/EN/aster-finance-prediction-api-tesetnet.md b/V3(Recommended)/EN/aster-finance-prediction-api-tesetnet.md index b2d532a..d6b092f 100644 --- a/V3(Recommended)/EN/aster-finance-prediction-api-tesetnet.md +++ b/V3(Recommended)/EN/aster-finance-prediction-api-tesetnet.md @@ -475,6 +475,9 @@ In order to comply with the `market lot size`, the `quantity` must satisfy the f "LIMIT", "MARKET" ], // Supported order types + "settleIntervalSeconds": 5, //twap price internal + "settlementDataPointCount": 5, //twap price data count + "reduceOnly": false, //reduceOnly "timeInForce": [ "GTC", "IOC", diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-chain_CN.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-chain_CN.md" index f37e324..6582338 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-chain_CN.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-chain_CN.md" @@ -9,6 +9,14 @@ - [查询账户状态 (USER_DATA)](#查询账户状态-user_data) - [修改账户状态 (TRADE)](#修改账户状态-trade) - [转账至地址 (WITHDRAW)](#转账至地址-withdraw) +- [Aster-Chain 质押接口](#aster-chain-质押接口) + - [查询质押账户状态 (USER_DATA)](#查询质押账户状态-user_data) + - [查询我的质押 (USER_DATA)](#查询我的质押-user_data) + - [查询可领取奖励 (USER_DATA)](#查询可领取奖励-user_data) + - [创建质押 (TRADE)](#创建质押-trade) + - [追加质押 (TRADE)](#追加质押-trade) + - [更新锁定期 (TRADE)](#更新锁定期-trade) + - [领取奖励 (TRADE)](#领取奖励-trade) --- @@ -92,3 +100,202 @@ | nonce | LONG | YES | 微秒时间戳 | | user | STRING | YES | 发起账户钱包地址 | | signature | STRING | YES | EIP-712 签名,使用 `user` 账户的钱包私钥签名 | + +--- + +# Aster-Chain 质押接口 + +## 查询质押账户状态 (USER_DATA) + +> **响应:** + +```javascript +{ + "stakeAccountStatus": "ACTIVE" // "ACTIVE"、"INACTIVE" 或 "PENDING" +} +``` + +`GET /aster-chain/v3/staking/stakeAccountStatus` + +查询当前用户的质押账户状态。 + +**权重:** 1 + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| nonce | LONG | YES | 微秒时间戳 | +| signer | STRING | YES | 代理钱包地址(被授权代表账户签名的子钱包) | +| signature | STRING | YES | EIP-712 签名,使用 `signer` 钱包私钥签名 | + +--- + +## 查询我的质押 (USER_DATA) + +> **响应:** + +```javascript +{ + "validatorAddress": "0x1a2b3c4d...", + "stakeAmount": "1000.00", + "periodCode": "90D", + "startTime": 1699900800000, + "endTime": 1707676800000, + "status": "ACTIVE" // "ACTIVE"、"UNLOCKING" 或 "COMPLETED" +} +``` + +`GET /aster-chain/v3/staking/myStaking` + +查询当前用户的质押仓位详情。 + +**权重:** 1 + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| nonce | LONG | YES | 微秒时间戳 | +| signer | STRING | YES | 代理钱包地址(被授权代表账户签名的子钱包) | +| signature | STRING | YES | EIP-712 签名,使用 `signer` 钱包私钥签名 | + +--- + +## 查询可领取奖励 (USER_DATA) + +> **响应:** + +```javascript +{ + "claimableAmount": "12.50", + "asset": "ASTER", + "accruedRewards": "25.00", + "lastClaimTime": 1699900800000 +} +``` + +`GET /aster-chain/v3/staking/claimableRewards` + +查询当前用户可领取的质押奖励数量。 + +**权重:** 1 + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| nonce | LONG | YES | 微秒时间戳 | +| signer | STRING | YES | 代理钱包地址(被授权代表账户签名的子钱包) | +| signature | STRING | YES | EIP-712 签名,使用 `signer` 钱包私钥签名 | + +--- + +## 创建质押 (TRADE) + +> **响应:** + +```javascript +{ + "result": "SUCCESS" +} +``` + +`POST /aster-chain/v3/staking/create` + +创建新的质押仓位,将代币委托至指定验证节点。链上操作类型为 `TokenDelegate`(`Stake`)。 + +**权重:** 5 + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| validatorAddress | STRING | YES | 目标验证节点的链上地址 | +| stakeAmount | DECIMAL | YES | 质押代币数量,必须大于 0 | +| periodCode | STRING | YES | 锁定周期代码,可选值:`"26_WEEKS"`、`"52_WEEKS"`、`"104_WEEKS"`、`"156_WEEKS"`、`"208_WEEKS"` | +| nonce | LONG | YES | 微秒时间戳 | +| user | STRING | YES | 发起账户钱包地址 | +| signature | STRING | YES | EIP-712 签名,使用 `user` 账户的钱包私钥签名 | + +--- + +## 追加质押 (TRADE) + +> **响应:** + +```javascript +{ + "result": "SUCCESS" +} +``` + +`POST /aster-chain/v3/staking/deposit` + +向指定验证节点的已有质押仓位追加代币。链上操作类型为 `TokenDelegate`(`AddStake`)。 + +**权重:** 5 + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| validatorAddress | STRING | YES | 目标验证节点的链上地址 | +| stakeAmount | DECIMAL | YES | 追加质押的代币数量,必须大于 0 | +| nonce | LONG | YES | 微秒时间戳 | +| user | STRING | YES | 发起账户钱包地址 | +| signature | STRING | YES | EIP-712 签名,使用 `user` 账户的钱包私钥签名 | + +--- + +## 更新锁定期 (TRADE) + +> **响应:** + +```javascript +{ + "result": "SUCCESS" +} +``` + +`POST /aster-chain/v3/staking/updateLockPeriod` + +延长当前质押仓位的锁定周期。链上操作类型为 `TokenDelegate`(`ExtendStakingTime`)。 + +**权重:** 5 + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| periodCode | STRING | YES | 新的锁定周期代码,可选值:`"26_WEEKS"`、`"52_WEEKS"`、`"104_WEEKS"`、`"156_WEEKS"`、`"208_WEEKS"`,须长于当前锁定周期 | +| nonce | LONG | YES | 微秒时间戳 | +| user | STRING | YES | 发起账户钱包地址 | +| signature | STRING | YES | EIP-712 签名,使用 `user` 账户的钱包私钥签名 | + +--- + +## 领取奖励 (TRADE) + +> **响应:** + +```javascript +{ + "result": "SUCCESS" +} +``` + +`POST /aster-chain/v3/staking/claimRewards` + +领取已累积的质押奖励。链上操作类型为 `TokenDelegate`(`ClaimRewards`)。 + +**权重:** 5 + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| requestedAmount | DECIMAL | YES | 申请领取的奖励数量,必须大于 0 且不超过可领取余额 | +| nonce | LONG | YES | 微秒时间戳 | +| user | STRING | YES | 发起账户钱包地址 | +| signature | STRING | YES | EIP-712 签名,使用 `user` 账户的钱包私钥签名 | diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-prediction-api-testnet.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-prediction-api-testnet.md" index ff8bcb7..e82d6c1 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-prediction-api-testnet.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-prediction-api-testnet.md" @@ -475,6 +475,9 @@ Lots是拍卖术语,`LOT_SIZE` 过滤器对订单中的 `quantity` 也就是 "FOK", "GTX" ], //预测事件的TIF + "settleIntervalSeconds": 5, //twap 价格数据周期 + "settlementDataPointCount": 5, //twap 价格数据数量 + "reduceOnly": false, //是否只减仓 "liveRound":{ "marketName": "USD1_UP_DOWN_5M_1778483280", //预测市场的名字 "symbolIds": [ From 8ab8d0e5b458945732347a0ca966c82b2f582d90 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Wed, 27 May 2026 14:32:02 +0800 Subject: [PATCH 122/131] prediction_twap --- .../aster-finance-prediction-api-tesetnet.md | 42 +++++++++++++++++++ .../aster-finance-prediction-api-testnet.md" | 41 ++++++++++++++++++ 2 files changed, 83 insertions(+) diff --git a/V3(Recommended)/EN/aster-finance-prediction-api-tesetnet.md b/V3(Recommended)/EN/aster-finance-prediction-api-tesetnet.md index d6b092f..0784208 100644 --- a/V3(Recommended)/EN/aster-finance-prediction-api-tesetnet.md +++ b/V3(Recommended)/EN/aster-finance-prediction-api-tesetnet.md @@ -2443,6 +2443,48 @@ Orders are updated via the `executionReport` event * m[1]: Maker address +## Event: Prediction Event Twap Update + +> **Topic Subscribe:** + +* eventName@evnet + +```javascript +{ + "method": "SUBSCRIBE", + "params": [ + "btc_up_down_5m@event" + ], + "id": 3 +} +``` + +> **Payload:** + +```javascript +{ + 'e': 'market_start', // Event start; pushes the initial price + 'm': 'ETH_UP_DOWN_5M_1779846360', // Event name + 'y': 'ETH_UP_DOWN_5M_1779846360_YUSDT', // Long (UP) symbol name + 'n': 'ETH_UP_DOWN_5M_1779846360_NUSDT', // Short (DOWN) symbol name + 'p': '2073.68023256', // Initial price + 't': 1779846360000 // Push timestamp +} + +{ + 'e': 'market_twap', // TWAP data update; pushes each TWAP sample point + 'm': 'ETH_UP_DOWN_5M_1779846660', // Event name + 'y': 'ETH_UP_DOWN_5M_1779846660_YUSDT', // Long (UP) symbol name + 'n': 'ETH_UP_DOWN_5M_1779846660_NUSDT', // Short (DOWN) symbol name + 'p': '2076.40762162', // Price + 'r': 0, // Remaining data points + 't': 1779846960000, // Push timestamp + 'w': 'Y' // Winning result: Y = UP, N = DOWN +} +``` + + + \#错误代码 error JSON payload: diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-prediction-api-testnet.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-prediction-api-testnet.md" index e82d6c1..ed8fbe1 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-prediction-api-testnet.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-prediction-api-testnet.md" @@ -2558,6 +2558,47 @@ listenKey | STRING | YES +## Event: 预测市场结算Twap数据更新 + +> **Topic Subscribe:** + +* eventName@evnet + +```javascript +{ + "method": "SUBSCRIBE", + "params": [ + "btc_up_down_5m@event" + ], + "id": 3 +} +``` + +> **Payload:** + +```javascript +{ + 'e': 'market_start', // 事件开始,推送初始价格 + 'm': 'ETH_UP_DOWN_5M_1779846360', // 事件名称 + 'y': 'ETH_UP_DOWN_5M_1779846360_YUSDT', // 上涨 symbol 名称 + 'n': 'ETH_UP_DOWN_5M_1779846360_NUSDT', // 下跌 symbol 名称 + 'p': '2073.68023256', // 初始价格 + 't': 1779846360000 // 推送时间 +} + +{ + 'e': 'market_twap', // 事件 TWAP 数据更新,推送每次的 TWAP 取点数据 + 'm': 'ETH_UP_DOWN_5M_1779846660', // 事件名称 + 'y': 'ETH_UP_DOWN_5M_1779846660_YUSDT', // 上涨 symbol 名称 + 'n': 'ETH_UP_DOWN_5M_1779846660_NUSDT', // 下跌 symbol 名称 + 'p': '2076.40762162', // 价格 + 'r': 0, // 剩余数据点数量 + 't': 1779846960000, // 推送时间 + 'w': 'Y' // 获胜结果:Y 代表上涨,N 代表下跌 +} +``` + + #错误代码 > error JSON payload: From 9da1763927a7aa249b361d0a19fe1dcb5bb6f24c Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Wed, 27 May 2026 14:35:35 +0800 Subject: [PATCH 123/131] prediction_twap --- V3(Recommended)/EN/aster-finance-prediction-api-tesetnet.md | 2 +- .../aster-finance-prediction-api-testnet.md" | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/V3(Recommended)/EN/aster-finance-prediction-api-tesetnet.md b/V3(Recommended)/EN/aster-finance-prediction-api-tesetnet.md index 0784208..5bf469c 100644 --- a/V3(Recommended)/EN/aster-finance-prediction-api-tesetnet.md +++ b/V3(Recommended)/EN/aster-finance-prediction-api-tesetnet.md @@ -2447,7 +2447,7 @@ Orders are updated via the `executionReport` event > **Topic Subscribe:** -* eventName@evnet +* eventName@event ```javascript { diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-prediction-api-testnet.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-prediction-api-testnet.md" index ed8fbe1..4e94ed8 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-prediction-api-testnet.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-prediction-api-testnet.md" @@ -2562,7 +2562,7 @@ listenKey | STRING | YES > **Topic Subscribe:** -* eventName@evnet +* eventName@event ```javascript { From a3e5cc993ee5c20089a0f9b4617d550dc41f772c Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Wed, 27 May 2026 14:49:34 +0800 Subject: [PATCH 124/131] prediction_twap --- V3(Recommended)/EN/aster-finance-prediction-api-tesetnet.md | 2 +- .../aster-finance-prediction-api-testnet.md" | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/V3(Recommended)/EN/aster-finance-prediction-api-tesetnet.md b/V3(Recommended)/EN/aster-finance-prediction-api-tesetnet.md index 5bf469c..ccd6be4 100644 --- a/V3(Recommended)/EN/aster-finance-prediction-api-tesetnet.md +++ b/V3(Recommended)/EN/aster-finance-prediction-api-tesetnet.md @@ -2479,7 +2479,7 @@ Orders are updated via the `executionReport` event 'p': '2076.40762162', // Price 'r': 0, // Remaining data points 't': 1779846960000, // Push timestamp - 'w': 'Y' // Winning result: Y = UP, N = DOWN + 'w': 'Y' // Winning result (only present in the last push): Y = UP, N = DOWN } ``` diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-prediction-api-testnet.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-prediction-api-testnet.md" index 4e94ed8..4707d63 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-prediction-api-testnet.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-prediction-api-testnet.md" @@ -2594,7 +2594,7 @@ listenKey | STRING | YES 'p': '2076.40762162', // 价格 'r': 0, // 剩余数据点数量 't': 1779846960000, // 推送时间 - 'w': 'Y' // 获胜结果:Y 代表上涨,N 代表下跌 + 'w': 'Y' // 获胜结果(仅在最后一条推送中出现):Y 代表上涨,N 代表下跌 } ``` From 75d9061799dfb6cd8a87548b3a171816b7d5a184 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Thu, 28 May 2026 09:58:33 +0800 Subject: [PATCH 125/131] add deposit withdraw --- V3(Recommended)/EN/aster-chain.md | 436 ++++++++++++++++++ .../aster-chain_CN.md" | 436 ++++++++++++++++++ 2 files changed, 872 insertions(+) diff --git a/V3(Recommended)/EN/aster-chain.md b/V3(Recommended)/EN/aster-chain.md index 95c2594..b51579f 100644 --- a/V3(Recommended)/EN/aster-chain.md +++ b/V3(Recommended)/EN/aster-chain.md @@ -17,6 +17,20 @@ - [Deposit Stake (TRADE)](#deposit-stake-trade) - [Update Lock Period (TRADE)](#update-lock-period-trade) - [Claim Rewards (TRADE)](#claim-rewards-trade) +- [Aster-Chain Perp Withdraw & Transfer Endpoints](#aster-chain-perp-withdraw--transfer-endpoints) + - [User Withdraw (WITHDRAW)](#user-withdraw-withdraw) + - [User Solana Withdraw (WITHDRAW)](#user-solana-withdraw-withdraw) + - [Get Withdraw Info (USER_DATA)](#get-withdraw-info-user_data) + - [Deposit/Withdraw History (USER_DATA)](#depositwithdraw-history-user_data) + - [Wallet Transfer (TRADE)](#wallet-transfer-trade) + - [Transfer History (USER_DATA)](#transfer-history-user_data) +- [Aster-Chain Spot Withdraw & Transfer Endpoints](#aster-chain-spot-withdraw--transfer-endpoints) + - [User Withdraw (WITHDRAW)](#user-withdraw-withdraw-1) + - [User Solana Withdraw (WITHDRAW)](#user-solana-withdraw-withdraw-1) + - [Get Withdraw Info (USER_DATA)](#get-withdraw-info-user_data-1) + - [Deposit/Withdraw History (USER_DATA)](#depositwithdraw-history-user_data-1) + - [Wallet Transfer (TRADE)](#wallet-transfer-trade-1) + - [Transfer History (USER_DATA)](#transfer-history-user_data-1) --- @@ -299,3 +313,425 @@ Claim accumulated staking rewards. The on-chain action type is `TokenDelegate` ( | nonce | LONG | YES | Microsecond timestamp | | user | STRING | YES | Source account wallet address | | signature | STRING | YES | EIP-712 signature, signed with the `user` account's wallet private key | + +--- + +# Aster-Chain Perp Withdraw & Transfer Endpoints + +## User Withdraw (WITHDRAW) + +> **Response:** + +```javascript +{ + "withdrawId": "987654321", + "hash": "0xabc123..." +} +``` + +`POST /aster-chain/v3/perp/user-withdraw` + +Submit a withdrawal request from the perp account to an on-chain address. + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Mandatory | Description | +|------|------|-----------|-------------| +| asset | STRING | YES | Asset name (e.g. `"USDT"`) | +| chainId | INTEGER | YES | Target chain ID | +| amount | STRING | YES | Withdrawal amount | +| fee | STRING | YES | Withdrawal fee | +| receiver | STRING | YES | Recipient on-chain address | +| userNonce | STRING | YES | User-side nonce included in the signature | +| userSignature | STRING | YES | User signature over the withdrawal parameters | + +--- + +## User Solana Withdraw (WITHDRAW) + +> **Response:** + +```javascript +{ + "withdrawId": "987654321", + "hash": "0xabc123..." +} +``` + +`POST /aster-chain/v3/perp/user-solana-withdraw` + +Submit a withdrawal request from the perp account to a Solana address. + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Mandatory | Description | +|------|------|-----------|-------------| +| asset | STRING | YES | Asset name (e.g. `"USDT"`) | +| chainId | INTEGER | YES | Target chain ID | +| amount | STRING | YES | Withdrawal amount | +| fee | STRING | YES | Withdrawal fee | +| receiver | STRING | YES | Recipient Solana address | +| userNonce | STRING | YES | User-side nonce included in the signature | +| userSignature | STRING | YES | User signature over the withdrawal parameters | + +--- + +## Get Withdraw Info (USER_DATA) + +> **Response:** + +```javascript +{ + "userDailyLimit": "10000", + "userRemainingDailyLimit": "9500", + "totalDailyLimit": "100000", + "totalRemainingDailyLimit": "95000", + "balances": { + "USDT": { + "currency": "USDT", + "spotTotalWithdrawAmount": "0", + "perpTotalWithdrawAmount": "500", + "dailyLimit": "5000", + "chainBalances": { + "1": { + "chainId": 1, + "spotMaxWithdrawAmount": "1000", + "perpMaxWithdrawAmount": "4500", + "chainLimit": "5000", + "withdrawFee": "0.5" + } + } + } + } +} +``` + +`GET /aster-chain/v3/perp/user-withdraw-info` + +Query the current user's withdrawal limits and available balances per asset and chain. + +**Weight:** 1 + +**Parameters:** + +None + +--- + +## Deposit/Withdraw History (USER_DATA) + +> **Response:** + +```javascript +[ + { + "id": "12345", + "type": "WITHDRAW", // "DEPOSIT" or "WITHDRAW" + "asset": "USDT", + "amount": "100", + "state": "COMPLETED", + "txHash": "0xabc123...", + "time": 1699900800000, + "chainId": 1, + "accountType": "perp" + } +] +``` + +`GET /aster-chain/v3/perp/deposit-withdraw-history` + +Query the deposit and withdrawal history for the current user's perp account. + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Mandatory | Description | +|------|------|-----------|-------------| +| chainId | STRING | NO | Filter records by chain ID | + +--- + +## Wallet Transfer (TRADE) + +> **Response:** + +```javascript +{ + "tranId": 123456789, + "status": "SUCCESS" +} +``` + +`POST /aster-chain/v3/perp/wallet/transfer` + +Transfer assets between the spot wallet and the perp account. + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Mandatory | Description | +|------|------|-----------|-------------| +| asset | STRING | YES | Asset name (e.g. `"USDT"`) | +| amount | DECIMAL | YES | Transfer amount, must be greater than 0 | +| clientTranId | STRING | YES | Client-defined transfer ID | +| kindType | STRING | YES | Transfer direction: `"SPOT_FUTURE"` (spot → perp) or `"FUTURE_SPOT"` (perp → spot) | +| nonce | LONG | YES | Microsecond timestamp | +| user | STRING | YES | Source account wallet address | +| signature | STRING | YES | EIP-712 signature, signed with the `user` account's wallet private key | + +--- + +## Transfer History (USER_DATA) + +> **Response:** + +```javascript +{ + "total": 2, + "rows": [ + { + "asset": "USDT", + "tranId": 123456789, + "amount": "100", + "kindType": "SPOT_FUTURE", // "SPOT_FUTURE" or "FUTURE_SPOT" + "createTime": 1699900800000, + "updateTime": 1699900810000, + "status": "SUCCESS" // "SUCCESS", "FAIL", or "PENDING" + } + ] +} +``` + +`GET /aster-chain/v3/perp/transfer/history` + +Query the wallet transfer history between spot and perp for the current user. + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Mandatory | Description | +|------|------|-----------|-------------| +| asset | STRING | NO | Filter by asset name | +| startTime | LONG | NO | Start time in milliseconds | +| endTime | LONG | NO | End time in milliseconds (defaults to current time) | +| page | INTEGER | NO | Page number, default `1` | +| pageSize | INTEGER | NO | Records per page, default `10`, max `100` | +| order | STRING | NO | Sort order: `"ASC"` or `"DESC"` (default `"DESC"`) | + +--- + +# Aster-Chain Spot Withdraw & Transfer Endpoints + +## User Withdraw (WITHDRAW) + +> **Response:** + +```javascript +{ + "withdrawId": "987654321", + "hash": "0xabc123..." +} +``` + +`POST /aster-chain/v3/spot/user-withdraw` + +Submit a withdrawal request from the spot account to an on-chain address. + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Mandatory | Description | +|------|------|-----------|-------------| +| asset | STRING | YES | Asset name (e.g. `"USDT"`) | +| chainId | INTEGER | YES | Target chain ID | +| amount | STRING | YES | Withdrawal amount | +| fee | STRING | YES | Withdrawal fee | +| receiver | STRING | YES | Recipient on-chain address | +| userNonce | STRING | YES | User-side nonce included in the signature | +| userSignature | STRING | YES | User signature over the withdrawal parameters | + +--- + +## User Solana Withdraw (WITHDRAW) + +> **Response:** + +```javascript +{ + "withdrawId": "987654321", + "hash": "0xabc123..." +} +``` + +`POST /aster-chain/v3/spot/user-solana-withdraw` + +Submit a withdrawal request from the spot account to a Solana address. + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Mandatory | Description | +|------|------|-----------|-------------| +| asset | STRING | YES | Asset name (e.g. `"USDT"`) | +| chainId | INTEGER | YES | Target chain ID | +| amount | DECIMAL | YES | Withdrawal amount | +| fee | DECIMAL | YES | Withdrawal fee | +| receiver | STRING | YES | Recipient Solana address | +| userNonce | STRING | YES | User-side nonce included in the signature | +| userSignature | STRING | YES | User signature over the withdrawal parameters | + +--- + +## Get Withdraw Info (USER_DATA) + +> **Response:** + +```javascript +{ + "userDailyLimit": "10000", + "userRemainingDailyLimit": "9500", + "totalDailyLimit": "100000", + "totalRemainingDailyLimit": "95000", + "balances": { + "USDT": { + "currency": "USDT", + "spotTotalWithdrawAmount": "500", + "perpTotalWithdrawAmount": "0", + "dailyLimit": "5000", + "chainBalances": { + "1": { + "chainId": 1, + "spotMaxWithdrawAmount": "4500", + "perpMaxWithdrawAmount": "1000", + "chainLimit": "5000", + "withdrawFee": "0.5" + } + } + } + } +} +``` + +`GET /aster-chain/v3/spot/user-withdraw-info` + +Query the current user's withdrawal limits and available balances per asset and chain for the spot account. + +**Weight:** 1 + +**Parameters:** + +None + +--- + +## Deposit/Withdraw History (USER_DATA) + +> **Response:** + +```javascript +[ + { + "id": "12345", + "type": "WITHDRAW", // "DEPOSIT" or "WITHDRAW" + "asset": "USDT", + "amount": "100", + "state": "COMPLETED", + "txHash": "0xabc123...", + "time": 1699900800000, + "chainId": 1, + "accountType": "spot" + } +] +``` + +`GET /aster-chain/v3/spot/deposit-withdraw-history` + +Query the deposit and withdrawal history for the current user's spot account. + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Mandatory | Description | +|------|------|-----------|-------------| +| chainId | STRING | NO | Filter records by chain ID | + +--- + +## Wallet Transfer (TRADE) + +> **Response:** + +```javascript +{ + "tranId": 123456789, + "status": "SUCCESS" +} +``` + +`POST /aster-chain/v3/spot/wallet/transfer` + +Transfer assets between the spot wallet and the perp account. + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Mandatory | Description | +|------|------|-----------|-------------| +| asset | STRING | YES | Asset name (e.g. `"USDT"`) | +| amount | DECIMAL | YES | Transfer amount, must be greater than 0 | +| clientTranId | STRING | YES | Client-defined transfer ID | +| kindType | STRING | YES | Transfer direction: `"SPOT_FUTURE"` (spot → perp) or `"FUTURE_SPOT"` (perp → spot) | +| nonce | LONG | YES | Microsecond timestamp | +| user | STRING | YES | Source account wallet address | +| signature | STRING | YES | EIP-712 signature, signed with the `user` account's wallet private key | + +--- + +## Transfer History (USER_DATA) + +> **Response:** + +```javascript +{ + "total": 2, + "rows": [ + { + "asset": "USDT", + "tranId": 123456789, + "amount": "100", + "kindType": "SPOT_FUTURE", // "SPOT_FUTURE" or "FUTURE_SPOT" + "createTime": 1699900800000, + "updateTime": 1699900810000, + "status": "SUCCESS" // "SUCCESS", "FAIL", or "PENDING" + } + ] +} +``` + +`GET /aster-chain/v3/spot/transfer/history` + +Query the wallet transfer history between spot and perp for the current user. + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Mandatory | Description | +|------|------|-----------|-------------| +| asset | STRING | NO | Filter by asset name | +| startTime | LONG | NO | Start time in milliseconds | +| endTime | LONG | NO | End time in milliseconds (defaults to current time) | +| page | INTEGER | NO | Page number, default `1` | +| pageSize | INTEGER | NO | Records per page, default `10`, max `100` | +| order | STRING | NO | Sort order: `"ASC"` or `"DESC"` (default `"DESC"`) | diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-chain_CN.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-chain_CN.md" index 6582338..bf1a9a0 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-chain_CN.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-chain_CN.md" @@ -17,6 +17,20 @@ - [追加质押 (TRADE)](#追加质押-trade) - [更新锁定期 (TRADE)](#更新锁定期-trade) - [领取奖励 (TRADE)](#领取奖励-trade) +- [Aster-Chain 合约提现与划转接口](#aster-chain-合约提现与划转接口) + - [合约提现 (WITHDRAW)](#合约提现-withdraw) + - [合约 Solana 提现 (WITHDRAW)](#合约-solana-提现-withdraw) + - [查询提现信息 (USER_DATA)](#查询提现信息-user_data) + - [充提记录 (USER_DATA)](#充提记录-user_data) + - [钱包划转 (TRADE)](#钱包划转-trade) + - [划转记录 (USER_DATA)](#划转记录-user_data) +- [Aster-Chain 现货提现与划转接口](#aster-chain-现货提现与划转接口) + - [现货提现 (WITHDRAW)](#现货提现-withdraw) + - [现货 Solana 提现 (WITHDRAW)](#现货-solana-提现-withdraw) + - [查询提现信息 (USER_DATA)](#查询提现信息-user_data-1) + - [充提记录 (USER_DATA)](#充提记录-user_data-1) + - [钱包划转 (TRADE)](#钱包划转-trade-1) + - [划转记录 (USER_DATA)](#划转记录-user_data-1) --- @@ -299,3 +313,425 @@ | nonce | LONG | YES | 微秒时间戳 | | user | STRING | YES | 发起账户钱包地址 | | signature | STRING | YES | EIP-712 签名,使用 `user` 账户的钱包私钥签名 | + +--- + +# Aster-Chain 合约提现与划转接口 + +## 合约提现 (WITHDRAW) + +> **响应:** + +```javascript +{ + "withdrawId": "987654321", + "hash": "0xabc123..." +} +``` + +`POST /aster-chain/v3/perp/user-withdraw` + +从合约账户提现至链上地址。 + +**权重:** 5 + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| asset | STRING | YES | 资产名称(如 `"USDT"`) | +| chainId | INTEGER | YES | 目标链 ID | +| amount | STRING | YES | 提现金额 | +| fee | STRING | YES | 提现手续费 | +| receiver | STRING | YES | 接收方链上地址 | +| userNonce | STRING | YES | 签名中包含的用户端 nonce | +| userSignature | STRING | YES | 用户对提现参数的签名 | + +--- + +## 合约 Solana 提现 (WITHDRAW) + +> **响应:** + +```javascript +{ + "withdrawId": "987654321", + "hash": "0xabc123..." +} +``` + +`POST /aster-chain/v3/perp/user-solana-withdraw` + +从合约账户提现至 Solana 地址。 + +**权重:** 5 + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| asset | STRING | YES | 资产名称(如 `"USDT"`) | +| chainId | INTEGER | YES | 目标链 ID | +| amount | STRING | YES | 提现金额 | +| fee | STRING | YES | 提现手续费 | +| receiver | STRING | YES | 接收方 Solana 地址 | +| userNonce | STRING | YES | 签名中包含的用户端 nonce | +| userSignature | STRING | YES | 用户对提现参数的签名 | + +--- + +## 查询提现信息 (USER_DATA) + +> **响应:** + +```javascript +{ + "userDailyLimit": "10000", + "userRemainingDailyLimit": "9500", + "totalDailyLimit": "100000", + "totalRemainingDailyLimit": "95000", + "balances": { + "USDT": { + "currency": "USDT", + "spotTotalWithdrawAmount": "0", + "perpTotalWithdrawAmount": "500", + "dailyLimit": "5000", + "chainBalances": { + "1": { + "chainId": 1, + "spotMaxWithdrawAmount": "1000", + "perpMaxWithdrawAmount": "4500", + "chainLimit": "5000", + "withdrawFee": "0.5" + } + } + } + } +} +``` + +`GET /aster-chain/v3/perp/user-withdraw-info` + +查询当前用户各资产、各链的提现限额及可用余额。 + +**权重:** 1 + +**参数:** + +无 + +--- + +## 充提记录 (USER_DATA) + +> **响应:** + +```javascript +[ + { + "id": "12345", + "type": "WITHDRAW", // "DEPOSIT" 或 "WITHDRAW" + "asset": "USDT", + "amount": "100", + "state": "COMPLETED", + "txHash": "0xabc123...", + "time": 1699900800000, + "chainId": 1, + "accountType": "perp" + } +] +``` + +`GET /aster-chain/v3/perp/deposit-withdraw-history` + +查询当前用户合约账户的充值与提现历史记录。 + +**权重:** 5 + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| chainId | STRING | NO | 按链 ID 过滤记录 | + +--- + +## 钱包划转 (TRADE) + +> **响应:** + +```javascript +{ + "tranId": 123456789, + "status": "SUCCESS" +} +``` + +`POST /aster-chain/v3/perp/wallet/transfer` + +在现货钱包与合约账户之间划转资产。 + +**权重:** 5 + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| asset | STRING | YES | 资产名称(如 `"USDT"`) | +| amount | DECIMAL | YES | 划转金额,必须大于 0 | +| clientTranId | STRING | YES | 客户端自定义划转 ID | +| kindType | STRING | YES | 划转方向:`"SPOT_FUTURE"`(现货 → 合约)或 `"FUTURE_SPOT"`(合约 → 现货) | +| nonce | LONG | YES | 微秒时间戳 | +| user | STRING | YES | 发起账户钱包地址 | +| signature | STRING | YES | EIP-712 签名,使用 `user` 账户的钱包私钥签名 | + +--- + +## 划转记录 (USER_DATA) + +> **响应:** + +```javascript +{ + "total": 2, + "rows": [ + { + "asset": "USDT", + "tranId": 123456789, + "amount": "100", + "kindType": "SPOT_FUTURE", // "SPOT_FUTURE" 或 "FUTURE_SPOT" + "createTime": 1699900800000, + "updateTime": 1699900810000, + "status": "SUCCESS" // "SUCCESS"、"FAIL" 或 "PENDING" + } + ] +} +``` + +`GET /aster-chain/v3/perp/transfer/history` + +查询当前用户现货与合约间的划转历史记录。 + +**权重:** 5 + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| asset | STRING | NO | 按资产名称过滤 | +| startTime | LONG | NO | 起始时间(毫秒) | +| endTime | LONG | NO | 结束时间(毫秒),默认为当前时间 | +| page | INTEGER | NO | 页码,默认 `1` | +| pageSize | INTEGER | NO | 每页记录数,默认 `10`,最大 `100` | +| order | STRING | NO | 排序方式:`"ASC"` 或 `"DESC"`(默认 `"DESC"`) | + +--- + +# Aster-Chain 现货提现与划转接口 + +## 现货提现 (WITHDRAW) + +> **响应:** + +```javascript +{ + "withdrawId": "987654321", + "hash": "0xabc123..." +} +``` + +`POST /aster-chain/v3/spot/user-withdraw` + +从现货账户提现至链上地址。 + +**权重:** 5 + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| asset | STRING | YES | 资产名称(如 `"USDT"`) | +| chainId | INTEGER | YES | 目标链 ID | +| amount | STRING | YES | 提现金额 | +| fee | STRING | YES | 提现手续费 | +| receiver | STRING | YES | 接收方链上地址 | +| userNonce | STRING | YES | 签名中包含的用户端 nonce | +| userSignature | STRING | YES | 用户对提现参数的签名 | + +--- + +## 现货 Solana 提现 (WITHDRAW) + +> **响应:** + +```javascript +{ + "withdrawId": "987654321", + "hash": "0xabc123..." +} +``` + +`POST /aster-chain/v3/spot/user-solana-withdraw` + +从现货账户提现至 Solana 地址。 + +**权重:** 5 + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| asset | STRING | YES | 资产名称(如 `"USDT"`) | +| chainId | INTEGER | YES | 目标链 ID | +| amount | DECIMAL | YES | 提现金额 | +| fee | DECIMAL | YES | 提现手续费 | +| receiver | STRING | YES | 接收方 Solana 地址 | +| userNonce | STRING | YES | 签名中包含的用户端 nonce | +| userSignature | STRING | YES | 用户对提现参数的签名 | + +--- + +## 查询提现信息 (USER_DATA) + +> **响应:** + +```javascript +{ + "userDailyLimit": "10000", + "userRemainingDailyLimit": "9500", + "totalDailyLimit": "100000", + "totalRemainingDailyLimit": "95000", + "balances": { + "USDT": { + "currency": "USDT", + "spotTotalWithdrawAmount": "500", + "perpTotalWithdrawAmount": "0", + "dailyLimit": "5000", + "chainBalances": { + "1": { + "chainId": 1, + "spotMaxWithdrawAmount": "4500", + "perpMaxWithdrawAmount": "1000", + "chainLimit": "5000", + "withdrawFee": "0.5" + } + } + } + } +} +``` + +`GET /aster-chain/v3/spot/user-withdraw-info` + +查询当前用户现货账户各资产、各链的提现限额及可用余额。 + +**权重:** 1 + +**参数:** + +无 + +--- + +## 充提记录 (USER_DATA) + +> **响应:** + +```javascript +[ + { + "id": "12345", + "type": "WITHDRAW", // "DEPOSIT" 或 "WITHDRAW" + "asset": "USDT", + "amount": "100", + "state": "COMPLETED", + "txHash": "0xabc123...", + "time": 1699900800000, + "chainId": 1, + "accountType": "spot" + } +] +``` + +`GET /aster-chain/v3/spot/deposit-withdraw-history` + +查询当前用户现货账户的充值与提现历史记录。 + +**权重:** 5 + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| chainId | STRING | NO | 按链 ID 过滤记录 | + +--- + +## 钱包划转 (TRADE) + +> **响应:** + +```javascript +{ + "tranId": 123456789, + "status": "SUCCESS" +} +``` + +`POST /aster-chain/v3/spot/wallet/transfer` + +在现货钱包与合约账户之间划转资产。 + +**权重:** 5 + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| asset | STRING | YES | 资产名称(如 `"USDT"`) | +| amount | DECIMAL | YES | 划转金额,必须大于 0 | +| clientTranId | STRING | YES | 客户端自定义划转 ID | +| kindType | STRING | YES | 划转方向:`"SPOT_FUTURE"`(现货 → 合约)或 `"FUTURE_SPOT"`(合约 → 现货) | +| nonce | LONG | YES | 微秒时间戳 | +| user | STRING | YES | 发起账户钱包地址 | +| signature | STRING | YES | EIP-712 签名,使用 `user` 账户的钱包私钥签名 | + +--- + +## 划转记录 (USER_DATA) + +> **响应:** + +```javascript +{ + "total": 2, + "rows": [ + { + "asset": "USDT", + "tranId": 123456789, + "amount": "100", + "kindType": "SPOT_FUTURE", // "SPOT_FUTURE" 或 "FUTURE_SPOT" + "createTime": 1699900800000, + "updateTime": 1699900810000, + "status": "SUCCESS" // "SUCCESS"、"FAIL" 或 "PENDING" + } + ] +} +``` + +`GET /aster-chain/v3/spot/transfer/history` + +查询当前用户现货与合约间的划转历史记录。 + +**权重:** 5 + +**参数:** + +| 名称 | 类型 | 是否必需 | 描述 | +|------|------|---------|------| +| asset | STRING | NO | 按资产名称过滤 | +| startTime | LONG | NO | 起始时间(毫秒) | +| endTime | LONG | NO | 结束时间(毫秒),默认为当前时间 | +| page | INTEGER | NO | 页码,默认 `1` | +| pageSize | INTEGER | NO | 每页记录数,默认 `10`,最大 `100` | +| order | STRING | NO | 排序方式:`"ASC"` 或 `"DESC"`(默认 `"DESC"`) | From c098a8a2ecf43f11f8caec5bb607cb2f04da9c1d Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Thu, 28 May 2026 16:52:13 +0800 Subject: [PATCH 126/131] remove transfer history, add estimate withdraw fee Co-Authored-By: Claude Sonnet 4.6 --- V3(Recommended)/EN/aster-chain.md | 124 ++------------ .../aster-chain_CN.md" | 158 ++---------------- 2 files changed, 32 insertions(+), 250 deletions(-) diff --git a/V3(Recommended)/EN/aster-chain.md b/V3(Recommended)/EN/aster-chain.md index b51579f..763a763 100644 --- a/V3(Recommended)/EN/aster-chain.md +++ b/V3(Recommended)/EN/aster-chain.md @@ -23,14 +23,12 @@ - [Get Withdraw Info (USER_DATA)](#get-withdraw-info-user_data) - [Deposit/Withdraw History (USER_DATA)](#depositwithdraw-history-user_data) - [Wallet Transfer (TRADE)](#wallet-transfer-trade) - - [Transfer History (USER_DATA)](#transfer-history-user_data) - [Aster-Chain Spot Withdraw & Transfer Endpoints](#aster-chain-spot-withdraw--transfer-endpoints) - [User Withdraw (WITHDRAW)](#user-withdraw-withdraw-1) - [User Solana Withdraw (WITHDRAW)](#user-solana-withdraw-withdraw-1) - - [Get Withdraw Info (USER_DATA)](#get-withdraw-info-user_data-1) - - [Deposit/Withdraw History (USER_DATA)](#depositwithdraw-history-user_data-1) - [Wallet Transfer (TRADE)](#wallet-transfer-trade-1) - - [Transfer History (USER_DATA)](#transfer-history-user_data-1) +- [Aster-Chain Withdraw Endpoints](#aster-chain-withdraw-endpoints) + - [Estimate Withdraw Fee (NONE)](#estimate-withdraw-fee-none) --- @@ -487,46 +485,6 @@ Transfer assets between the spot wallet and the perp account. --- -## Transfer History (USER_DATA) - -> **Response:** - -```javascript -{ - "total": 2, - "rows": [ - { - "asset": "USDT", - "tranId": 123456789, - "amount": "100", - "kindType": "SPOT_FUTURE", // "SPOT_FUTURE" or "FUTURE_SPOT" - "createTime": 1699900800000, - "updateTime": 1699900810000, - "status": "SUCCESS" // "SUCCESS", "FAIL", or "PENDING" - } - ] -} -``` - -`GET /aster-chain/v3/perp/transfer/history` - -Query the wallet transfer history between spot and perp for the current user. - -**Weight:** 5 - -**Parameters:** - -| Name | Type | Mandatory | Description | -|------|------|-----------|-------------| -| asset | STRING | NO | Filter by asset name | -| startTime | LONG | NO | Start time in milliseconds | -| endTime | LONG | NO | End time in milliseconds (defaults to current time) | -| page | INTEGER | NO | Page number, default `1` | -| pageSize | INTEGER | NO | Records per page, default `10`, max `100` | -| order | STRING | NO | Sort order: `"ASC"` or `"DESC"` (default `"DESC"`) | - ---- - # Aster-Chain Spot Withdraw & Transfer Endpoints ## User Withdraw (WITHDRAW) @@ -591,48 +549,6 @@ Submit a withdrawal request from the spot account to a Solana address. --- -## Get Withdraw Info (USER_DATA) - -> **Response:** - -```javascript -{ - "userDailyLimit": "10000", - "userRemainingDailyLimit": "9500", - "totalDailyLimit": "100000", - "totalRemainingDailyLimit": "95000", - "balances": { - "USDT": { - "currency": "USDT", - "spotTotalWithdrawAmount": "500", - "perpTotalWithdrawAmount": "0", - "dailyLimit": "5000", - "chainBalances": { - "1": { - "chainId": 1, - "spotMaxWithdrawAmount": "4500", - "perpMaxWithdrawAmount": "1000", - "chainLimit": "5000", - "withdrawFee": "0.5" - } - } - } - } -} -``` - -`GET /aster-chain/v3/spot/user-withdraw-info` - -Query the current user's withdrawal limits and available balances per asset and chain for the spot account. - -**Weight:** 1 - -**Parameters:** - -None - ---- - ## Deposit/Withdraw History (USER_DATA) > **Response:** @@ -698,40 +614,32 @@ Transfer assets between the spot wallet and the perp account. --- -## Transfer History (USER_DATA) +# Aster-Chain Withdraw Endpoints + +## Estimate Withdraw Fee (NONE) > **Response:** ```javascript { - "total": 2, - "rows": [ - { - "asset": "USDT", - "tranId": 123456789, - "amount": "100", - "kindType": "SPOT_FUTURE", // "SPOT_FUTURE" or "FUTURE_SPOT" - "createTime": 1699900800000, - "updateTime": 1699900810000, - "status": "SUCCESS" // "SUCCESS", "FAIL", or "PENDING" - } - ] + "gasPrice": 1000000000, + "gasLimit": 21000, + "nativePrice": "1800.00", + "tokenPrice": "1.00", + "gasCost": "0.000021", + "gasUsdValue": "0.038" } ``` -`GET /aster-chain/v3/spot/transfer/history` +`GET /aster-chain/v3/withdraw/estimateFee` -Query the wallet transfer history between spot and perp for the current user. +Estimate the gas fee for a withdrawal on the specified chain and asset. -**Weight:** 5 +**Weight:** 1 **Parameters:** | Name | Type | Mandatory | Description | |------|------|-----------|-------------| -| asset | STRING | NO | Filter by asset name | -| startTime | LONG | NO | Start time in milliseconds | -| endTime | LONG | NO | End time in milliseconds (defaults to current time) | -| page | INTEGER | NO | Page number, default `1` | -| pageSize | INTEGER | NO | Records per page, default `10`, max `100` | -| order | STRING | NO | Sort order: `"ASC"` or `"DESC"` (default `"DESC"`) | +| chainId | INTEGER | YES | Target chain ID | +| asset | STRING | YES | Asset name (e.g. `"USDT"`) | diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-chain_CN.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-chain_CN.md" index bf1a9a0..2dd9323 100644 --- "a/V3(Recommended)/\344\270\255\346\226\207/aster-chain_CN.md" +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-chain_CN.md" @@ -23,14 +23,12 @@ - [查询提现信息 (USER_DATA)](#查询提现信息-user_data) - [充提记录 (USER_DATA)](#充提记录-user_data) - [钱包划转 (TRADE)](#钱包划转-trade) - - [划转记录 (USER_DATA)](#划转记录-user_data) - [Aster-Chain 现货提现与划转接口](#aster-chain-现货提现与划转接口) - [现货提现 (WITHDRAW)](#现货提现-withdraw) - [现货 Solana 提现 (WITHDRAW)](#现货-solana-提现-withdraw) - - [查询提现信息 (USER_DATA)](#查询提现信息-user_data-1) - - [充提记录 (USER_DATA)](#充提记录-user_data-1) - [钱包划转 (TRADE)](#钱包划转-trade-1) - - [划转记录 (USER_DATA)](#划转记录-user_data-1) +- [Aster-Chain 提现接口](#aster-chain-提现接口) + - [估算提现手续费 (NONE)](#估算提现手续费-none) --- @@ -487,46 +485,6 @@ --- -## 划转记录 (USER_DATA) - -> **响应:** - -```javascript -{ - "total": 2, - "rows": [ - { - "asset": "USDT", - "tranId": 123456789, - "amount": "100", - "kindType": "SPOT_FUTURE", // "SPOT_FUTURE" 或 "FUTURE_SPOT" - "createTime": 1699900800000, - "updateTime": 1699900810000, - "status": "SUCCESS" // "SUCCESS"、"FAIL" 或 "PENDING" - } - ] -} -``` - -`GET /aster-chain/v3/perp/transfer/history` - -查询当前用户现货与合约间的划转历史记录。 - -**权重:** 5 - -**参数:** - -| 名称 | 类型 | 是否必需 | 描述 | -|------|------|---------|------| -| asset | STRING | NO | 按资产名称过滤 | -| startTime | LONG | NO | 起始时间(毫秒) | -| endTime | LONG | NO | 结束时间(毫秒),默认为当前时间 | -| page | INTEGER | NO | 页码,默认 `1` | -| pageSize | INTEGER | NO | 每页记录数,默认 `10`,最大 `100` | -| order | STRING | NO | 排序方式:`"ASC"` 或 `"DESC"`(默认 `"DESC"`) | - ---- - # Aster-Chain 现货提现与划转接口 ## 现货提现 (WITHDRAW) @@ -591,82 +549,6 @@ --- -## 查询提现信息 (USER_DATA) - -> **响应:** - -```javascript -{ - "userDailyLimit": "10000", - "userRemainingDailyLimit": "9500", - "totalDailyLimit": "100000", - "totalRemainingDailyLimit": "95000", - "balances": { - "USDT": { - "currency": "USDT", - "spotTotalWithdrawAmount": "500", - "perpTotalWithdrawAmount": "0", - "dailyLimit": "5000", - "chainBalances": { - "1": { - "chainId": 1, - "spotMaxWithdrawAmount": "4500", - "perpMaxWithdrawAmount": "1000", - "chainLimit": "5000", - "withdrawFee": "0.5" - } - } - } - } -} -``` - -`GET /aster-chain/v3/spot/user-withdraw-info` - -查询当前用户现货账户各资产、各链的提现限额及可用余额。 - -**权重:** 1 - -**参数:** - -无 - ---- - -## 充提记录 (USER_DATA) - -> **响应:** - -```javascript -[ - { - "id": "12345", - "type": "WITHDRAW", // "DEPOSIT" 或 "WITHDRAW" - "asset": "USDT", - "amount": "100", - "state": "COMPLETED", - "txHash": "0xabc123...", - "time": 1699900800000, - "chainId": 1, - "accountType": "spot" - } -] -``` - -`GET /aster-chain/v3/spot/deposit-withdraw-history` - -查询当前用户现货账户的充值与提现历史记录。 - -**权重:** 5 - -**参数:** - -| 名称 | 类型 | 是否必需 | 描述 | -|------|------|---------|------| -| chainId | STRING | NO | 按链 ID 过滤记录 | - ---- - ## 钱包划转 (TRADE) > **响应:** @@ -698,40 +580,32 @@ --- -## 划转记录 (USER_DATA) +# Aster-Chain 提现接口 + +## 估算提现手续费 (NONE) > **响应:** ```javascript { - "total": 2, - "rows": [ - { - "asset": "USDT", - "tranId": 123456789, - "amount": "100", - "kindType": "SPOT_FUTURE", // "SPOT_FUTURE" 或 "FUTURE_SPOT" - "createTime": 1699900800000, - "updateTime": 1699900810000, - "status": "SUCCESS" // "SUCCESS"、"FAIL" 或 "PENDING" - } - ] + "gasPrice": 1000000000, + "gasLimit": 21000, + "nativePrice": "1800.00", + "tokenPrice": "1.00", + "gasCost": "0.000021", + "gasUsdValue": "0.038" } ``` -`GET /aster-chain/v3/spot/transfer/history` +`GET /aster-chain/v3/withdraw/estimateFee` -查询当前用户现货与合约间的划转历史记录。 +估算指定链和资产的提现 Gas 手续费。 -**权重:** 5 +**权重:** 1 **参数:** | 名称 | 类型 | 是否必需 | 描述 | |------|------|---------|------| -| asset | STRING | NO | 按资产名称过滤 | -| startTime | LONG | NO | 起始时间(毫秒) | -| endTime | LONG | NO | 结束时间(毫秒),默认为当前时间 | -| page | INTEGER | NO | 页码,默认 `1` | -| pageSize | INTEGER | NO | 每页记录数,默认 `10`,最大 `100` | -| order | STRING | NO | 排序方式:`"ASC"` 或 `"DESC"`(默认 `"DESC"`) | +| chainId | INTEGER | YES | 目标链 ID | +| asset | STRING | YES | 资产名称(如 `"USDT"`) | From a836e0261bfac793d29584020fb3bda7d5291c86 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Thu, 28 May 2026 16:55:48 +0800 Subject: [PATCH 127/131] remove spot deposit/withdraw history section Co-Authored-By: Claude Sonnet 4.6 --- V3(Recommended)/EN/aster-chain.md | 33 ------------------------------- 1 file changed, 33 deletions(-) diff --git a/V3(Recommended)/EN/aster-chain.md b/V3(Recommended)/EN/aster-chain.md index 763a763..e674bb5 100644 --- a/V3(Recommended)/EN/aster-chain.md +++ b/V3(Recommended)/EN/aster-chain.md @@ -549,39 +549,6 @@ Submit a withdrawal request from the spot account to a Solana address. --- -## Deposit/Withdraw History (USER_DATA) - -> **Response:** - -```javascript -[ - { - "id": "12345", - "type": "WITHDRAW", // "DEPOSIT" or "WITHDRAW" - "asset": "USDT", - "amount": "100", - "state": "COMPLETED", - "txHash": "0xabc123...", - "time": 1699900800000, - "chainId": 1, - "accountType": "spot" - } -] -``` - -`GET /aster-chain/v3/spot/deposit-withdraw-history` - -Query the deposit and withdrawal history for the current user's spot account. - -**Weight:** 5 - -**Parameters:** - -| Name | Type | Mandatory | Description | -|------|------|-----------|-------------| -| chainId | STRING | NO | Filter records by chain ID | - ---- ## Wallet Transfer (TRADE) From 998a44ef22d16823a0ab0ca12e3cac4e95924b13 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Fri, 29 May 2026 09:38:57 +0800 Subject: [PATCH 128/131] prediction_prod --- .../EN/aster-finance-prediction-api.md | 2970 ++++++++++++++++ .../aster-finance-prediction-api.md" | 3104 +++++++++++++++++ 2 files changed, 6074 insertions(+) create mode 100644 V3(Recommended)/EN/aster-finance-prediction-api.md create mode 100644 "V3(Recommended)/\344\270\255\346\226\207/aster-finance-prediction-api.md" diff --git a/V3(Recommended)/EN/aster-finance-prediction-api.md b/V3(Recommended)/EN/aster-finance-prediction-api.md new file mode 100644 index 0000000..af97fc4 --- /dev/null +++ b/V3(Recommended)/EN/aster-finance-prediction-api.md @@ -0,0 +1,2970 @@ +# Prediction API Overview + +* This document lists the base URL for the API endpoints: [**https://papi.asterdex.com**](https://papi.asterdex.com) +* All API responses are in JSON format. + +## API Agent Address settings + +* Many endpoints require an API Key to access. +* When setting the Agent Address, for security reasons it is recommended to set an IP access whitelist. +* **Never reveal your Agent Address/private key to anyone.** + +If an API Key is accidentally exposed, immediately delete that Key and generate a new one. + +### Attention +* TESTUSDT or any other symbols starting with TEST are symbols used for Aster's INTERNAL TESTING ONLY. Please DO NOT trade on these symbols starting with TEST. Aster does not hold any accountability for loss of funds due to trading on these symbols. However, if you run into issues, you may contact support about this any time, we will try to help you recover your funds. + +### V3 Nonce Mechanism + +* **Nonce** is used to validate the **validity, uniqueness, and replay-protection** of requests. Clients should use the **current timestamp (microsecond precision)** as the nonce, and the difference from server time must not exceed **10 seconds**. + +* Request processing flow: + + 1. If the nonce **has already been used** → rejected as a **duplicate request** + 2. Otherwise, the system checks whether it is **too old** + +* To improve performance, each user maintains only the **most recent 100 nonces**: + + * If the list is full and the new nonce is **smaller than the current minimum** → rejected as **expired** + * Otherwise, the **oldest nonce is removed** and the new one is added + +* Overall effect: **prevents duplicates and stale requests, retaining only recent valid requests** + +### HTTP return codes + +* HTTP `4XX` status codes are used to indicate errors in the request content, behavior, or format. The problem lies with the requester. +* HTTP `403` status code indicates a violation of WAF restrictions (Web Application Firewall). +* HTTP `429` error code indicates a warning that the access frequency limit has been exceeded and the IP is about to be blocked. +* HTTP `418` indicates that after receiving a 429 you continued to access, so the IP has been blocked. +* HTTP `5XX` error codes are used to indicate issues on the Aster service side. + +### API error codes + +* When using the endpoint `/api/v3`, any endpoint may throw exceptions; + +The API error codes are returned in the following format: + +```javascript +{ + "code": -1121, + "msg": "Invalid symbol." +} +``` + +### Basic information about the endpoint + +* Endpoints with the `GET` method must send parameters in the `query string`. +* For `POST`, `PUT`, and `DELETE` endpoints, parameters can be sent in the `query string` with content type `application/x-www-form-urlencoded` , or in the `request body`. +* The order of parameters is not required. + +--- + +## Access restrictions + +### Basic information on access restrictions + +* The `rateLimits` array in `/api/v3/prediction/exchangeInfo` contains objects related to REQUEST\_WEIGHT and ORDERS rate limits for trading. These are further defined in the `enum definitions` section under `rateLimitType`. +* A 429 will be returned when any of the rate limits are violated. + +### IP access limits + +* Each request will include a header named `X-MBX-USED-WEIGHT-(intervalNum)(intervalLetter)` that contains the used weight of all requests from the current IP. +* Each endpoint has a corresponding weight, and some endpoints may have different weights depending on their parameters. The more resources an endpoint consumes, the higher its weight will be. +* Upon receiving a 429, you are responsible for stopping requests and must not abuse the API. +* **If you continue to violate access limits after receiving a 429, your IP will be banned and you will receive a 418 error code.** +* Repeated violations of the limits will result in progressively longer bans, **from a minimum of 2 minutes up to a maximum of 3 days**. +* The `Retry-After` header will be sent with responses bearing 418 or 429, and will give the wait time **in seconds** (if 429\) to avoid the ban, or, if 418, until the ban ends. +* **Access restrictions are based on IP, not API Key** + +You are advised to use WebSocket messages to obtain the corresponding data as much as possible to reduce the load and rate-limit pressure from requests. + +### Order rate limits + +* Each successful order response will include a `X-MBX-ORDER-COUNT-(intervalNum)(intervalLetter)` header containing the number of order limit units currently used by the account. +* When the number of orders exceeds the limit, you will receive a response with status 429 but without the `Retry-After` header. Please check the order rate limits in `GET api/v3/prediction/exchangeInfo` (rateLimitType \= ORDERS) and wait until the ban period ends. +* Rejected or unsuccessful orders are not guaranteed to include the above header in the response. +* **Order placement rate limits are counted per account.** + +### WebSocket connection limits + +* The WebSocket server accepts a maximum of 5 messages per second. Messages include: + * PING frame + * PONG frame + * Messages in JSON format, such as subscribe and unsubscribe. +* If a user sends messages that exceed the limit, the connection will be terminated. IPs that are repeatedly disconnected may be blocked by the server. +* A single connection can subscribe to up to **1024** Streams. + +--- + +## API authentication types + +* Each API has its own authentication type, which determines what kind of authentication should be performed when accessing it. +* The authentication type will be indicated next to each endpoint name in this document; if not specifically stated, it defaults to `NONE`. + +| Security Type | Description | +| ------------- | ----------------------------------------- | +| NONE | API that does not require authentication | +| PREDICTION_TRADE | A valid signer and signature are required | +| USER_DATA | A valid signer and signature are required | +| USER_STREAM | A valid signer and signature are required | +| MARKET_DATA | API that does not require authentication | + +--- + +## SIGNED (TRADE AND USER\_DATA) Endpoint security +* Security Type: PREDICTION_TRADE, USER_DATA, USER_STREAM + + +## Example of POST /api/v3/order + + +#### The following parameters are API registration details. The values for user, signer, and privateKey are for demonstration purposes only (the privateKey corresponds to the signer). + +| Key | Value | Desc +| ---------- | ------------------------------------------------------------------ | ---------- | +| user | 0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e |Login wallet address | +| signer | 0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0 |[Click Here](https://www.asterdex.com/en/api-wallet) | +| privateKey | 0x4fd0a42218f3eae43a6ce26d22544e986139a01e5b34a62db53757ffca81bae1 |[Click Here](https://www.asterdex.com/en/api-wallet) | + +#### The nonce parameter is the current system time in microseconds. If it exceeds the system time or lags behind it by more than 10 seconds, the request is considered invalid. +```python +#python +nonce = math.trunc(time.time()*1000000) +print(nonce) +#1748310859508867 +``` +```java +#python +//java +Instant now = Instant.now(); +long microsecond = now.getEpochSecond() * 1000000 + now.getNano() / 1000; +``` + +#### Example: Post an order (using Python as an example). + + +```python +import time +import urllib +import threading + +import requests +from eth_account.messages import encode_structured_data +from eth_account import Account + +typed_data = { + "types": { + "EIP712Domain": [ + {"name": "name", "type": "string"}, + {"name": "version", "type": "string"}, + {"name": "chainId", "type": "uint256"}, + {"name": "verifyingContract", "type": "address"} + ], + "Message": [ + { "name": "msg", "type": "string" } + ] + }, + "primaryType": "Message", + "domain": { + "name": "AsterSignTransaction", + "version": "1", + "chainId": 1666, + "verifyingContract": "0x0000000000000000000000000000000000000000" + }, + "message": { + "msg": "$msg" + } +} + +headers = { + 'Content-Type': 'application/x-www-form-urlencoded', + 'User-Agent': 'PythonApp/1.0' +} +host = 'https://papi.asterdex.com' + +# config your user and agent info here +user = '*' +signer = '*' +private_key = "*" + +place_order = {"url":"/api/v3/order","method":"POST","params":{"symbol": "ASTERUSDT", "type": "LIMIT", "side": "BUY", + "timeInForce": "GTC", "quantity": "100", "price": "0.4"}} +_last_ms = 0 +_i = 0 +_nonce_lock = threading.Lock() + +def get_nonce(): + global _last_ms, _i + with _nonce_lock: + now_ms = int(time.time()) + + if now_ms == _last_ms: + _i += 1 + else: + _last_ms = now_ms + _i = 0 + + return now_ms * 1_000_000 + _i + +def send_by_url(api) : + my_dict = api['params'] + url = host + api['url'] + + my_dict['nonce'] = str(get_nonce()) + my_dict['signer'] = signer + + param = urllib.parse.urlencode(my_dict) + print(param) + typed_data['message']['msg'] = param + message = encode_structured_data(typed_data) + signed = Account.sign_message(message, private_key=private_key) + + url = url + '?' + param + '&signature=' + signed.signature.hex() + print(url) + res = requests.post(url, headers=headers) + + print(res.text) + +def send_by_body(api) : + my_dict = api['params'] + url = host +api['url'] + my_dict['nonce'] = str(get_nonce()) + my_dict['signer'] = signer + + param = urllib.parse.urlencode(my_dict) + typed_data['message']['msg'] = param + message = encode_structured_data(typed_data) + + signed = Account.sign_message(message, private_key=private_key) + print(signed.signature.hex()) + + my_dict['signature'] = signed.signature.hex() + + print(my_dict) + res = requests.post(url, data=my_dict, headers=headers) + + print(res.text) + +if __name__ == '__main__': + send_by_url(place_order) + # send_by_body(place_order) + +``` + +## Public API parameters + +### Terminology + +The terminology in this section applies throughout the document. New users are encouraged to read it carefully for better understanding. + +* `base asset` refers to the asset being traded in a trading pair, i.e., the asset name written first; for example, in `BTCUSDT`, `BTC` is the `base asset`. +* `quote asset` refers to the pricing asset of a trading pair, i.e., the asset name written at the latter part; for example, in `BTCUSDT`, `USDT` is the `quote asset`. + +### Enumeration definition + +**Trading pair status (status):** + +* TRADING \- after trade + +**Trading pair type:** + +* PREDICTION \- prediction + +**Order status (status):** + +| Status | Description | +| :---- | :---- | +| NEW | Order accepted by the matching engine | +| PARTIALLY\_FILLED | Part of the order was filled | +| FILLED | The order was fully filled | +| CANCELED | The user canceled the order | +| REJECTED | The order was not accepted by the matching engine and was not processed | +| EXPIRED | Order canceled by the trading engine, for example: Limit FOK order not filled, Market order not fully filled, orders canceled during exchange maintenance | + +**Order types (orderTypes, type):** + +* LIMIT \- Limit Order +* MARKET \- Market Order + +**Order response type (newOrderRespType):** + +* ACK +* RESULT +* FULL + +**Order direction (direction side):** + +* BUY \- Buy +* SELL \- Sell + +**Valid types (timeInForce):** + +This defines how long an order can remain valid before expiring. + +| Status | Description | +| :---- | :---- | +| GTC (Good 'Til Canceled) | The order remains active until it is fully executed or manually canceled. | +| IOC (Immediate or Cancel) | The order will execute immediately for any amount available. Any unfilled portion is automatically canceled. | +| FOK (Fill or Kill) | The order must be fully executed immediately. If it cannot be filled in full, it is canceled right away. | +| GTX (Good till crossing, Post only) | The post-only limit order will only be placed if it can be added as a maker order and not as a taker order. | + +**K-line interval:** + +m (minutes) + +* 1s (added) +* 1m + +**Rate limit type (rateLimitType)** + +REQUEST\_WEIGHT + +```json + { + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200 + } +``` + +ORDERS + +```json + { + "rateLimitType": "ORDERS", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 100 + } +``` + +* REQUEST\_WEIGHT \- The maximum sum of request weights allowed within a unit time + +* ORDERS \- Order placement frequency limit per time unit + +**Interval restriction (interval)** + +* MINUTE \- Minute + +--- + +## Filters + +Filters, i.e. Filter, define a set of trading rules. There are two types: filters for trading pairs `symbol filters`, and filters for the entire exchange `exchange filters` (not supported yet) + +### Trading pair filters + +#### PRICE\_FILTER Price filter + +**Format in the /exchangeInfo response:** + +```javascript + { + "minPrice": "0.0001", + "maxPrice": "0.9999", + "filterType": "PRICE_FILTER", + "tickSize": "0.01" + } +``` + +The `Price Filter` checks the validity of the `price` parameter in an order. It consists of the following three parts: + +* `minPrice` defines the minimum allowed value for `price`/`stopPrice`. +* `maxPrice` defines the maximum allowed value for `price`/`stopPrice`. +* `tickSize` defines the step interval for `price`/`stopPrice`, meaning the price must equal minPrice plus an integer multiple of tickSize. + +Each of the above items can be 0; when 0 it means that item is not constrained. + +The logical pseudocode is as follows: + +* `price` \>= `minPrice` +* `price` \<= `maxPrice` +* (`price`\-`minPrice`) % `tickSize` \== 0 + +#### PERCENT\_PRICE price amplitude filter + +**Format in the /exchangeInfo response:** + +```javascript + { + "multiplierDown": "0.9500", + "multiplierUp": "1.0500", + "multiplierDecimal": "4", + "filterType": "PERCENT_PRICE" + } +``` + +The `PERCENT_PRICE` filter defines the valid range of prices based on the index price. + +For the "price percentage" to apply, the "price" must meet the following conditions: + +* `price` \<=`indexPrice` \*`multiplierUp` +* `price`\> \=`indexPrice` \*`multiplierDown` + +#### LOT\_SIZE order size + +**Format in the /exchangeInfo response:** + +```javascript + { + "stepSize": "0.00100000", + "filterType": "LOT_SIZE", + "maxQty": "100000.00000000", + "minQty": "0.00100000" + } +``` + +Lots is an auction term. The `LOT_SIZE` filter validates the `quantity` (i.e., the amount) parameter in orders. It consists of three parts: + +* `minQty` indicates the minimum allowed value for `quantity`. +* `maxQty` denotes the maximum allowed value for `quantity`. +* `stepSize` denotes the allowed step increment for `quantity`. + +The logical pseudocode is as follows: + +* `quantity` \>= `minQty` +* `quantity` \<= `maxQty` +* (`quantity`\-`minQty`) % `stepSize` \== 0 + +#### MARKET\_LOT\_SIZE \- Market order size + +\***/exchangeInfo response format:** + +```javascript + { + "stepSize": "0.00100000", + "filterType": "MARKET_LOT_SIZE" + "maxQty": "100000.00000000", + "minQty": "0.00100000" + } +``` + +The `MARKET_LOT_SIZE` filter defines the `quantity` (i.e., the "lots" in an auction) rules for `MARKET` orders on a trading pair. There are three parts: + +* `minQty` defines the minimum allowed `quantity`. +* `maxQty` defines the maximum allowed quantity. +* `stepSize` defines the increments by which the quantity can be increased or decreased. + +In order to comply with the `market lot size`, the `quantity` must satisfy the following conditions: + +* `quantity` \>= `minQty` +* `quantity` \<= `maxQty` +* (`quantity`\-`minQty`) % `stepSize` \== 0 + +#### predictionEvents \- Prediction Events + +**Format in the /exchangeInfo response:** + +```javascript +"predictionEvents": [ + { + "eventName": "ETH_UP_DOWN_7D", // Prediction event name + "oracleSymbol": "ETHUSDT", // Predicted symbol + "predictionType": "UP_DOWN", // Prediction type + "sides": [ + "UP", + "DOWN" + ], // Prediction directions + "period": "10080M", // Prediction period in minutes + "startTime": 1778476080000, // Event start time + "endTime": 1780376880000, // Event end time + "status": "LIVE", // Event status + "currentRoundId": 3, // Current round ID + "orderTypes": [ + "LIMIT", + "MARKET" + ], // Supported order types + "settleIntervalSeconds": 5, //twap price internal + "settlementDataPointCount": 5, //twap price data count + "reduceOnly": false, //reduceOnly + "timeInForce": [ + "GTC", + "IOC", + "FOK", + "GTX" + ], // Supported TIF values + "liveRound":{ + "marketName": "USD1_UP_DOWN_5M_1778483280", // Prediction market name + "symbols": [ + "USD1_UP_DOWN_5M_1778483280_YUSDT", + "USD1_UP_DOWN_5M_1778483280_NUSDT" + ], // Two symbols for the market; Y = up, N = down + "assets": [ + "USD1_UP_DOWN_5M_1778483280_Y", + "USD1_UP_DOWN_5M_1778483280_N" + ], // Two assets for the market; Y = up, N = down + "roundId": 2, // Round ID + "tradingStartTime": 1778482970000, // Trading start time + "tradingEndTime": 1778483520000, // Trading end time + "windowStartTime": 1778483280000, // Window start time + "windowEndTime": 1778483580000, // Window end time + "roundStatus": "SETTLED", // Market status + "openPrice": "0.99920000", // Opening price + "endPrice": "0.99910000", // Ending price + "winAsset": "USD1_UP_DOWN_5M_1778483280_N", // Winning asset: Y if up, N if down + "settleTime": 1778483582057, // Settlement time + "settleHash": "0x3bc0aff52472dafd4b70d3423386a2dabf675fe7cd604e92391e2a4702cf0980" // On-chain settlement hash + }, + "rounds": [ + { + "marketName": "USD1_UP_DOWN_5M_1778483280", // Prediction market name + "symbols": [ + "USD1_UP_DOWN_5M_1778483280_YUSDT", + "USD1_UP_DOWN_5M_1778483280_NUSDT" + ], // Two symbols for the market; Y = up, N = down + "assets": [ + "USD1_UP_DOWN_5M_1778483280_Y", + "USD1_UP_DOWN_5M_1778483280_N" + ], // Two assets for the market; Y = up, N = down + "roundId": 2, // Round ID + "tradingStartTime": 1778482970000, // Trading start time + "tradingEndTime": 1778483520000, // Trading end time + "windowStartTime": 1778483280000, // Window start time + "windowEndTime": 1778483580000, // Window end time + "roundStatus": "SETTLED", // Market status + "openPrice": "0.99920000", // Opening price + "endPrice": "0.99910000", // Ending price + "winAsset": "USD1_UP_DOWN_5M_1778483280_N", // Winning asset: Y if up, N if down + "settleTime": 1778483582057, // Settlement time + "settleHash": "0x3bc0aff52472dafd4b70d3423386a2dabf675fe7cd604e92391e2a4702cf0980" // On-chain settlement hash + } + ] + } +] +``` + +`status` is the event status: + +| Status | Description | +| :---- | :---- | +| `LIVE` | Running | +| `CLOSED` | Closed | +| `INVALID` | Invalid | + +`roundStatus` is the market status: + +| RoundStatus | Description | +| :---- | :---- | +| `PREMARKET` | Pre-market ready (trading available in advance) | +| `TRADING` | Market is open for trading | +| `SETTLED` | Market has been settled | + +* After settlement, the market will be automatically delisted after a period (24H). Delisted markets are no longer displayed. +* For events with `status` of `CLOSED` or `INVALID`, only `reduceOnly` Market Sell orders can be placed. + +# Market data API + +## Noop + +> **Response:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +``POST /api/v3/noop`` + +By using this request, it is possible to efficiently cancel previously sent transactions that are still in the queue and have not completed the on chain operation (Nonce should be equal to this request,no guarantee of success +) + +**Weight:** +1 + +## Test server connectivity + +**Response** + +```javascript +{} +``` + +`GET /api/v3/ping` + +Test whether the REST API can be reached. + +**Weight:** 1 + +**Parameters:** NONE + +## Get server time + +**Response** + +```javascript +{ + "serverTime": 1499827319559 +} +``` + +`GET /api/v3/time` + +Test if the REST API can be reached and retrieve the server time. + +**Weight:** 1 + +**Parameters:** NONE + +## Trading specification information + +**Response** + +```javascript +{ + "timezone": "UTC", + "serverTime": 1756197279679, + "rateLimits": [{ + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 6000 + }, + { + "rateLimitType": "ORDERS", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 6000 + }, + { + "rateLimitType": "ORDERS", + "interval": "SECOND", + "intervalNum": 10, + "limit": 300 + } + ], + "exchangeFilters": [], + "assets": [{ + "asset": "USD" + }, { + "asset": "USDT" + }, + { + "asset": "BNB" + } + ], + "symbols": [{ + "status": "TRADING", + "baseAsset": "BNB", + "quoteAsset": "USDT", + "pricePrecision": 8, + "quantityPrecision": 8, + "baseAssetPrecision": 8, + "quotePrecision": 8, + "filters": [{ + "minPrice": "0.0001", + "maxPrice": "0.9999", + "filterType": "PRICE_FILTER", + "tickSize": "0.01000000" + }, + { + "stepSize": "0.00100000", + "filterType": "LOT_SIZE", + "maxQty": "1000", + "minQty": "1" + }, + { + "stepSize": "0.00100000", + "filterType": "MARKET_LOT_SIZE", + "maxQty": "900000", + "minQty": "0.00100000" + }, + { + "limit": 200, + "filterType": "MAX_NUM_ORDERS" + }, + { + "minNotional": "5", + "filterType": "MIN_NOTIONAL" + }, + { + "maxNotional": "100", + "filterType": "MAX_NOTIONAL" + }, + { + "maxNotional": "100", + "minNotional": "5", + "avgPriceMins": 5, + "applyMinToMarket": true, + "filterType": "NOTIONAL", + "applyMaxToMarket": true + }, + { + "multiplierDown": "0", + "multiplierUp": "5", + "multiplierDecimal": "0", + "filterType": "PERCENT_PRICE" + }, + { + "bidMultiplierUp": "5", + "askMultiplierUp": "5", + "bidMultiplierDown": "0", + "avgPriceMins": 5, + "multiplierDecimal": "0", + "filterType": "PERCENT_PRICE_BY_SIDE", + "askMultiplierDown": "0" + } + ], + "orderTypes": [ + "LIMIT", + "MARKET" + ], + "timeInForce": [ + "GTC", + "IOC", + "FOK", + "GTX" + ], + "symbol": "BTC_UP_DOWN_5M_1778483280_YUSDT", + "ocoAllowed": false + }] +} +``` + +`GET /api/v3/prediction/exchangeInfo` + +Retrieve trading rules and trading pair information. + +**Weight:** 1 + +**Parameters:** None + +## Depth information + +**Response** + +```javascript +{ + "lastUpdateId": 1027024, + "E":1589436922972, // Message output time + "T":1589436922959, // Transaction time + "bids": [ + [ + "4.00000000", // PRICE + "431.00000000" // QTY + ] + ], + "asks": [ + [ + "4.00000200", + "12.00000000" + ] + ] +} +``` + +`GET /api/v3/depth` + +**Weight:** + +Based on limit adjustments: + +| Limitations | Weight | +| :---- | :---- | +| 5, 10, 20, 50 | 2 | +| 100 | 5 | +| 500 | 10 | +| 1000 | 20 | + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| limit | INT | NO | Default 100\. Optional values: \[5, 10, 20, 50, 100, 500, 1000\] | + +## Recent trades list + +**Response** + +```javascript +[ + { + "id": 657, + "price": "1.01000000", + "qty": "5.00000000", + "baseQty": "4.95049505", + "time": 1755156533943, + "isBuyerMaker": false + } +] +``` + +`GET /api/v3/trades` + +Get recent trades + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| limit | INT | NO | Default 500; maximum 1000 | + +## Query historical trades (MARKET\_DATA) + +**Response** + +```javascript +[ + { + "id": 1140, + "price": "1.10000000", + "qty": "7.27200000", + "baseQty": "6.61090909", + "time": 1756094288700, + "isBuyerMaker": false + } +] +``` + +`GET /api/v3/historicalTrades` + +Retrieve historical trades + +**Weight:** 20 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| limit | INT | NO | Default 500; maximum 1000\. | +| fromId | LONG | NO | Return starting from which trade id. Defaults to returning the most recent trade records. | + +## Recent trades (aggregated) + +**Response** + +```javascript +[ + { + "a": 26129, // Aggregate tradeId + "p": "0.01633102", // Price + "q": "4.70443515", // Quantity + "f": 27781, // First tradeId + "l": 27781, // Last tradeId + "T": 1498793709153, // Timestamp + "m": true, // Was the buyer the maker? + } +] +``` + +`GET /api/v3/aggTrades` + +The difference between aggregated trades and individual trades is that trades with the same price, same side, and same time are combined into a single entry. + +**Weight:** 20 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| fromId | LONG | NO | Return results starting from the trade ID that includes fromId | +| startTime | LONG | NO | Return results starting from trades after that time | +| endTime | LONG | NO | Return the trade records up to that moment | +| limit | INT | NO | Default 500; maximum 1000\. | + +* If you send startTime and endTime, the interval must be less than one hour. +* If no filter parameters (fromId, startTime, endTime) are sent, the most recent trade records are returned by default + +## K-line data + +**Response** + +```javascript +[ + [ + 1499040000000, // Open time + "0.01634790", // Open + "0.80000000", // High + "0.01575800", // Low + "0.01577100", // Close + "148976.11427815", // Volume + 1499644799999, // Close time + "2434.19055334", // Quote asset volume + 308, // Number of trades + "1756.87402397", // Taker buy base asset volume + "28.46694368", // Taker buy quote asset volume + ] +] +``` + +`GET /api/v3/klines` + +Each K-line represents a trading pair. The open time of each K-line can be regarded as a unique ID. + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| interval | ENUM | YES | See the enumeration definition: K-line interval | +| startTime | LONG | NO | | +| endTime | LONG | NO | | +| limit | INT | NO | Default 500; maximum 1500\. | + +* If startTime and endTime are not sent, the most recent trades are returned by default + +## 24h price change + +**Response** + +```javascript +{ + "symbol": "BTC_UP_DOWN_5M_1778483280_YUSDT", //symbol + "priceChange": "-94.99999800", //price change + "priceChangePercent": "-95.960", //price change percent + "weightedAvgPrice": "0.29628482", //weighted avgPrice + "prevClosePrice": "3.89000000", //prev close price + "lastPrice": "4.00000200", //last price + "lastQty": "200.00000000", //last qty + "bidPrice": "0.4999", //first bid price + "bidQty": "431.00", //first bid qty + "askPrice": "0.5001", //first ask price + "askQty": "9.00", //first ask qty + "openPrice": "99.00000000", //open price + "highPrice": "100.00000000", //high price + "lowPrice": "0.10000000", //low price + "volume": "8913.30000000", //volume + "quoteVolume": "15.30000000", //quote volume + "openTime": 1499783499040, //open time + "closeTime": 1499869899040, //close time + "firstId": 28385, // first id + "lastId": 28460, // last id + "count": 76, // count + "baseAsset": "BTC", //base asset + "quoteAsset": "USDT" //quote asset +} +``` + +`GET /api/v3/ticker/24hr` + +24-hour rolling window price change data. Please note that omitting the symbol parameter will return data for all trading pairs; in that case the returned data is an example array for the respective pairs, which is not only large in volume but also has a very high weight. + +**Weight:** 1 \= single trading pair; **40** \= When the trading pair parameter is missing (returns all trading pairs) + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | NO | | + +* Please note that omitting the symbol parameter will return data for all trading pairs + +## Latest price + +**Response** + +```javascript +{ + "symbol": "BTC_UP_DOWN_5M_1778483280_YUSDT", + "price": "1.30000000", + "time": 1649666690902 +} +``` + +OR + +```javascript +[ + { + "symbol": "BTC_UP_DOWN_5M_1778483280_YUSDT", + "price": "1.30000000", + "time": 1649666690902 + } +] +``` + +`GET /api/v3/ticker/price` + +Get the latest price for a trading pair + +**Weight:** 1 \= Single trading pair; **2** \= No symbol parameter (returns all pairs) + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | NO | | + +* If no trading pair parameter is sent, information for all trading pairs will be returned + +## Current best order + +**Response** + +```javascript +{ + "symbol": "BTC_UP_DOWN_5M_1778483280_YUSDT", + "bidPrice": "0.4999", + "bidQty": "431.00", + "askPrice": "0.5001", + "askQty": "9.00" + "time": 1589437530011 // Timestamp +} +``` + +OR + +```javascript +[ + { + "symbol": "BTC_UP_DOWN_5M_1778483280_YUSDT", + "bidPrice": "0.4999", + "bidQty": "431.00", + "askPrice": "0.5001", + "askQty": "9.00", + "time": 1589437530011 // Timestamp + } +] +``` + +`GET /api/v3/ticker/bookTicker` + +Return the current best orders (highest bid, lowest ask) + +**Weight:** 1 \= Single trading pair; **2** \= No symbol parameter (returns all pairs) + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | NO | | + +* If no trading pair parameter is sent, information for all trading pairs will be returned + +## Get symbol fees + +**Response** + +```javascript +{ + "symbol": "BTC_UP_DOWN_5M_1778483280_YUSDT", + "makerCommissionRate": "0.000200", + "takerCommissionRate": "0.000700", + "settleCommissionRate": "0.000100" +} +``` + +`GET /api/v3/commissionRate` + +Get symbol fees + +**Weight:** 20 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | + +# Spot account and trading API + +## Place order (TRADE) + +**Response ACK:** + +```javascript +{ + "symbol": "BTC_UP_DOWN_5M_1778483280_YUSDT", + "orderId": 28, + "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP", + "updateTime": 1507725176595, + "price": "0.00000000", + "avgPrice": "0.0000000000000000", + "origQty": "10.00000000", + "cumQty": "0", + "executedQty": "10.00000000", + "cumQuote": "10.00000000", + "status": "FILLED", + "timeInForce": "GTC", + "stopPrice": "0", + "origType": "LIMIT", + "type": "LIMIT", + "side": "SELL", +} +``` + +`POST /api/v3/order` + +Send order + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| side | ENUM | YES | See enum definition: Order direction | +| type | ENUM | YES | See enumeration definition: Order type | +| timeInForce | ENUM | NO | See enum definition: Time in force | +| quantity | DECIMAL | NO | | +| quoteOrderQty | DECIMAL | NO | | +| price | DECIMAL | NO | | +| newClientOrderId | STRING | NO | Client-customized unique order ID. If not provided, one will be generated automatically. | +| stopPrice | DECIMAL | NO | Only STOP, STOP\_MARKET, TAKE\_PROFIT, TAKE\_PROFIT\_MARKET require this parameter | + +Depending on the order `type`, certain parameters are mandatory: + +| Type | Mandatory parameters | +| :---- | :---- | +| LIMIT | timeInForce, quantity, price | +| MARKET | quantity or quoteOrderQty | +| STOP and TAKE\_PROFIT | quantity, price, stopPrice | +| STOP\_MARKET and TAKE\_PROFIT\_MARKET | quantity, stopPrice | + +Other information: + +* Place a `MARKET` `SELL` market order; the user controls the amount of base assets to sell with the market order via `QUANTITY`. + * For example, when placing a `MARKET` `SELL` market order on the `BTC_UP_DOWN_5M_1778483280_YUSDT` pair, use `QUANTITY` to let the user specify how much BTC they want to sell. +* For a `MARKET` `BUY` market order, the user controls how much of the quote asset they want to spend with `quoteOrderQty`; `QUANTITY` will be calculated by the system based on market liquidity. For example, when placing a `MARKET` `BUY` market order on the `BTC_UP_DOWN_5M_1778483280_YUSDT` pair, use `quoteOrderQty` to let the user choose how much USDT to use to buy BTC. +* A `MARKET` order using `quoteOrderQty` will not violate the `LOT_SIZE` limit rules; the order will be executed as closely as possible to the given `quoteOrderQty`. +* Unless a previous order has already been filled, orders set with the same `newClientOrderId` will be rejected. + +## Cancel order (TRADE) + +**Response** + +```javascript +{ + "symbol": "BTC_UP_DOWN_5M_1778483280_YUSDT", + "orderId": 28, + "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP", + "updateTime": 1507725176595, + "price": "0.00000000", + "avgPrice": "0.0000000000000000", + "origQty": "10.00000000", + "cumQty": "0", + "executedQty": "10.00000000", + "cumQuote": "10.00000000", + "status": "CANCELED", + "timeInForce": "GTC", + "stopPrice": "0", + "origType": "LIMIT", + "type": "LIMIT", + "side": "SELL", +} +``` + +`DELETE /api/v3/order` + +Cancel active orders + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| orderId | LONG | NO | | +| origClientOrderId | STRING | NO | | + +At least one of `orderId` or `origClientOrderId` must be sent. + +## Query order (USER\_DATA) + +**Response** + +```javascript +{ + "orderId": 38, + "symbol": "BTC_UP_DOWN_5M_1778483280_YUSDT", + "status": "FILLED", + "clientOrderId": "afMd4GBQyHkHpGWdiy34Li", + "price": "20", + "avgPrice": "12.0000000000000000", + "origQty": "10", + "executedQty": "10", + "cumQuote": "120", + "timeInForce": "GTC", + "type": "LIMIT", + "side": "BUY", + "stopPrice": "0", + "origType": "LIMIT", + "time": 1649913186270, + "updateTime": 1649913186297 +} +``` + +`GET /api/v3/order` + +Query order status + +* Please note that orders meeting the following conditions will not be returned: + * The final status of the order is `CANCELED` or `EXPIRED`, **and** + * The order has no trade records, **and** + * Order creation time \+ 7 days \< current time + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| orderId | LONG | NO | | +| origClientOrderId | STRING | NO | | + +Note: + +* You must send at least one of `orderId` or `origClientOrderId`. + +## Query Current Open Order (USER\_DATA) + +**Response** + +```javascript +{ + "orderId": 38, + "symbol": "BTC_UP_DOWN_5M_1778483280_YUSDT", + "status": "NEW", + "clientOrderId": "afMd4GBQyHkHpGWdiy34Li", + "price": "20", + "avgPrice": "12.0000000000000000", + "origQty": "10", + "executedQty": "10", + "cumQuote": "120", + "timeInForce": "GTC", + "type": "LIMIT", + "side": "BUY", + "stopPrice": "0", + "origType": "LIMIT", + "time": 1649913186270, + "updateTime": 1649913186297 +} +``` + +`GET /api/v3/openOrder` + +Query current open order status. + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| orderId | LONG | NO | | +| origClientOrderId | STRING | NO | | + +Note: + +* You must send at least one of `orderId` or `origClientOrderId`. + +## Current open orders (USER\_DATA) + +**Response** + +```javascript +[ + { + "orderId": 349661, + "symbol": "BTC_UP_DOWN_5M_1778483280_YUSDT", + "status": "NEW", + "clientOrderId": "LzypgiMwkf3TQ8wwvLo8RA", + "price": "1.10000000", + "avgPrice": "0.0000000000000000", + "origQty": "5", + "executedQty": "0", + "cumQuote": "0", + "timeInForce": "GTC", + "type": "LIMIT", + "side": "BUY", + "stopPrice": "0", + "origType": "LIMIT", + "time": 1756252940207, + "updateTime": 1756252940207, + } +] +``` + +`GET /api/v3/openOrders` + +Retrieve all current open orders for trading pairs. Use calls without a trading pair parameter with caution. + +**Weight:** + +* With symbol ***1*** +* Without ***40*** + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | NO | | + +* If the symbol parameter is not provided, it will return the order books for all trading pairs. + +## Cancel All Open Orders (TRADE) + +> **Response** + +```javascript +{ + "code": 200, + "msg": "The operation of cancel all open order is done." +} +``` + +`` +DEL /api/v3/allOpenOrders `` + +**Weight:** +- ***1*** + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +orderIdList | STRING | NO | orderid array string +origClientOrderIdList | STRING | NO | clientOrderId array string + + +## Query all orders (USER\_DATA) + +**Response** + +```javascript +[ + { + "orderId": 349661, + "symbol": "BTC_UP_DOWN_5M_1778483280_YUSDT", + "status": "NEW", + "clientOrderId": "LzypgiMwkf3TQ8wwvLo8RA", + "price": "1.10000000", + "avgPrice": "0.0000000000000000", + "origQty": "5", + "executedQty": "0", + "cumQuote": "0", + "timeInForce": "GTC", + "type": "LIMIT", + "side": "BUY", + "stopPrice": "0", + "origType": "LIMIT", + "time": 1756252940207, + "updateTime": 1756252940207, + } +] +``` + +`GET /api/v3/allOrders` + +Retrieve all account orders; active, canceled, or completed. + +* Please note that orders meeting the following conditions will not be returned: + * Order creation time \+ 7 days \< current time + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | | +| orderId | LONG | NO | | +| startTime | LONG | NO | | +| endTime | LONG | NO | | +| limit | INT | NO | Default 500; maximum 1000 | + +* The maximum query time range must not exceed 7 days. +* By default, query data is from the last 7 days. + + +`` +GET /api/v3/prediction/transactionHistory`` +> **Response** + +```javascript +[ + { + "tranId": 1759115482304540227, + "tradeId": null, + "asset": "ASTER", + "symbol": "BTC_UP_DOWN_5M_1778483280_YUSDT", + "balanceDelta": "-500.00000000", + "balanceInfo": "TRADE_SOURCE", + "time": 1759115482000, + "type": "TRADE_SOURCE" + } +] +``` + +Query transaction records + +**Weight:** +30 + +**Parameters:** + +| Name | Type | Is it required? | Description | +------------ | ------------ | ------------ | ------------ +asset | STRING | NO | asset +type | STRING | NO | type +startTime | LONG | NO | startTime +endTime | LONG | NO | endTime +limit | LONG | NO | default:100 max:1000 + +**Note:** + +* `type`: `TRADE_TARGET`,`TRADE_SOURCE`,`TRANSFER_SPOT_TO_FUTURE`,`TRANSFER_FUTURE_TO_SPOT`,`TRANSFER_SPOT_TO_SPOT`,`AIRDROP`,`DIVIDEND`,`TRANSFER_REFUND`,`INTERNAL_TRANSFER`,`TRANSFER`,`SWAP`,`COMMISSION_REBATE`,`CASH_BACK`,`STAKING_WITHDRAW`, `STAKING_CLAIM`, `STAKING_DELEGATE`,`PREDICTION_CLAIM`,`PREDICTION_USER_REBATE`,`PREDICTION_SETTLE`,`PREDICTION_SETTLE_FEE`,`PREDICTION_MINT`,`PREDICTION_BURN` +* If startTime and endTime are not provided, only data from the most recent 7 days will be returned. + +## Perp-spot transfer (TRADE) + +**Response:** + +```javascript +{ + "tranId": 21841, //Tran Id + "status": "SUCCESS" //Status +} +``` + +`POST /api/v3/asset/wallet/transfer ` + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| amount | DECIMAL | YES | Quantity | +| asset | STRING | YES | Asset | +| clientTranId | STRING | YES | Transaction ID | +| kindType | STRING | YES | Transaction type | + +* kindType FUTURE_SPOT(future to spot)/SPOT_FUTURE(spot to future) + +## Prediction market mint (TRADE) + +**Response** + +```javascript +{ + "clientOrderId": "xxx", // Client order ID + "quoteAmount": "10.00000000", // Total quote asset spent + "yesPrice": "0.55000000", // YES token price at mint time + "noPrice": "0.45000000", // NO token price at mint time (yesPrice + noPrice = 1) + "pairCount": "10.00000000" // Number of YES+NO pairs minted +} +``` + +`POST /api/v3/prediction/mint` + +Mint YES+NO token pairs for a prediction market. The system deducts an equivalent amount of quote asset at the current market price and credits equal quantities of YES and NO tokens to the account. + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | The YES token trading pair of the prediction market | +| quantity | DECIMAL | YES | Number of YES+NO token pairs to mint | +| newClientOrderId | STRING | NO | Client-customized unique order ID. If not provided, one will be generated automatically. | + +Notes: +* `symbol` must be a valid prediction market token trading pair with status `TRADING` or `PENDING_TRADING` +* `quantity` represents the number of pairs to mint simultaneously; the account will receive equal amounts of YES and NO tokens +* `yesPrice` + `noPrice` = 1 (in quote asset units) + + +## Prediction market burn (TRADE) + +**Response** + +```javascript +{ + "clientOrderId": "xxx", // Client order ID + "quoteAmount": "9.80000000", // Total quote asset returned after burn + "yesPrice": null, // Not returned for burn operations + "noPrice": null, // Not returned for burn operations + "pairCount": "10.00000000" // Number of YES+NO pairs burned +} +``` + +`POST /api/v3/prediction/burn` + +Burn equal quantities of YES+NO token pairs to redeem the corresponding quote asset. The account must hold equal amounts of YES and NO tokens to perform a burn. + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | YES | The YES token trading pair of the prediction market | +| quantity | DECIMAL | YES | Number of YES+NO token pairs to burn | +| newClientOrderId | STRING | NO | Client-customized unique order ID. If not provided, one will be generated automatically. | + +Notes: +* `symbol` must be a valid prediction market token trading pair with status `TRADING`, `PENDING_TRADING`, or `CLOSED` +* `quantity` represents the number of pairs to burn simultaneously; the account must hold the corresponding amounts of both YES and NO tokens +* `yesPrice` and `noPrice` are `null` in the burn response +* Burn operations are still available after the market is `CLOSED` + + +## Query prediction market current positions (USER\_DATA) + +**Response** + +```javascript +[ + { + "marketName": "BTC_UP_DOWN_20260512", // Prediction market name + "symbol": "BTC_UP_DOWN_5M_1778483280_YUSDT", // Trading pair + "assetName": "USDT", // Settlement asset + "type": "YES", // Position direction: "YES" or "NO" + "openAvgPrice": "0.65000000", // Average open price + "cumQty": "100.00000000", // Total position quantity + "closeAvgPrice": "0.00000000", // Average close price (0 if not closed) + "realizedPnl": "0.00000000", // Realized PnL + "closeQty": "0.00000000", // Closed quantity + "insertTime": 1747000000000, // Position open time (millisecond timestamp) + "commissionFee": "0.10000000", // Commission fee paid + "commissionAsset": "USDT", // Commission fee asset + "balance": "65.00000000", // Position value (quantity × average open price) + "availableBalance": "65.00000000", // Available balance + } +] +``` + +`GET /api/v3/prediction/positions` + +Query the current account's prediction market position list. + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | NO | Trading pair; if not provided, returns all positions | +| signer | STRING | YES | API wallet address | +| nonce | STRING | YES | Current time in microseconds | +| signature | STRING | YES | Signature | + +## Query prediction market position history (USER\_DATA) + +**Response** + +```javascript +[ + { + "marketName": "BTC_UP_DOWN_20260501", // Prediction market name + "symbol": "BTC_UP_DOWN_5M_1778483280_YUSDT", // Trading pair + "assetName": "USDT", // Settlement asset + "type": "YES", // Position direction: "YES" or "NO" + "openAvgPrice": "0.72000000", // Average open price + "cumQty": "200.00000000", // Total position quantity + "closeAvgPrice": "1.00000000", // Average close price + "realizedPnl": "56.00000000", // Realized PnL + "closeQty": "200.00000000", // Closed quantity + "insertTime": 1746000000000, // Position open time (millisecond timestamp) + "closeTime": 1746086400000, // Close/settlement time (millisecond timestamp) + "status": "settled", // Position status: "close" (manually closed) or "settled" (market settled) + "commissionFee": "0.10000000", // Commission fee paid + "commissionAsset": "USDT", // Commission fee asset + "settleFee": "2.00000000", // Settlement fee (only present when status is "settled") + "settleAsset": "USDT", // Settlement fee asset + } +] +``` + +`GET /api/v3/prediction/positionHistories` + +Query the current account's prediction market historical position list (closed or settled). + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | NO | Trading pair; if not provided, returns all historical positions | +| startTime | LONG | NO | Start time (millisecond timestamp) | +| endTime | LONG | NO | End time (millisecond timestamp) | +| limit | INT | NO | Number of results; default 100, maximum 1000 | +| signer | STRING | YES | API wallet address | +| nonce | STRING | YES | Current time in microseconds | +| signature | STRING | YES | Signature | + +Notes: +* When both `startTime` and `endTime` are provided, `startTime` must not be greater than `endTime` +* `limit` range is 1 to 1000, default is 100 +* `status` field: `close` means the user manually closed the position; `settled` means the prediction market expired and settled + +## Query prediction market settlement histories (USER\_DATA) + +**Response** + +```javascript +[ + { + "marketName": "BTC_UP_DOWN_20260501", // Prediction market name + "asset": "BTC_UP_DOWN_20260501YES", // Token asset (YES or NO token) + "symbol": "BTC_UP_DOWN_20260501YES", // Trading pair + "marketStartTime": 1746000000000, // Market start time (millisecond timestamp) + "marketEndTime": 1746086400000, // Market end time / settlement time (millisecond timestamp) + "shareAmount": "200.00000000", // Share quantity held at settlement + "settleAsset": "USDT", // Settlement asset + "settleAmount": "200.00000000", // Settlement amount received + "settleFeeAmount": "2.00000000", // Settlement fee charged + "entryPrice": "0.72000000", // Average entry price + "settlePrice": "1.00000000", // Final settlement price + "realizedPnl": "56.00000000", // Realized PnL after settlement + "status": "settled" // Settlement status + } +] +``` + +`GET /api/v3/prediction/settlementHistories` + +Query the current account's prediction market settlement history (markets that have expired and settled). + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | NO | Trading pair; if not provided, returns all settlement records | +| startTime | LONG | NO | Filter by market start time (millisecond timestamp) | +| endTime | LONG | NO | Filter by market end time (millisecond timestamp) | +| limit | INT | NO | Number of results; default 100, maximum 1000 | +| signer | STRING | YES | API wallet address | +| nonce | STRING | YES | Current time in microseconds | +| signature | STRING | YES | Signature | + +Notes: +* When both `startTime` and `endTime` are provided, `startTime` must not be greater than `endTime` +* `limit` range is 1 to 1000, default is 100 +* `settleAmount` is the gross payout; `realizedPnl` equals `settleAmount` minus the cost basis +* `settleFeeAmount` is deducted from the settlement payout + +## Get withdraw fee (NONE) +> **Response:** +```javascript +{ + "tokenPrice": 1.00019000, + "gasCost": 0.5000, + "gasUsdValue": 0.5 +} +``` + +`` +GET /api/v3/aster/withdraw/estimateFee +`` + +**Weight:** +1 + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +chainId | STRING | YES | +asset | STRING | YES | + +**Notes:** +* chainId: 1(ETH),56(BSC),42161(Arbi) +* gasCost: The minimum fee required for a withdrawal + +## Withdraw (USER_DATA) +> **Response:** +```javascript +{ + "withdrawId": "1014729574755487744", + "hash":"0xa6d1e617a3f69211df276fdd8097ac8f12b6ad9c7a49ba75bbb24f002df0ebb" +} +``` + +`` +POST /api/v3/aster/user-withdraw`` + +**Weight:** +5 + +**Parameters:** + +Name | Type | Mandatory | Description +------------ | ------------ | ------------ | ------------ +chainId | STRING | YES | 1(ETH),56(BSC),42161(Arbi) +asset | STRING | YES | +amount | STRING | YES | +fee | STRING | YES | +receiver | STRING | YES | The address of the current account +nonce | STRING | YES | The current time in microseconds +userSignature | STRING | YES | + + +**Note:** +* chainId: 1(ETH),56(BSC),42161(Arbi) +* receiver: The address of the current account +* If the futures account balance is insufficient, funds will be transferred from the spot account to the perp account for withdrawal. +* userSignature demo + +```shell +const domain = { + name: 'Aster', + version: '1', + chainId: 56, + verifyingContract: ethers.ZeroAddress, + } + +const currentTime = Date.now() * 1000 + +const types = { + Action: [ + {name: "type", type: "string"}, + {name: "destination", type: "address"}, + {name: "destination Chain", type: "string"}, + {name: "token", type: "string"}, + {name: "amount", type: "string"}, + {name: "fee", type: "string"}, + {name: "nonce", type: "uint256"}, + {name: "aster chain", type: "string"}, + ], + } + const value = { + 'type': 'Withdraw', + 'destination': '0xD9cA6952F1b1349d27f91E4fa6FB8ef67b89F02d', + 'destination Chain': 'BSC', + 'token': 'USDT', + 'amount': '10.123400', + 'fee': '1.234567891', + 'nonce': currentTime, + 'aster chain': 'Mainnet', + } + + +const signature = await signer.signTypedData(domain, types, value) +``` + +## Account information (USER\_DATA) + +**Response** + +```javascript +{ + "feeTier": 0, + "canTrade": true, + "canDeposit": true, + "canWithdraw": true, + "canBurnAsset": true, + "updateTime": 0, + "balances": [ + { + "asset": "BTC", + "free": "4723846.89208129", + "locked": "0.00000000" + }, + { + "asset": "LTC", + "free": "4763368.68006011", + "locked": "0.00000000" + } + ] +} +``` + +`GET /api/v3/account` + +Retrieve current account information + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | + +## Account trade history (USER\_DATA) + +**Response** + +```javascript +[ + { + "symbol": "BTC_UP_DOWN_5M_1778483280_YUSDT", + "id": 1002, + "orderId": 266358, + "side": "BUY", + "price": "1", + "qty": "2", + "quoteQty": "2", + "commission": "0.00105000", + "commissionAsset": "BNB", + "time": 1755656788798, + "counterpartyId": 19, + "createUpdateId": null, + "maker": false, + "buyer": true + } +] +``` + +`GET /api/v3/userTrades` + +Retrieve the trade history for a specified trading pair of an account + +**Weight:** 5 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| symbol | STRING | NO | | +| orderId | LONG | NO | Must be used together with the parameter symbol | +| startTime | LONG | NO | | +| endTime | LONG | NO | | +| fromId | LONG | NO | Starting trade ID. Defaults to fetching the most recent trade. | +| limit | INT | NO | Default 500; maximum 1000 | + +* If both `startTime` and `endTime` are not sent, only data from the last 7 days will be returned. +* The maximum interval between startTime and endTime is 7 days. +* `fromId` cannot be sent together with `startTime` or `endTime`. + +--- + +# WebSocket market data feed + +* The base URL for all wss endpoints listed in this document is: **wss://pstream.asterdex.com** +* Streams have either a single raw stream or a combined stream +* Single raw streams format is \*\*/ws/\*\* +* The URL format for combined streams is \*\*/stream?streams=//\*\* +* When subscribing to combined streams, the event payload is wrapped in this format: \*\*{"stream":"","data":}\*\* +* All trading pairs in stream names are **lowercase** +* Each link to **pstream.asterdex.com** is valid for no more than 24 hours; please handle reconnections appropriately +* Every 3 minutes the server sends a ping frame; the client must reply with a pong frame within 10 minutes, otherwise the server will close the connection. The client is allowed to send unpaired pong frames (i.e., the client may send pong frames at a frequency higher than once every 10 minutes to keep the connection alive). + +## Real-time subscribe/unsubscribe data streams + +* The following messages can be sent via WebSocket to subscribe or unsubscribe to data streams. Examples are shown below. +* The `id` in the response content is an unsigned integer that serves as the unique identifier for exchanges of information. +* If the `result` in the response content is `null`, it indicates the request was sent successfully. + +### Subscribe to a stream + +**Response** + +```javascript +{ + "result": null, + "id": 1 +} +``` + +* **Request** { "method": "SUBSCRIBE", "params": \[ "btc_up_dowm_5m_1778483280_yusdt@aggTrade", "btc_up_dowm_5m_1778483280_yusdt@depth" \], "id": 1 } + +### Unsubscribe from a stream + +**Response** + +```javascript +{ + "result": null, + "id": 312 +} +``` + +* **Request** { "method": "UNSUBSCRIBE", "params": \[ "btc_up_dowm_5m_1778483280_yusdt@depth" \], "id": 312 } + +### Subscribed to the feed + +**Response** + +```javascript +{ + "result": [ + "btc_up_dowm_5m_1778483280_yusdt@aggTrade" + ], + "id": 3 +} +``` + +* **Request** + + { "method": "LIST\_SUBSCRIPTIONS", "id": 3 } + +### Set properties + +Currently, the only configurable property is whether to enable the `combined` ("combined") stream. When connecting using `/ws/` ("raw stream"), the combined property is set to `false`, while connecting using `/stream/` sets the property to `true`. + +**Response** + +```javascript +{ +"result": null, +"id": 5 +} +``` + +* **Request** { "method": "SET\_PROPERTY" "params": \[ "combined", true \], "id": 5 } + +### Retrieve properties + +**Response** + +```javascript +{ + "result": true, // Indicates that combined is set to true. + "id": 2 +} +``` + +* **Request** + + { "method": "GET\_PROPERTY", "params": \[ "combined" \], "id": 2 } + +\#\#\# Error message + +| Error message | Description | +| :---- | :---- | +| {"code": 0, "msg": "Unknown property"} | Parameters applied in SET\_PROPERTY or GET\_PROPERTY are invalid | +| {"code": 1, "msg": "Invalid value type: expected Boolean", "id": '%s'} | Only true or false are accepted | +| {"code": 2, "msg": "Invalid request: property name must be a string"} | The provided attribute name is invalid | +| {"code": 2, "msg": "Invalid request: request ID must be an unsigned integer"} | Parameter ID not provided or ID has an invalid type | +| {"code": 2, "msg": "Invalid request: unknown variant %s, expected one of SUBSCRIBE, UNSUBSCRIBE, LIST\_SUBSCRIPTIONS, SET\_PROPERTY, GET\_PROPERTY at line 1 column 28"} | Typo warning, or the provided value is not of the expected type | +| {"code": 2, "msg": "Invalid request: too many parameters"} | Unnecessary parameters were provided in the data | +| {"code": 2, "msg": "Invalid request: property name must be a string"} | Property name not provided | +| {"code": 2, "msg": "Invalid request: missing field method at line 1 column 73"} | Data did not provide method | +| {"code":3,"msg":"Invalid JSON: expected value at line %s column %s"} | JSON syntax error | + +## Collection transaction flow + +**Payload:** + +```javascript +{ + "e": "aggTrade", // Event type + "E": 123456789, // Event time + "s": "BTC_UP_DOWN_5M_1778483280_YUSDT", // Symbol + "a": 12345, // Aggregate trade ID + "p": "0.001", // Price + "q": "100", // Quantity + "f": 100, // First trade ID + "l": 105, // Last trade ID + "T": 123456785, // Trade time + "m": true, // Is the buyer the market maker? + "M": true // Ignore +} +``` + +The collection transaction stream pushes transaction information and is an aggregation of a single order. + +**Stream name:** `@aggTrade` + +**Update speed:** real-time + +## Tick-by-tick trades + +**Payload:** + +```javascript +{ + "e": "trade", // Event type + "E": 123456789, // Event time + "s": "BTC_UP_DOWN_5M_1778483280_YUSDT", // Symbol + "t": 12345, // Trade ID + "p": "0.001", // Price + "q": "100", // Quantity + "T": 123456785, // Trade time + "m": true, // Is the buyer the market maker? +} +``` + +**Stream name:** `@trade` + +Each trade stream pushes the details of every individual trade. A **trade**, also called a transaction, is defined as a match between exactly one taker and one maker. + +## K-line streams + +**Payload:** + +```javascript +{ + "e": "kline", // Event type + "E": 123456789, // Event time + "s": "BTC_UP_DOWN_5M_1778483280_YUSDT", // Symbol + "k": { + "t": 123400000, // Kline start time + "T": 123460000, // Kline close time + "s": "BTC_UP_DOWN_5M_1778483280_YUSDT", // Symbol + "i": "1m", // Interval + "f": 100, // First trade ID + "L": 200, // Last trade ID + "o": "0.0010", // Open price + "c": "0.0020", // Close price + "h": "0.0025", // High price + "l": "0.0015", // Low price + "v": "1000", // Base asset volume + "n": 100, // Number of trades + "x": false, // Is this kline closed? + "q": "1.0000", // Quote asset volume + "V": "500", // Taker buy base asset volume + "Q": "0.500", // Taker buy quote asset volume + "B": "123456" // Ignore + } +} +``` + +The K-line stream pushes per-second updates for the requested type of K-line (the latest candle). + +**Stream name:** `@kline_` + +**Update speed:** 2000ms + +**K-line interval parameter:** + +m (minutes), h (hours), d (days), w (weeks), M (months) + +* 1m +* 3m +* 5m +* 15m +* 30m +* 1h +* 2h +* 4h +* 6h +* 8h +* 12h +* 1d +* 3d +* 1w +* 1M + +## Simplified ticker by symbol + +**Payload:** + +```javascript + { + "e": "24hrMiniTicker", // Event type + "E": 123456789, // Event time + "s": "BTC_UP_DOWN_5M_1778483280_YUSDT", // Symbol + "c": "0.0025", // Close price + "o": "0.0010", // Open price + "h": "0.0025", // High price + "l": "0.0010", // Low price + "v": "10000", // Total traded base asset volume + "q": "18" // Total traded quote asset volume + } +``` + +Refreshed simplified 24-hour ticker information by symbol + +**Stream name:** `@miniTicker` + +**Update speed:** 1000ms + +## Compact tickers for all symbols in the entire market + +**Payload:** + +```javascript +[ + { + // Same as @miniTicker payload + } +] +``` + +Same as above, but pushes all trading pairs. Note that only updated tickers will be pushed. + +**Stream name:** \!miniTicker@arr + +**Update speed:** 1000ms + +## Full ticker per symbol + +**Payload:** + +```javascript +{ + "e": "24hrTicker", // Event type + "E": 123456789, // Event time + "s": "BTC_UP_DOWN_5M_1778483280_YUSDT", // Symbol + "p": "0.0015", // Price change + "P": "250.00", // Price change percent + "w": "0.0018", // Weighted average price + "c": "0.0025", // Last price + "Q": "10", // Last quantity + "o": "0.0010", // Open price + "h": "0.0025", // High price + "l": "0.0010", // Low price + "v": "10000", // Total traded base asset volume + "q": "18", // Total traded quote asset volume + "O": 0, // Statistics open time + "C": 86400000, // Statistics close time + "F": 0, // First trade ID + "L": 18150, // Last trade Id + "n": 18151 // Total number of trades +} +``` + +Pushes per-second tag statistics for a single trading pair over a rolling 24-hour window. + +**Stream name:** `@ticker` + +**Update speed:** 1000ms + +## Complete ticker for all trading pairs on the entire market + +**Payload:** + +```javascript +[ + { + // Same as @ticker payload + } +] +``` + +Pushes the full 24-hour refreshed ticker information for all trading pairs across the entire market. Note that tickers without updates will not be pushed. + +**Stream name:** `!ticker@arr` + +**Update speed:** 1000ms + +## Best order book information by symbol + +**Payload:** + +```javascript +{ + "u":400900217, // order book updateId + "s": "BTC_UP_DOWN_5M_1778483280_YUSDT", // symbol + "b":"25.35190000", // best bid price + "B":"31.21000000", // best bid qty + "a":"25.36520000", // best ask price + "A":"40.66000000" // best ask qty +} +``` + +Real-time push of best order book information for the specified trading pair + +**Stream name:** `@bookTicker` + +**Update speed:** Real-time + +## Best order book information across the entire market + +**Payload:** + +```javascript +{ + // Same as @bookTicker payload +} +``` + +Real-time push of the best order information for all trading pairs + +**Stream name:** `!bookTicker` + +**Update speed:** Real-time + +## Limited depth information + +**Payload:** + +```javascript +{ + "e": "depthUpdate", // Event type + "E": 123456789, // Event time + "T": 123456788, // Transaction time + "s": "BTC_UP_DOWN_5M_1778483280_YUSDT", // Symbol + "U": 100, // First update ID in event + "u": 120, // Final update ID in event + "pu": 99, // Final update Id in last stream(ie `u` in last stream) + "bids": [ // Bids to be updated + [ + "0.0024", // Price level to be updated + "10" // Quantity + ] + ], + "asks": [ // Asks to be updated + [ + "0.0026", // Price level to be updated + "100" // Quantity + ] + ] +} +``` + +Limited depth information pushed every second or every 100 milliseconds. Levels indicate how many levels of bid/ask information, optional 5/10/20 levels. + +**Stream names:** `@depth` or `@depth@100ms`. + +**Update speed:** 1000ms or 100ms + +## Incremental depth information + +**Payload:** + +```javascript +{ + "e": "depthUpdate", // Event type + "E": 123456789, // Event time + "T": 123456788, // Transaction time + "s": "BTC_UP_DOWN_5M_1778483280_YUSDT", // Symbol + "U": 100, // First update ID in event + "u": 120, // Final update ID in event + "pu": 99, // Final update Id in last stream(ie `u` in last stream) + "b": [ // Bids to be updated + [ + "5.4", // Price level to be updated + "10" // Quantity + ] + ], + "a": [ // Asks to be updated + [ + "5.6", // Price level to be updated + "100" // Quantity + ] + ] +} +``` + +Pushes the changed parts of the orderbook (if any) every second or every 100 milliseconds + +**Stream name:** `@depth` or `@depth@100ms` + +**Update speed:** 1000ms or 100ms + +## How to correctly maintain a local copy of an order book + +1. Subscribe to **wss://pstream.asterdex.com/ws/btc_up_dowm_5m_1778483280_yusdt@depth** +2. Start caching the received updates. For the same price level, later updates overwrite earlier ones. +3. Fetch the REST endpoint [**https://papi.asterdex.com/api/v3/depth?symbol=BTC_UP_DOWN_5M_1778483280_YUSDT\&limit=1000**](https://papi.asterdex.com/api/v3/depth?symbol=BTC_UP_DOWN_5M_1778483280_YUSDT&limit=1000) to obtain a 1000-level depth snapshot +4. Discard from the currently cached messages those with `u` \<= the `lastUpdateId` obtained in step 3 (drop older, expired information) +5. Apply the depth snapshot to your local order book copy, and resume updating the local copy from the first WebSocket event whose `U` \<= `lastUpdateId`\+1 **and** `u` \>= `lastUpdateId`\+1 +6. Each new event's `U` should equal exactly the previous event's `u`\+1; otherwise packets may have been lost \- restart initialization from step 3 +7. The order quantity in each event represents the current order quantity at that price as an **absolute value**, not a relative change +8. If the order quantity at a given price is 0, it means the orders at that price have been canceled or filled, and that price level should be removed + +# WebSocket account information push + +* The base URL for the API endpoints listed in this document is: [**https://papi.asterdex.com**](https://papi.asterdex.com) +* The `listenKey` used to subscribe to account data is valid for 60 minutes from the time of creation +* You can extend the 60-minute validity of a `listenKey` by sending a `PUT` request +* You can immediately close the current data stream and invalidate the `listenKey` by sending a `DELETE` for a `listenKey` +* Sending a `POST` on an account with a valid `listenKey` will return the currently valid `listenKey` and extend its validity by 60 minutes +* The WebSocket interface baseurl: **wss://pstream.asterdex.com** +* The stream name for subscribing to the user account data stream is \*\*/ws/\*\* +* Each connection is valid for no more than 24 hours; please handle disconnections and reconnections appropriately + +## Listen Key (spot account) + +### Generate Listen Key (USER\_STREAM) + +**Response** + +```javascript +{ + "listenKey": "pqia91ma19a5s61cv6a81va65sdf19v8a65a1a5s61cv6a81va65sdf19v8a65a1" +} +``` + +`POST /api/v3/listenKey` + +Start a new data stream. The data stream will be closed after 60 minutes unless a keepalive is sent. If the account already has a valid `listenKey`, that `listenKey` will be returned and its validity extended by 60 minutes. + +**Weight:** 1 + +**Parameters:** NONE + +### Extend Listen Key validity period (USER\_STREAM) + +**Response** + +```javascript +{} +``` + +`PUT /api/v3/listenKey` + +Validity extended to 60 minutes after this call. It is recommended to send a ping every 30 minutes. + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| listenKey | STRING | YES | | + +### Close Listen Key (USER\_STREAM) + +**Response** + +```javascript +{} +``` + +`DELETE /api/v3/listenKey` + +Close user data stream + +**Weight:** 1 + +**Parameters:** + +| Name | Type | Is it required? | Description | +| :---- | :---- | :---- | :---- | +| listenKey | STRING | YES | | + +## Payload: ACCOUNT\_UPDATE + +An `outboundAccountPosition` event is sent whenever an account balance changes; it contains the assets that may have changed due to the event that generated the balance update. + +**Payload** + +```javascript +{ + "B":[ //Balance + { + "a":"SLP25", //Asset + "f":"10282.42029415", //Free + "l":"653.00000001" //Locked + }, + { + "a":"ADA25", + "f":"9916.96229880", + "l":"34.00510000" + } + ], + "e":"outboundAccountPosition", //Event type + "T":1649926447190, //Time of last account update + "E":1649926447205 //Event Time + "m":"WITHDRAW" // Event reason type +} +``` + +## Payload: Order Update + +Orders are updated via the `executionReport` event + +**Payload** + +```javascript +{ + "s": "BTC_UP_DOWN_5M_1778483280_YUSDT", // symbol + "c":"Xzh0gnxT41PStbwqOtXnjD", // client order id + "S":"SELL", // order direction + "o":"LIMIT", // order type + "f":"GTC", // Time in force + "q":"10.001000", // Order quantity + "p":"19.1000000000", // Order price + "ap":"19.0999999955550656", //average price + "P":"0", //stop price + "x":"TRADE", // Current execution type + "X":"PARTIALLY_FILLED", // Current order status + "i":27, // Order ID + "l":"1", // Last executed quantity + "z":"8.999000", // Cumulative filled quantity + "L":"19.1000000000", // Last executed price + "n":"0.00382000", // Commission amount + "N":"SLP25", // Commission asset + "T":1649926447190, //Transaction Time + "t":18, // transaction id + "m":true, // is this trade the maker side? + "ot":"LIMIT", //original order type + "O":0, // Order creation time + "Z":"171.88089996", // Cumulative quote asset transacted quantity + "Y":"19.1000000000000000", // Last quote asset transacted quantity (i.e. lastPrice * lastQty) + "Q":"0", // Quote Order Qty + "e":"executionReport", // event + "E":1649926447209 // event time +} +``` + +**Execution type:** + +* NEW \- New Order +* CANCELED \- Order canceled +* REJECTED \- New order was rejected +* TRADE \- Order had a new fill +* EXPIRED \- Order expired (based on the order's Time In Force parameter) + +## Event: TradePro + +> **Topic Subscribe:** + +```javascript +{ + "method": "SUBSCRIBE", + "params": [ + "btc_up_dowm_5m_1778483280_yusdt@tradepro" + ], + "id": 3 +} +``` + +> **Payload:** + +```javascript +{ + "stream": "btc_up_dowm_5m_1778483280_yusdt@tradepro", + "data": { + "e": "tradepro", + "E": 1773751963081, + "T": 1773751963079, + "s": "BTC_UP_DOWN_5M_1778483280_YUSDT", + "t": 128884613, + "p": "73685.5", + "q": "0.297", + "h": "0X0000000000000000000000000000000000000000000000000000000000000000", + "m": [ + "hidden", + "hidden" + ] + } +} +``` + +* h: Transaction hash of the trade. + +* m: Array containing the participant addresses: + + * m[0]: Taker address + + * m[1]: Maker address + + +## Event: Prediction Event Twap Update + +> **Topic Subscribe:** + +* eventName@event + +```javascript +{ + "method": "SUBSCRIBE", + "params": [ + "btc_up_down_5m@event" + ], + "id": 3 +} +``` + +> **Payload:** + +```javascript +{ + 'e': 'market_start', // Event start; pushes the initial price + 'm': 'ETH_UP_DOWN_5M_1779846360', // Event name + 'y': 'ETH_UP_DOWN_5M_1779846360_YUSDT', // Long (UP) symbol name + 'n': 'ETH_UP_DOWN_5M_1779846360_NUSDT', // Short (DOWN) symbol name + 'p': '2073.68023256', // Initial price + 't': 1779846360000 // Push timestamp +} + +{ + 'e': 'market_twap', // TWAP data update; pushes each TWAP sample point + 'm': 'ETH_UP_DOWN_5M_1779846660', // Event name + 'y': 'ETH_UP_DOWN_5M_1779846660_YUSDT', // Long (UP) symbol name + 'n': 'ETH_UP_DOWN_5M_1779846660_NUSDT', // Short (DOWN) symbol name + 'p': '2076.40762162', // Price + 'r': 0, // Remaining data points + 't': 1779846960000, // Push timestamp + 'w': 'Y' // Winning result (only present in the last push): Y = UP, N = DOWN +} +``` + + + +\#错误代码 + +error JSON payload: + +```javascript +{ + "code":-1121, + "msg":"Invalid symbol." +} +``` + +Errors consist of two parts: an error code and a message. The code is standardized, but the message may vary. + +## 10xx \- General server or network issues + +### \-1000 UNKNOWN + +* An unknown error occurred while processing the request. + +### \-1001 DISCONNECTED + +* Internal error; unable to process your request. Please try again. + +### \-1002 UNAUTHORIZED + +* You are not authorized to execute this request. + +### \-1003 TOO\_MANY\_REQUESTS + +* Too many requests queued. +* Too many requests; please use the WebSocket for live updates. +* Too many requests; current limit is %s requests per minute. Please use the WebSocket for live updates to avoid polling the API. +* Too many request weights; IP banned until %s. Please use the WebSocket for live updates to avoid bans. + +### \-1004 DUPLICATE\_IP + +* This IP is already on the white list. + +### \-1005 NO\_SUCH\_IP + +* No such IP has been whitelisted. + +### \-1006 UNEXPECTED\_RESP + +* An unexpected response was received from the message bus. Execution status unknown. + +### \-1007 TIMEOUT + +* Timeout waiting for response from backend server. Send status unknown; execution status unknown. + +### \-1014 UNKNOWN\_ORDER\_COMPOSITION + +* The current order parameter combination is not supported. + +### \-1015 TOO\_MANY\_ORDERS + +* Too many new orders. +* Too many new orders; the current limit is %s orders per %s. + +### \-1016 SERVICE\_SHUTTING\_DOWN + +* This service is no longer available. + +### \-1020 UNSUPPORTED\_OPERATION + +* This operation is not supported. + +### \-1022 INVALID\_SIGNATURE + +* The signature for this request is invalid. + +### \-1023 START\_TIME\_GREATER\_THAN\_END\_TIME + +* The start time in the parameters is after the end time. + +## 11xx \- Request issues + +### \-1100 ILLEGAL\_CHARS + +* Illegal characters found in a parameter. +* Illegal characters found in parameter %s; legal range is %s. + +### \-1101 TOO\_MANY\_PARAMETERS + +* Too many parameters sent for this endpoint. +* Too many parameters; expected %s and received %s. +* Duplicate values for a parameter detected. + +### \-1102 MANDATORY\_PARAM\_EMPTY\_OR\_MALFORMED + +* A mandatory parameter was not sent, was empty/null, or malformed. +* Mandatory parameter %s was not sent, was empty/null, or malformed. +* Param %s or %s must be sent, but both were empty/null. + +### \-1103 UNKNOWN\_PARAM + +* An unknown parameter was sent. + +### \-1104 UNREAD\_PARAMETERS + +* Not all sent parameters were read. +* Not all sent parameters were read; read %s parameter(s) but %s parameter(s) were sent. + +### \-1105 PARAM\_EMPTY + +* A parameter was empty. +* Parameter %s was empty. + +### \-1106 PARAM\_NOT\_REQUIRED + +* A parameter was sent when not required. + +### \-1111 BAD\_PRECISION + +* The precision exceeds the maximum defined for this asset. + +### \-1112 NO\_DEPTH + +* No open orders for the trading pair. + +### \-1114 TIF\_NOT\_REQUIRED + +* TimeInForce parameter sent when not required. + +### \-1115 INVALID\_TIF + +* Invalid timeInForce. + +### \-1116 INVALID\_ORDER\_TYPE + +* Invalid orderType. + +### \-1117 INVALID\_SIDE + +* Invalid order side. + +### \-1118 EMPTY\_NEW\_CL\_ORD\_ID + +* New client order ID was empty. + +### \-1119 EMPTY\_ORG\_CL\_ORD\_ID + +* The client's custom order ID is empty. + +### \-1120 BAD\_INTERVAL + +* Invalid time interval. + +### \-1121 BAD\_SYMBOL + +* Invalid trading pair. + +### \-1125 INVALID\_LISTEN\_KEY + +* This listenKey does not exist. + +### \-1127 MORE\_THAN\_XX\_HOURS + +* The query interval is too large. +* More than %s hours between startTime and endTime. + +### \-1128 OPTIONAL\_PARAMS\_BAD\_COMBO + +* Combination of optional parameters invalid. + +### \-1130 INVALID\_PARAMETER + +* The parameter sent contains invalid data. +* Data sent for parameter %s is not valid. + +### \-1136 INVALID\_NEW\_ORDER\_RESP\_TYPE + +* Invalid newOrderRespType. + +## 20xx \- Processing Issues + +### \-2010 NEW\_ORDER\_REJECTED + +* New order rejected. + +### \-2011 CANCEL\_REJECTED + +* Order cancellation rejected. + +### \-2013 NO\_SUCH\_ORDER + +* Order does not exist. + +### \-2014 BAD\_API\_KEY\_FMT + +* API-key format invalid. + +### \-2015 REJECTED\_MBX\_KEY + +* Invalid API key, IP, or permissions for action. + +### \-2016 NO\_TRADING\_WINDOW + +* No trading window could be found for the symbol. Try ticker/24hrs instead. + +### \-2018 BALANCE\_NOT\_SUFFICIENT + +* Balance is insufficient. + +### \-2020 UNABLE\_TO\_FILL + +* Unable to fill. + +### \-2021 ORDER\_WOULD\_IMMEDIATELY\_TRIGGER + +* Order would immediately trigger. + +### \-2022 REDUCE\_ONLY\_REJECT + +* ReduceOnly Order is rejected. + +### \-2024 POSITION\_NOT\_SUFFICIENT + +* Position is not sufficient. + +### \-2025 MAX\_OPEN\_ORDER\_EXCEEDED + +* Reached max open order limit. + +### \-2026 REDUCE\_ONLY\_ORDER\_TYPE\_NOT\_SUPPORTED + +* This OrderType is not supported when reduceOnly. + +## 40xx \- Filters and other Issues + +### \-4000 INVALID\_ORDER\_STATUS + +* Invalid order status. + +### \-4001 PRICE\_LESS\_THAN\_ZERO + +* Price less than 0\. + +### \-4002 PRICE\_GREATER\_THAN\_MAX\_PRICE + +* Price greater than max price. + +### \-4003 QTY\_LESS\_THAN\_ZERO + +* Quantity less than zero. + +### \-4004 QTY\_LESS\_THAN\_MIN\_QTY + +* Quantity less than minimum quantity. + +### \-4005 QTY\_GREATER\_THAN\_MAX\_QTY + +* Quantity greater than maximum quantity. + +### \-4006 STOP\_PRICE\_LESS\_THAN\_ZERO + +* Stop price less than zero. + +### \-4007 STOP\_PRICE\_GREATER\_THAN\_MAX\_PRICE + +* Stop price greater than max price. + +### \-4008 TICK\_SIZE\_LESS\_THAN\_ZERO + +* Tick size less than zero. + +### \-4009 MAX\_PRICE\_LESS\_THAN\_MIN\_PRICE + +* Max price less than min price. + +### \-4010 MAX\_QTY\_LESS\_THAN\_MIN\_QTY + +* Maximum quantity less than minimum quantity. + +### \-4011 STEP\_SIZE\_LESS\_THAN\_ZERO + +* Step size less than zero. + +### \-4012 MAX\_NUM\_ORDERS\_LESS\_THAN\_ZERO + +* Maximum order quantity less than 0\. + +### \-4013 PRICE\_LESS\_THAN\_MIN\_PRICE + +* Price less than minimum price. + +### \-4014 PRICE\_NOT\_INCREASED\_BY\_TICK\_SIZE + +* Price not increased by tick size. + +### \-4015 INVALID\_CL\_ORD\_ID\_LEN + +* Client order ID is not valid. +* Client order ID length should not be more than 36 characters. + +### \-4016 PRICE\_HIGHTER\_THAN\_MULTIPLIER\_UP + +* Price is higher than mark price multiplier cap. + +### \-4017 MULTIPLIER\_UP\_LESS\_THAN\_ZERO + +* Multiplier up less than zero. + +### \-4018 MULTIPLIER\_DOWN\_LESS\_THAN\_ZERO + +* Multiplier down less than zero. + +### \-4019 COMPOSITE\_SCALE\_OVERFLOW + +* Composite scale too large. + +### \-4020 TARGET\_STRATEGY\_INVALID + +* Target strategy invalid for orderType %s, reduceOnly %b' + +### \-4021 INVALID\_DEPTH\_LIMIT + +* Invalid depth limit. +* %s is not a valid depth limit. + +### \-4022 WRONG\_MARKET\_STATUS + +* Market status sent is not valid. + +### \-4023 QTY\_NOT\_INCREASED\_BY\_STEP\_SIZE + +* The increment of the quantity is not a multiple of the step size. + +### \-4024 PRICE\_LOWER\_THAN\_MULTIPLIER\_DOWN + +* Price is lower than mark price multiplier floor. + +### \-4025 MULTIPLIER\_DECIMAL\_LESS\_THAN\_ZERO + +* Multiplier decimal less than zero. + +### \-4026 COMMISSION\_INVALID + +* Commission invalid. +* Incorrect profit value. +* `%s` less than zero. +* `%s` absolute value greater than `%s`. + +### \-4027 INVALID\_ACCOUNT\_TYPE + +* Invalid account type. + +### \-4029 INVALID\_TICK\_SIZE\_PRECISION + +* Tick size precision is invalid. +* Price decimal precision is incorrect. + +### \-4030 INVALID\_STEP\_SIZE\_PRECISION + +* The number of decimal places for the step size is incorrect. + +### \-4031 INVALID\_WORKING\_TYPE + +* Invalid parameter working type: `%s` + +### \-4032 EXCEED\_MAX\_CANCEL\_ORDER\_SIZE + +* Exceeds the maximum order quantity that can be canceled. +* Invalid parameter working type: `%s` + +### \-4044 INVALID\_BALANCE\_TYPE + +* The balance type is incorrect. + +### \-4045 MAX\_STOP\_ORDER\_EXCEEDED + +* Reached the stop-loss order limit. + +### \-4055 AMOUNT\_MUST\_BE\_POSITIVE + +* The quantity must be a positive integer. + +### \-4056 INVALID\_API\_KEY\_TYPE + +* The API key type is invalid. + +### \-4057 INVALID\_RSA\_PUBLIC\_KEY + +* The API key is invalid. + +### \-4058 MAX\_PRICE\_TOO\_LARGE + +* maxPrice and priceDecimal too large, please check. + +### \-4060 INVALID\_POSITION\_SIDE + +* Invalid position side. + +### \-4061 POSITION\_SIDE\_NOT\_MATCH + +* The order's position direction does not match the user's settings. + +### \-4062 REDUCE\_ONLY\_CONFLICT + +* Invalid or improper reduceOnly value. + +### \-4084 UPCOMING\_METHOD + +* Method is not allowed currently. Coming soon. + +### \-4086 INVALID\_PRICE\_SPREAD\_THRESHOLD + +* Invalid price spread threshold. + +### \-4087 REDUCE\_ONLY\_ORDER\_PERMISSION + +* Users can only place reduce-only orders. + +### \-4088 NO\_PLACE\_ORDER\_PERMISSION + +* User cannot place orders currently. + +### \-4114 INVALID\_CLIENT\_TRAN\_ID\_LEN + +* clientTranId is not valid. +* The customer's tranId length should be less than 64 characters. + +### \-4115 DUPLICATED\_CLIENT\_TRAN\_ID + +* clientTranId is duplicated. +* The client's tranId should be unique within 7 days. + +### \-4118 REDUCE\_ONLY\_MARGIN\_CHECK\_FAILED + +* ReduceOnly Order failed. Please check your existing position and open orders + +### \-4131 MARKET\_ORDER\_REJECT + +* The counterparty's best price does not meet the PERCENT\_PRICE filter limit. + +### \-4135 INVALID\_ACTIVATION\_PRICE + +* Invalid activation price. + +### \-4137 QUANTITY\_EXISTS\_WITH\_CLOSE\_POSITION + +* Quantity must be zero when closePosition is true. + +### \-4138 REDUCE\_ONLY\_MUST\_BE\_TRUE + +* Reduce only must be true when closePosition is true. + +### \-4139 ORDER\_TYPE\_CANNOT\_BE\_MKT + +* Order type cannot be a market order if it cannot be canceled. + +### \-4140 INVALID\_OPENING\_POSITION\_STATUS + +* Invalid symbol status for opening position. + +### \-4141 SYMBOL\_ALREADY\_CLOSED + +* Trading pair has been delisted. + +### \-4142 STRATEGY\_INVALID\_TRIGGER\_PRICE + +* Rejected: Take Profit or Stop order would be triggered immediately. + +### \-4164 MIN\_NOTIONAL + +* Order notional must be at least 5.0 (unless you select Reduce Only) +* Order notional must be no smaller than %s (unless you choose Reduce Only) + +### \-4165 INVALID\_TIME\_INTERVAL + +* Invalid time interval +* Maximum time interval is %s days + +### \-4183 PRICE\_HIGHTER\_THAN\_STOP\_MULTIPLIER\_UP + +* Limit price cannot be higher than the cap of %s. +* Take-Profit/Stop-Loss price cannot be higher than the cap of %s. + +### \-4184 PRICE\_LOWER\_THAN\_STOP\_MULTIPLIER\_DOWN + +* Price is below the stop price limit. +* Take-Profit/Stop-Loss price must be above the trigger price × multiplier floor. +* Order price (limit or TP/SL) can't be below %s. diff --git "a/V3(Recommended)/\344\270\255\346\226\207/aster-finance-prediction-api.md" "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-prediction-api.md" new file mode 100644 index 0000000..ae90305 --- /dev/null +++ "b/V3(Recommended)/\344\270\255\346\226\207/aster-finance-prediction-api.md" @@ -0,0 +1,3104 @@ +# 基本信息 +## API 基本信息 +* 本篇列出接口的baseurl: **https://papi.asterdex.com** +* 所有接口的响应都是 JSON 格式。 +* 所有时间、时间戳均为UNIX时间,单位为**毫秒**。 + +## API Agent Address 设置 +* 很多接口需要API Key才可以访问. +* 设置API Key的同时,为了安全,建议设置IP访问白名单. +* **永远不要把你的API Agent Address/Private Key告诉给任何人** + + + +### 注意事项 +* TESTUSDT 或任何其他以 TEST 开头的交易对仅用于 Aster 的内部测试。请不要在这些以 TEST 开头的交易品种上进行交易。Aster 对因交易这些交易对而造成的资金损失不承担任何责任。但是,如果您遇到问题,您可以随时联系支持人员,我们将尽力帮助您收回资金。 + + +### HTTP 返回代码 +* HTTP `4XX` 错误码用于指示错误的请求内容、行为、格式。问题在于请求者。 +* HTTP `403` 错误码表示违反WAF限制(Web应用程序防火墙)。 +* HTTP `429` 错误码表示警告访问频次超限,即将被封IP。 +* HTTP `418` 表示收到429后继续访问,IP已经被封禁。 +* HTTP `5XX` 错误码用于指示Aster服务侧的问题。 + +### 接口错误代码 +* 使用接口 `/api/v3`, 每个接口都有可能抛出异常; +> API的错误代码返回形式如下: +```javascript +{ + "code": -1121, + "msg": "Invalid symbol." +} +``` + +### 接口的基本信息 + +* `GET` 方法的接口, 参数必须在 `query string`中发送。 +* `POST`, `PUT`, 和 `DELETE` 方法的接口,参数可以在内容形式为`application/x-www-form-urlencoded`的 `query string` 中发送,也可以在 `request body` 中发送。 +* 对参数的顺序不做要求。 + +### V3 Nonce 机制 + +* **Nonce** 用于校验请求的**有效性、唯一性和防重放**。客户端应使用**当前时间戳(微秒级)****作为 nonce**,且与服务端时间误差不超过 **10 秒**。 + +* 请求处理流程: + + 1. 若 nonce **已使用过** → 判定为**重复请求并拒绝** + 2. 否则判断是否**过旧** + +* 为提升性能,每个用户仅维护**最近 100 个 nonce**: + + * 若已满且新 nonce **小于当前最小值** → 判定为**过期并拒绝** + * 否则**移除最旧的 nonce**,加入新的 + +* 总体效果:**防重复、防过期,仅保留近期有效请求** + +--- +## 访问限制 +### 访问限制基本信息 + +* 在 `/api/v3/prediction/exchangeInfo` `rateLimits` 数组中包含与交易的有关REQUEST_WEIGHT和ORDERS速率限制相关的对象。这些在 `限制种类 (rateLimitType)` 下的 `枚举定义` 部分中进一步定义。 +* 违反任何一个速率限制时,将返回429。 + +### IP 访问限制 +* 每个请求的回报中包含一个`X-MBX-USED-WEIGHT-(intervalNum)(intervalLetter)`的头,其中包含当前IP所有请求的已使用权重。 +* 每一个接口均有一个相应的权重(weight),有的接口根据参数不同可能拥有不同的权重。越消耗资源的接口权重就会越大。 +* 收到429时,您有责任停止发送请求,不得滥用API。 +* **收到429后仍然继续违反访问限制,会被封禁IP,并收到418错误码** +* 频繁违反限制,封禁时间会逐渐延长,**从最短2分钟到最长3天**。 +* `Retry-After`的头会与带有418或429的响应发送,并且会给出**以秒为单位**的等待时长(如果是429)以防止禁令,或者如果是418,直到禁令结束。 +* **访问限制是基于IP的,而不是API Key** + + + + +### 下单频率限制 +* 每个成功的下单回报将包含一个`X-MBX-ORDER-COUNT-(intervalNum)(intervalLetter)`的头,其中包含当前账户已用的下单限制数量。 +* 当下单数超过限制时,会收到带有429但不含`Retry-After`头的响应。请检查 `GET api/v3/prediction/exchangeInfo` 的下单频率限制 (rateLimitType = ORDERS) 并等待封禁时间结束。 +* 被拒绝或不成功的下单并不保证回报中包含以上头内容。 +* **下单频率限制是基于每个账户计数的。** + +### WEB SOCKET 连接限制 + +* Websocket服务器每秒最多接受5个消息。消息包括: + * PING帧 + * PONG帧 + * JSON格式的消息, 比如订阅, 断开订阅. +* 如果用户发送的消息超过限制,连接会被断开连接。反复被断开连接的IP有可能被服务器屏蔽。 +* 单个连接最多可以订阅 **1024** 个Streams。 + + +## 接口鉴权类型 +* 每个接口都有自己的鉴权类型,鉴权类型决定了访问时应当进行何种鉴权 +* 如果需要使用API_WALLET鉴权,应当在请求体中添加signer +* 如果需要使用主地址鉴权,应当在请求体中添加user + +鉴权类型 | 描述 +------------ | ------------ +NONE | 不需要鉴权的接口 +SPOT_TRADE | 需要有效的signer和签名 +USER_DATA | 需要有效的signer和签名 +USER_STREAM | 需要有效的signer和签名 +MARKET_DATA | 不需要鉴权的接口 + + +### POST /api/v3/order 的示例 + +#### 示例 : 以下参数为api注册信息,user,signer,privateKey仅供示范(privateKey为signer的私钥) + + +Key | Value | Desc +------------ | ------------ | ------------ +user | 0x63DD5aCC6b1aa0f563956C0e534DD30B6dcF7C4e | 登陆钱包地址 +signer | 0x21cF8Ae13Bb72632562c6Fff438652Ba1a151bb0 | [点击这里获取](https://www.asterdex.com/zh-CN/api-wallet) +privateKey | 0x4fd0a42218f3eae43a6ce26d22544e986139a01e5b34a62db53757ffca81bae1 | [点击这里获取](https://www.asterdex.com/zh-CN/api-wallet) + +#### 示例 : nonce参数为当前系统微秒值,超过系统时间,或者落后系统时间超过10s为非法请求 +```python +#python +nonce = math.trunc(time.time()*1000000) +print(nonce) +#1748310859508867 +``` +```java +//java +Instant now = Instant.now(); +long microsecond = now.getEpochSecond() * 1000000 + now.getNano() / 1000; +``` + +#### 示例 : 下单 (方法以python为例) + +```python +import time +import urllib +import threading + +import requests +from eth_account.messages import encode_structured_data +from eth_account import Account + +typed_data = { + "types": { + "EIP712Domain": [ + {"name": "name", "type": "string"}, + {"name": "version", "type": "string"}, + {"name": "chainId", "type": "uint256"}, + {"name": "verifyingContract", "type": "address"} + ], + "Message": [ + { "name": "msg", "type": "string" } + ] + }, + "primaryType": "Message", + "domain": { + "name": "AsterSignTransaction", + "version": "1", + "chainId": 1666, + "verifyingContract": "0x0000000000000000000000000000000000000000" + }, + "message": { + "msg": "$msg" + } +} + +headers = { + 'Content-Type': 'application/x-www-form-urlencoded', + 'User-Agent': 'PythonApp/1.0' +} +host = 'https://papi.asterdex.com' + +# config your user and agent info here +user = '*' +signer = '*' +private_key = "*" + +place_order = {"url":"/api/v3/order","method":"POST","params":{"symbol": "ASTERUSDT", "type": "LIMIT", "side": "BUY", + "timeInForce": "GTC", "quantity": "100", "price": "0.4"}} +_last_ms = 0 +_i = 0 +_nonce_lock = threading.Lock() + +def get_nonce(): + global _last_ms, _i + with _nonce_lock: + now_ms = int(time.time()) + + if now_ms == _last_ms: + _i += 1 + else: + _last_ms = now_ms + _i = 0 + + return now_ms * 1_000_000 + _i + +def send_by_url(api) : + my_dict = api['params'] + url = host + api['url'] + + my_dict['nonce'] = str(get_nonce()) + my_dict['signer'] = signer + + param = urllib.parse.urlencode(my_dict) + print(param) + typed_data['message']['msg'] = param + message = encode_structured_data(typed_data) + signed = Account.sign_message(message, private_key=private_key) + + url = url + '?' + param + '&signature=' + signed.signature.hex() + print(url) + res = requests.post(url, headers=headers) + + print(res.text) + +def send_by_body(api) : + my_dict = api['params'] + url = host +api['url'] + my_dict['nonce'] = str(get_nonce()) + my_dict['signer'] = signer + + param = urllib.parse.urlencode(my_dict) + typed_data['message']['msg'] = param + message = encode_structured_data(typed_data) + + signed = Account.sign_message(message, private_key=private_key) + print(signed.signature.hex()) + + my_dict['signature'] = signed.signature.hex() + + print(my_dict) + res = requests.post(url, data=my_dict, headers=headers) + + print(res.text) + +if __name__ == '__main__': + send_by_url(place_order) + # send_by_body(place_order) + +``` + +## 公开 API 参数 +### 术语 + +这里的术语适用于全部文档,建议特别是新手熟读,也便于理解。 + +* `base asset` 指一个交易对的交易对象,即写在靠前部分的资产名, 比如`BTCUSDT`, `BTC`是`base asset`。 +* `quote asset` 指一个交易对的定价资产,即写在靠后部分的资产名, 比如`BTCUSDT`, `USDT`是`quote asset`。 + +### 枚举定义 +**交易对状态 (状态 status):** + +* TRADING 交易中 + + +**交易对类型:** + +* SPOT 现货 + +**订单状态 (状态 status):** + +状态 | 描述 +-----------| -------------- +`NEW` | 订单被交易引擎接受 +`PARTIALLY_FILLED`| 部分订单被成交 +`FILLED` | 订单完全成交 +`CANCELED` | 用户撤销了订单 +`REJECTED` | 订单没有被交易引擎接受,也没被处理 +`EXPIRED` | 订单被交易引擎取消, 比如
LIMIT FOK 订单没有成交
市价单没有完全成交
交易所维护期间被取消的订单 + + +**订单类型 (orderTypes, type):** + +* LIMIT 限价单 +* MARKET 市价单 + +**订单返回类型 (newOrderRespType):** + +* ACK +* RESULT +* FULL + +**订单方向 (方向 side):** + +* BUY 买入 +* SELL 卖出 + +**有效方式 (timeInForce):** + +这里定义了订单多久能够失效 + +Status | Description +-----------| -------------- +`GTC` | 成交为止
订单会一直有效,直到被成交或者取消。 +`IOC` | 无法立即成交的部分就撤销
订单在失效前会尽量多的成交。 +`FOK` | 无法全部立即成交就撤销
如果无法全部成交,订单会失效。 +`GTX` | 直到挂单成交
限价只挂单。 + +**K线间隔:** + +m -> 分钟 + +* 1s +* 1m + + +新增了1s参数 + +**限制种类 (rateLimitType)** + +> REQUEST_WEIGHT +```json + { + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 1200 + } +``` + +> ORDERS +```json + { + "rateLimitType": "ORDERS", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 100 + } +``` + + +* REQUEST_WEIGHT 单位时间请求权重之和上限 + +* ORDERS 单位时间下单次数限制 + + +**限制间隔 (interval)** + +* MINUTE 分 + +--- +## 过滤器 +过滤器,即Filter,定义了一系列交易规则。 +共有两类,分别是针对交易对的过滤器`symbol filters`,和针对整个交易所的过滤器`exchange filters`(暂不支持) + +### 交易对过滤器   + +#### PRICE_FILTER 价格过滤器 + +> **/exchangeInfo 响应中的格式:** +```javascript + { + "minPrice": "556.72", + "maxPrice": "4529764", + "filterType": "PRICE_FILTER", + "tickSize": "0.01"   + } +``` + +`价格过滤器` 用于检测订单中 `price` 参数的合法性。包含以下三个部分: + +* `minPrice` 定义了 `price`/`stopPrice` 允许的最小值。 +* `maxPrice` 定义了 `price`/`stopPrice` 允许的最大值。 +* `tickSize` 定义了 `price`/`stopPrice` 的步进间隔,即price必须等于minPrice+(tickSize的整数倍) + +以上每一项均可为0,为0时代表这一项不再做限制。 + +逻辑伪代码如下: + +* `price` >= `minPrice` +* `price` <= `maxPrice` +* (`price`-`minPrice`) % `tickSize` == 0 + + +#### PERCENT_PRICE 价格振幅过滤器 + +> **/exchangeInfo 响应中的格式:** +```javascript + { + "multiplierDown": "0.9500", + "multiplierUp": "1.0500", + "multiplierDecimal": "4", + "filterType": "PERCENT_PRICE" +  } +``` + +`PERCENT_PRICE`过滤器基于指数价格来定义价格的有效范围。 + +为了通过"价格百分比","价格"必须符合以下条件: + +* `price` <=`indexPrice` *`multiplierUp` +* `price`> =`indexPrice` *`multiplierDown` + + +#### LOT_SIZE 订单尺寸 + +> **/exchangeInfo 响应中的格式:** +```javascript + { + "stepSize": "0.00100000", +   "filterType": "LOT_SIZE", + "maxQty": "100000.00000000", +   "minQty": "0.00100000" + } +``` + +Lots是拍卖术语,`LOT_SIZE` 过滤器对订单中的 `quantity` 也就是数量参数进行合法性检查。包含三个部分: + +* `minQty` 表示 `quantity` 允许的最小值。 +* `maxQty` 表示 `quantity` 允许的最大值。 +* `stepSize` 表示 `quantity` 允许的步进值。 + +逻辑伪代码如下: + +* `quantity` >= `minQty` +* `quantity` <= `maxQty` +* (`quantity`-`minQty`) % `stepSize` == 0 + + + + +#### MARKET_LOT_SIZE 市价订单尺寸 + +> ***/exchangeInfo 响应中的格式:** +```javascript + { + "stepSize": "0.00100000", +   "filterType": "MARKET_LOT_SIZE" + "maxQty": "100000.00000000", + "minQty": "0.00100000" + } +``` + + +`MARKET_LOT_SIZE`过滤器为交易对上的`MARKET`订单定义了`数量`(即拍卖中的"手数")规则。 共有3部分: + +* `minQty`定义了允许的最小`quantity`。 +* `maxQty`定义了允许的最大数量。 +* `stepSize`定义了可以增加/减少数量的间隔。 + +为了通过`market lot size`,`quantity`必须满足以下条件: + +* `quantity` >= `minQty` +* `quantity` <= `maxQty` +* (`quantity`-`minQty`) % `stepSize` == 0 + + +#### predictionEvents 预测事件 + +> ***/exchangeInfo 响应中的格式:** +```javascript +"predictionEvents": [ + { + "eventName": "ETH_UP_DOWN_7D", //预测事件 + "oracleSymbol": "ETHUSDT", //预测的SYMBOL + "predictionType": "UP_DOWN", //预测类型 + "sides": [ + "UP", + "DOWN" + ], //预测方向 + "period": "10080M", //预测周期 单位分钟 + "startTime": 1778476080000, //预测事件的开始时间 + "endTime": 1780376880000, //预测事件的结束时间 + "status": "LIVE", //预测事件的状态 + "currentRoundId": 3, //预测事件当前轮次 + "orderTypes": [ + "LIMIT", + "MARKET" + ], //预测事件的订单类型 + "timeInForce": [ + "GTC", + "IOC", + "FOK", + "GTX" + ], //预测事件的TIF + "settleIntervalSeconds": 5, //twap 价格数据周期 + "settlementDataPointCount": 5, //twap 价格数据数量 + "reduceOnly": false, //是否只减仓 + "liveRound":{ + "marketName": "ETHUSDT_UP_DOWN_5M_1778483280", //预测市场的名字 + "symbolIds": [ + "ETHUSDT_UP_DOWN_5M_1778483280_YUSDT", + "ETHUSDT_UP_DOWN_5M_1778483280_NUSDT" + ], // 预测市场的2个SYMBOL,Y代表上涨,N代表下跌 + "assetIds": [ + "ETHUSDT_UP_DOWN_5M_1778483280_Y", + "ETHUSDT_UP_DOWN_5M_1778483280_N" + ], // 预测市场的2个Asset,Y代表上涨,N代表下跌 + "roundId": 2, //预测市场的轮次ID + "tradingStartTime": 1778482970000, //预测市场的开始交易时间 + "tradingEndTime": 1778483520000, //预测市场的结束交易时间 + "windowStartTime": 1778483280000, //预测市场的窗口开始时间 + "windowEndTime": 1778483580000, //预测市场的窗口结束时间 + "roundStatus": "SETTLED", //预测市场的状态 + "openPrice": "0.99920000", //预测市场的开始价格 + "endPrice": "0.99910000", //预测市场的结束价格 + "winAsset": "ETHUSDT_UP_DOWN_5M_1778483280_N", //预测市场的获胜资产 如果上涨则是Y,如果下跌是N + "settleTime": 1778483582057, //预测市场的结算时间 + "settleHash": "0x3bc0aff52472dafd4b70d3423386a2dabf675fe7cd604e92391e2a4702cf0980" //预测市场的结算链上Hash + }, + "rounds": [ + { + "marketName": "ETHUSDT_UP_DOWN_5M_1778483280", //预测市场的名字 + "symbolIds": [ + "ETHUSDT_UP_DOWN_5M_1778483280_YUSDT", + "ETHUSDT_UP_DOWN_5M_1778483280_NUSDT" + ], // 预测市场的2个SYMBOL,Y代表上涨,N代表下跌 + "assetIds": [ + "ETHUSDT_UP_DOWN_5M_1778483280_Y", + "ETHUSDT_UP_DOWN_5M_1778483280_N" + ], // 预测市场的2个Asset,Y代表上涨,N代表下跌 + "roundId": 2, //预测市场的轮次ID + "tradingStartTime": 1778482970000, //预测市场的开始交易时间 + "tradingEndTime": 1778483520000, //预测市场的结束交易时间 + "windowStartTime": 1778483280000, //预测市场的窗口开始时间 + "windowEndTime": 1778483580000, //预测市场的窗口结束时间 + "roundStatus": "SETTLED", //预测市场的状态 + "openPrice": "0.99920000", //预测市场的开始价格 + "endPrice": "0.99910000", //预测市场的结束价格 + "winAsset": "ETHUSDT_UP_DOWN_5M_1778483280_N", //预测市场的获胜资产 如果上涨则是Y,如果下跌是N + "settleTime": 1778483582057, //预测市场的结算时间 + "settleHash": "0x3bc0aff52472dafd4b70d3423386a2dabf675fe7cd604e92391e2a4702cf0980" //预测市场的结算链上Hash + } + ] + } +] +``` + +`status` 为事件的状态 + +Status | Description +-----------| -------------- +`LIVE` | 正在运行。 +`CLOSED` | INVALID。 +`INVALID` | 无效。 + +`roundStatus` 为市场的状态 + +RoundStatus | Description +-----------| -------------- +`PREMARKET` | 预先准备好的市场(可以提前交易) +`TRADING` | 交易中的市场 +`SETTLED` | 已结算的市场 + +* 结算完成一段时间(24H)后,会自动下架,下架后的市场不再展示 +* `status` 为`CLOSED`或者`INVALID`的事件对应的市场,只能下reduceOnly的Market Sell订单 + +# 行情接口 + +## Noop + +> **Response:** + +```javascript +{ + "code": 200, + "msg": "success" +} +``` + +``POST /api/v3/noop`` + +通过此请求,可以高效取消已发送但仍在队列中且尚未完成链上操作的交易(Nonce需与该请求一致,不保证成功) + +**Weight:** +1 + +## 测试服务器连通性 +> **响应** +```javascript +{} +``` +`` +GET /api/v3/ping +`` + +测试能否联通 Rest API。 + +**权重:** +1 + +**参数:** +NONE + + +## 获取服务器时间 +> **响应** +```javascript +{ + "serverTime": 1499827319559 +} +``` +`` +GET /api/v3/time +`` + +测试能否联通 Rest API 并获取服务器时间。 + +**权重:** +1 + +**参数:** +NONE + + +## 交易规范信息 + +> **响应** + +```javascript     +{ + "timezone": "UTC", + "serverTime": 1756197279679, + "rateLimits": [{ + "rateLimitType": "REQUEST_WEIGHT", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 6000 + }, + { + "rateLimitType": "ORDERS", + "interval": "MINUTE", + "intervalNum": 1, + "limit": 6000 + }, + { + "rateLimitType": "ORDERS", + "interval": "SECOND", + "intervalNum": 10, + "limit": 300 + } + ], + "exchangeFilters": [], + "assets": [{ + "asset": "USD" + }, { + "asset": "USDT" + }, + { + "asset": "BNB" + } + ], + "symbols": [{ + "status": "TRADING", + "baseAsset": "BNB", + "quoteAsset": "USDT", + "pricePrecision": 8, + "quantityPrecision": 8, + "baseAssetPrecision": 8, + "quotePrecision": 8, + "filters": [{ + "minPrice": "0.01000000", + "maxPrice": "100000", + "filterType": "PRICE_FILTER", + "tickSize": "0.01000000" + }, + { + "stepSize": "0.00100000", + "filterType": "LOT_SIZE", + "maxQty": "1000", + "minQty": "1" + }, + { + "stepSize": "0.00100000", + "filterType": "MARKET_LOT_SIZE", + "maxQty": "900000", + "minQty": "0.00100000" + }, + { + "limit": 200, + "filterType": "MAX_NUM_ORDERS" + }, + { + "minNotional": "5", + "filterType": "MIN_NOTIONAL" + }, + { + "maxNotional": "100", + "filterType": "MAX_NOTIONAL" + }, + { + "maxNotional": "100", + "minNotional": "5", + "avgPriceMins": 5, + "applyMinToMarket": true, + "filterType": "NOTIONAL", + "applyMaxToMarket": true + }, + { + "multiplierDown": "0", + "multiplierUp": "5", + "multiplierDecimal": "0", + "filterType": "PERCENT_PRICE" + }, + { + "bidMultiplierUp": "5", + "askMultiplierUp": "5", + "bidMultiplierDown": "0", + "avgPriceMins": 5, + "multiplierDecimal": "0", + "filterType": "PERCENT_PRICE_BY_SIDE", + "askMultiplierDown": "0" + } + ], + "orderTypes": [ + "LIMIT", + "MARKET", + "STOP", + "STOP_MARKET", + "TAKE_PROFIT", + "TAKE_PROFIT_MARKET" + ], + "timeInForce": [ + "GTC", + "IOC", + "FOK", + "GTX", + "HIDDEN" + ], + "symbol": "BTC_UP_DOWN_5M_1778483280_YUSDT", + "ocoAllowed": false + }] +} +``` + +`` +GET /api/v3/prediction/exchangeInfo +`` + +获取交易规则和交易对信息。 + +**权重:** +1 + +**参数:** +无 + + +## 深度信息 + +> **响应** + +```javascript +{ + "lastUpdateId": 1027024, + "E":1589436922972, // 消息时间 + "T":1589436922959, // 撮合引擎时间 + "bids": [ + [ + "4.00000000", // 价位 + "431.00000000" // 挂单量 + ] + ], + "asks": [ + [ + "4.00000200", + "12.00000000" + ] + ] +} +``` +`` +GET /api/v3/depth +`` + +**权重:** + +基于限制调整: + +限制 | 权重 +------------ | ------------ +5, 10, 20, 50 | 2 +100 | 5 +500 | 10 +1000 | 20 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +limit | INT | NO | 默认 100. 可选值:[5, 10, 20, 50, 100, 500, 1000] + + +## 近期成交列表 + +> **响应** + +```javascript +[ + { + "id": 657, + "price": "1.01000000", + "qty": "5.00000000", + "baseQty": "4.95049505", + "time": 1755156533943, + "isBuyerMaker": false + } +] +``` +`` +GET /api/v3/trades +`` + +获取近期成交 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +limit | INT | NO | 默认 500;最大1000 + + +## 查询历史成交 (MARKET_DATA) + +> **响应** + +```javascript +[ + { + "id": 1140, + "price": "1.10000000", + "qty": "7.27200000", + "baseQty": "6.61090909", + "time": 1756094288700, + "isBuyerMaker": false + } +] +``` +`` +GET /api/v3/historicalTrades +`` + +获取历史成交。 + +**权重:** +20 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +limit | INT | NO | 默认 500; 最大值 1000. +fromId | LONG | NO | 从哪一条成交id开始返回. 缺省返回最近的成交记录。 + + +## 近期成交(归集) + +> **响应** + +```javascript +[ + { + "a": 26129, // 归集成交ID + "p": "0.01633102", // 成交价 + "q": "4.70443515", // 成交量 + "f": 27781, // 被归集的首个成交ID + "l": 27781, // 被归集的末个成交ID + "T": 1498793709153, // 成交时间 + "m": true, // 是否为主动卖出单 + } +] +``` +`` +GET /api/v3/aggTrades +`` + +归集交易与逐笔交易的区别在于,同一价格、同一方向、同一时间的trade会被聚合为一条 + +**权重:** +20 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +fromId | LONG | NO | 从包含fromId的成交id开始返回结果 +startTime | LONG | NO | 从该时刻之后的成交记录开始返回结果 +endTime | LONG | NO | 返回该时刻为止的成交记录 +limit | INT | NO | 默认 500; 最大 1000. +* 如果发送startTime和endTime,间隔必须小于一小时。 +* 如果没有发送任何筛选参数(fromId, startTime,endTime),默认返回最近的成交记录 + + +## K线数据 + +> **响应** +```javascript +[ + [ + 1499040000000, // 开盘时间 + "0.01634790", // 开盘价 + "0.80000000", // 最高价 + "0.01575800", // 最低价 + "0.01577100", // 收盘价(当前K线未结束的即为最新价) + "148976.11427815", // 成交量 + 1499644799999, // 收盘时间 + "2434.19055334", // 成交额 + 308, // 成交笔数 + "1756.87402397", // 主动买入成交量 + "28.46694368", // 主动买入成交额 + ] +] +``` +`` +GET /api/v3/klines +`` + +每根K线代表一个交易对。 +每根K线的开盘时间可视为唯一ID + + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +interval | ENUM | YES | 详见枚举定义:K线间隔 +startTime | LONG | NO | +endTime | LONG | NO | +limit | INT | NO | 默认 500; 最大 1500. +* 如果未发送 startTime 和 endTime ,默认返回最近的交易。 + + + +## 24hr 价格变动情况 + +> **响应** + +```javascript +{ + "symbol": "BTC_UP_DOWN_5M_1778483280_YUSDT", + "priceChange": "-94.99999800", //24小时价格变动 + "priceChangePercent": "-95.960", //24小时价格变动百分比 + "weightedAvgPrice": "0.29628482", //加权平均价 + "prevClosePrice": "3.89000000", //上一次结束价格 + "lastPrice": "4.00000200", //最近一次成交价 + "lastQty": "200.00000000", //最近一次成交额 + "bidPrice": "866.66000000", //最高的买入价格 + "bidQty": "72.05100000", //最高的买入价格的数量 + "askPrice": "866.73000000", //最低的卖出价 + "askQty": "1.21700000", //最低的卖出价格的数量 + "openPrice": "99.00000000", //24小时内第一次成交的价格 + "highPrice": "100.00000000", //24小时最高价 + "lowPrice": "0.10000000", //24小时最低价 + "volume": "8913.30000000", //24小时成交量 + "quoteVolume": "15.30000000", //24小时成交额 + "openTime": 1499783499040, //24小时内,第一笔交易的发生时间 + "closeTime": 1499869899040, //24小时内,最后一笔交易的发生时间 + "firstId": 28385, // 首笔成交id + "lastId": 28460, // 末笔成交id + "count": 76, // 成交笔数 + "baseAsset": "BTC", //基础代币 + "quoteAsset": "USDT" //报价代币 +} +``` + +`` +GET /api/v3/ticker/24hr +`` + +24 小时滚动窗口价格变动数据。 请注意,不携带symbol参数会返回全部交易对数据,此时返回的数据为示例相应的数组,不仅数据庞大,而且权重极高 + +**权重:** +1 单一交易对; +**40** 交易对参数缺失; + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | NO | +* 请注意,不携带symbol参数会返回全部交易对数据 + +## 最新价格 + +> **响应** + +```javascript +{ + "symbol": "ADAUSDT", + "price": "1.30000000", + "time": 1649666690902 +} +``` + +> OR + +```javascript +[ + { + "symbol": "ADAUSDT", + "price": "1.30000000", + "time": 1649666690902 + } +] +``` + +`` +GET /api/v3/ticker/price +`` + +获取交易对最新价格 + +**权重:** +1 单一交易对; +**2** 交易对参数缺失; + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | NO | +* 不发送交易对参数,则会返回所有交易对信息 + + +## 当前最优挂单 +> **响应** +```javascript +{ + "symbol": "LTCBTC", + "bidPrice": "4.00000000", + "bidQty": "431.00000000", + "askPrice": "4.00000200", + "askQty": "9.00000000" + "time": 1589437530011 // 交易时间 +} +``` +> OR +```javascript +[ + { + "symbol": "LTCBTC", + "bidPrice": "4.00000000", + "bidQty": "431.00000000", + "askPrice": "4.00000200", + "askQty": "9.00000000", + "time": 1589437530011 // 交易时间 + } +] +``` + +`` +GET /api/v3/ticker/bookTicker +`` + +返回当前最优的挂单(最高买单,最低卖单) + +**权重:** +1 单一交易对; +**2** 交易对参数缺失; + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | NO | +* 不发送交易对参数,则会返回所有交易对信息 + +## 获取Symbol手续费 + +> **响应** + +```javascript +{ + "symbol": "APXUSDT", + "makerCommissionRate": "0.000200",     + "takerCommissionRate": "0.000700", + "settlementFeeRate": "0.000700" +} +``` +`` +GET /api/v3/commissionRate +`` + +获取Symbol手续费。 + +**权重:** +20 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | + + + + + +# 现货账户和交易接口 + + +## 下单 (TRADE) + +> **Response ACK:** + +```javascript +{ + "symbol": "BTC_UP_DOWN_5M_1778483280_YUSDT", // 交易对 + "orderId": 28, // 系统的订单ID + "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP", // 客户自己设置的ID + "updateTime": 1507725176595, // 交易的时间戳 + "price": "0.00000000", // 订单价格 + "avgPrice": "0.0000000000000000", //平均价格 + "origQty": "10.00000000", // 用户设置的原始订单数量 + "cumQty": "0", //累计数量 + "executedQty": "10.00000000", // 交易的订单数量 + "cumQuote": "10.00000000", // 累计交易的金额 + "status": "FILLED", // 订单状态 + "timeInForce": "GTC", // 订单的时效方式 + "stopPrice": "0", //触发价格 + "origType": "LIMIT", //触发前订单类型 + "type": "LIMIT", // 订单类型, 比如市价单,现价单等 + "side": "SELL", // 订单方向,买还是卖 +} +``` + +`` +POST /api/v3/order `` + +发送下单。 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +side | ENUM | YES | 详见枚举定义:订单方向 +type | ENUM | YES | 详见枚举定义:订单类型 +timeInForce | ENUM | NO | 详见枚举定义:有效方式 +quantity | DECIMAL | NO | +quoteOrderQty|DECIMAL|NO| +price | DECIMAL | NO | +newClientOrderId | STRING | NO | 客户自定义的唯一订单ID。 如果未发送,则自动生成 +stopPrice | DECIMAL | NO | 仅 `STOP`, `STOP_MARKET` , `TAKE_PROFIT`,`TAKE_PROFIT_MARKET` 需要此参数。 + +基于订单 `type`不同,强制要求某些参数: + +类型 | 强制要求的参数 +------------ | ------------ +`LIMIT` | `timeInForce`, `quantity`, `price` +`MARKET` | `quantity` 或 `quoteOrderQty` +`STOP`和`TAKE_PROFIT` | `quantity`, `price`, `stopPrice` +`STOP_MARKET`和`TAKE_PROFIT_MARKET` | `quantity`, `stopPrice` + +其他信息: + +* 下`MARKET` `SELL`市价单,用户通过`QUANTITY`控制想用市价单卖出的基础资产数量。 + * 比如在`BTC_UP_DOWN_5M_1778483280_YUSDT`交易对上下一个`MARKET` `SELL`市价单, 通过`QUANTITY`让用户指明想卖出多少BTC。 +* 下`MARKET` `BUY`的市价单,用户使用 `quoteOrderQty` 控制想用市价单买入的报价资产数量,`QUANTITY`将由系统根据市场流动性计算出来。 +  * 比如在`BTC_UP_DOWN_5M_1778483280_YUSDT`交易对上下一个`MARKET` `BUY`市价单, 通过`quoteOrderQty`让用户选择想使用多少USDT买入BTC。 +* 使用 `quoteOrderQty` 的市价单`MARKET`不会突破`LOT_SIZE`的限制规则; 报单会按给定的`quoteOrderQty`尽可能接近地被执行。 +* 除非之前的订单已经成交, 不然设置了相同的`newClientOrderId`订单会被拒绝。 + + + +## 撤销订单 (TRADE) + +> **响应** + +```javascript +{ + "symbol": "BTC_UP_DOWN_5M_1778483280_YUSDT", // 交易对 + "orderId": 28, // 系统的订单ID + "clientOrderId": "6gCrw2kRUAF9CvJDGP16IP", // 客户自己设置的ID + "updateTime": 1507725176595, // 交易的时间戳 + "price": "0.00000000", // 订单价格 + "avgPrice": "0.0000000000000000", //平均价格 + "origQty": "10.00000000", // 用户设置的原始订单数量 + "cumQty": "0", //累计数量 + "executedQty": "10.00000000", // 交易的订单数量 + "cumQuote": "10.00000000", // 累计交易的金额 + "status": "CANCELED", // 订单状态 + "timeInForce": "GTC", // 订单的时效方式 + "stopPrice": "0", //触发价格 + "origType": "LIMIT", //触发前订单类型 + "type": "LIMIT", // 订单类型, 比如市价单,现价单等 + "side": "SELL", // 订单方向,买还是卖 +} +``` + +`` +DELETE /api/v3/order `` + +取消有效订单。 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +orderId | LONG | NO | +origClientOrderId | STRING | NO | + +`orderId` 或 `origClientOrderId` 必须至少发送一个 + +## 查询订单 (USER_DATA) + +> **响应** +```javascript +{ + "orderId": 38,   // 系统订单号 + "symbol": "ADA25SLP25",  // 交易对 + "status": "FILLED",  // 订单状态 + "clientOrderId": "afMd4GBQyHkHpGWdiy34Li",  // 用户自定义的订单号 + "price": "20",  // 委托价格 + "avgPrice": "12.0000000000000000",  // 平均成交价 + "origQty": "10",  // 原始委托数量 + "executedQty": "10",  // 成交量 + "cumQuote": "120",  // 成交金额 + "timeInForce": "GTC",  // 有效方法 + "type": "LIMIT",  // 订单类型 + "side": "BUY",  // 买卖方向 + "stopPrice": "0",  // 触发价 + "origType": "LIMIT",  // 触发前订单类型 + "time": 1649913186270,  // 订单时间 + "updateTime": 1649913186297  // 更新时间 +} +``` + +`` +GET /api/v3/order`` + +查询订单状态。 + +* 请注意,如果订单满足如下条件,不会被查询到: + * 订单的最终状态为 `CANCELED` 或者 `EXPIRED`, **并且** + * 订单没有任何的成交记录, **并且** + * 订单生成时间 + 7天 < 当前时间 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +orderId | LONG | NO | +origClientOrderId | STRING | NO | + +注意: + +* 至少需要发送 `orderId` 与 `origClientOrderId`中的一个 + + +## 查询当前挂单 (USER_DATA) + +> **响应** +```javascript +{ + "orderId": 38,   // 系统订单号 + "symbol": "ADA25SLP25",  // 交易对 + "status": "NEW",  // 订单状态 + "clientOrderId": "afMd4GBQyHkHpGWdiy34Li",  // 用户自定义的订单号 + "price": "20",  // 委托价格 + "avgPrice": "12.0000000000000000",  // 平均成交价 + "origQty": "10",  // 原始委托数量 + "executedQty": "10",  // 成交量 + "cumQuote": "120",  // 成交金额 + "timeInForce": "GTC",  // 有效方法 + "type": "LIMIT",  // 订单类型 + "side": "BUY",  // 买卖方向 + "stopPrice": "0",  // 触发价 + "origType": "LIMIT",  // 触发前订单类型 + "time": 1649913186270,  // 订单时间 + "updateTime": 1649913186297  // 更新时间 +} +``` + +`` +GET /api/v3/openOrder`` + +查询订单状态。 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +orderId | LONG | NO | +origClientOrderId | STRING | NO | + +注意: + +* 至少需要发送 `orderId` 与 `origClientOrderId`中的一个 + + +## 当前所有挂单 (USER_DATA) + +> **响应** + +```javascript +[ + { + "orderId": 349661, // 系统订单号 + "symbol": "BTC_UP_DOWN_5M_1778483280_YUSDT", // 交易对 + "status": "NEW", // 订单状态 + "clientOrderId": "LzypgiMwkf3TQ8wwvLo8RA", // 用户自定义的订单号 + "price": "1.10000000", // 委托价格 + "avgPrice": "0.0000000000000000", // 平均成交价 + "origQty": "5",  // 原始委托数量 + "executedQty": "0", // 成交量 + "cumQuote": "0", // 成交金额 + "timeInForce": "GTC", // 有效方法 + "type": "LIMIT", // 订单类型 + "side": "BUY", // 买卖方向 + "stopPrice": "0", // 触发价 + "origType": "LIMIT", // 触发前订单类型 + "time": 1756252940207, // 订单时间 + "updateTime": 1756252940207, // 更新时间 + } +] +``` + +`` +GET /api/v3/openOrders `` + +获取交易对的所有当前挂单, 请小心使用不带交易对参数的调用。 + +**权重:** +- 带symbol ***1*** +- 不带 ***40***   + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | NO | + +* 不带symbol参数,会返回所有交易对的挂单 + + + +## 取消当前所有挂单 (USER_DATA) + +> **响应** + +```javascript +{ + "code": 200, + "msg": "The operation of cancel all open order is done." +} +``` + +`` +DEL /api/v3/allOpenOrders `` + +**权重:** +- ***1*** + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +orderIdList | STRING | NO | id数组字符串 +origClientOrderIdList | STRING | NO | clientOrderId数组字符串 + + +## 查询所有订单 (USER_DATA) +> **响应** +```javascript +[ + { + "orderId": 349661, // 系统订单号 + "symbol": "BTC_UP_DOWN_5M_1778483280_YUSDT", // 交易对 + "status": "NEW", // 订单状态 + "clientOrderId": "LzypgiMwkf3TQ8wwvLo8RA", // 用户自定义的订单号 + "price": "1.10000000", // 委托价格 + "avgPrice": "0.0000000000000000", // 平均成交价 + "origQty": "5",  // 原始委托数量 + "executedQty": "0", // 成交量 + "cumQuote": "0", // 成交金额 + "timeInForce": "GTC", // 有效方法 + "type": "LIMIT", // 订单类型 + "side": "BUY", // 买卖方向 + "stopPrice": "0", // 触发价 + "origType": "LIMIT", // 触发前订单类型 + "time": 1756252940207, // 订单时间 + "updateTime": 1756252940207, // 更新时间 + } +] +``` + +`` +GET /api/v3/allOrders`` + +获取所有帐户订单; 有效,已取消或已完成。 + +* 请注意,如果订单满足如下条件,不会被查询到: + * 订单生成时间 + 7天 < 当前时间 + +**权重:** +5 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | +orderId | LONG | NO | +startTime | LONG | NO | +endTime | LONG | NO | +limit | INT | NO | 默认 500; 最大 1000. + +* 查询时间范围最大不得超过7天 +* 默认查询最近7天内的数据 + + + +`` +GET /api/v3/prediction/transactionHistory`` +> **响应** + +```javascript +[ + { + "tranId": 1759115482304540227, //划转ID + "tradeId": null, //流水ID + "asset": "ASTER", //资产 + "symbol": "", //交易对 + "balanceDelta": "-500.00000000", //资金流数量,正数代表流入,负数代表流出 + "balanceInfo": "TRADE_SOURCE", //流水描述 + "time": 1759115482000, // 时间 + "type": "TRADE_SOURCE" //资金流类型 + } +] +``` + +查询交易流水 + +**权重:** +30 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +asset | STRING | NO | 资产 +type | STRING | NO | 类别 +startTime | LONG | NO | 开始时间 +endTime | LONG | NO | 结束时间 +limit | LONG | NO | 返回的结果集数量 默认值:100 最大值:1000 + +注意: + +* `type` 取值 `TRADE_TARGET`,`TRADE_SOURCE`,`TRANSFER_SPOT_TO_FUTURE`,`TRANSFER_FUTURE_TO_SPOT`,`TRANSFER_SPOT_TO_SPOT`,`AIRDROP`,`DIVIDEND`,`TRANSFER_REFUND`,`INTERNAL_TRANSFER`,`TRANSFER`,`SWAP`,`COMMISSION_REBATE`,`CASH_BACK`,`STAKING_WITHDRAW`, `STAKING_CLAIM`, `STAKING_DELEGATE`,`PREDICTION_CLAIM`,`PREDICTION_USER_REBATE`,`PREDICTION_SETTLE`,`PREDICTION_SETTLE_FEE`,`PREDICTION_MINT`,`PREDICTION_BURN` 中的一种 +* 如果`startTime` 和 `endTime` 均未发送, 只会返回最近7天的数据。 + +## 期货现货互转 (TRADE) + +> **响应:** + +```javascript +{ + "tranId": 21841, //交易id + "status": "SUCCESS" //状态 +} +``` + +`` +POST /api/v3/asset/wallet/transfer `` + +**权重:** +5 + +**参数:** + + +名称 | 类型 | 是否必需 | 描述 +---------------- | ------- | -------- | ---- +amount | DECIMAL | YES | 数量 +asset | STRING | YES | 资产 +clientTranId | STRING | YES | 交易id +kindType | STRING | YES | 交易类型 + +注意: +* kindType 取值为FUTURE_SPOT(期货转现货),SPOT_FUTURE(现货转期货) + +## 预测市场铸造 (TRADE) + +> **响应** + +```javascript +{ + "clientOrderId": "xxx", // 客户自定义订单ID + "quoteAmount": "10.00000000", // 花费的报价资产总量 + "yesPrice": "0.55000000", // 铸造时YES代币的价格 + "noPrice": "0.45000000", // 铸造时NO代币的价格(yesPrice + noPrice = 1) + "pairCount": "10.00000000" // 已铸造的YES+NO代币对数量 +} +``` + +`` +POST /api/v3/prediction/mint`` + +为预测市场铸造 YES+NO 代币对。铸造时系统按当前市场价格扣除等值报价资产,同时向账户发放等量的 YES 和 NO 代币。 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | 预测市场的 YES 代币交易对 +quantity | DECIMAL | YES | 铸造的 YES+NO 代币对数量 +newClientOrderId | STRING | NO | 客户自定义的唯一订单ID,若不填则自动生成 + +注意: +* `symbol` 必须是有效的预测市场代币交易对,且状态为 `TRADING` 或 `PENDING_TRADING` +* `quantity` 表示同时铸造的 YES 和 NO 代币对数量,铸造后账户将获得等量的 YES 代币和 NO 代币 +* `yesPrice` + `noPrice` = 1(报价资产单位) + + +## 预测市场销毁 (TRADE) + +> **响应** + +```javascript +{ + "clientOrderId": "xxx", // 客户自定义订单ID + "quoteAmount": "9.80000000", // 销毁后返还的报价资产总量 + "yesPrice": null, // 销毁操作不返回价格 + "noPrice": null, // 销毁操作不返回价格 + "pairCount": "10.00000000" // 已销毁的YES+NO代币对数量 +} +``` + +`` +POST /api/v3/prediction/burn`` + +销毁等量的 YES+NO 代币对,赎回相应的报价资产。账户需同时持有等量的 YES 代币和 NO 代币才可销毁。 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | YES | 预测市场的 YES 代币交易对 +quantity | DECIMAL | YES | 销毁的 YES+NO 代币对数量 +newClientOrderId | STRING | NO | 客户自定义的唯一订单ID,若不填则自动生成 + +注意: +* `symbol` 必须是有效的预测市场代币交易对,且状态为 `TRADING`、`PENDING_TRADING` 或 `CLOSED` +* `quantity` 表示同时销毁的 YES 和 NO 代币对数量,账户需同时持有对应数量的 YES 代币和 NO 代币 +* 销毁操作响应中 `yesPrice` 和 `noPrice` 为 null +* 市场关闭(`CLOSED`)后仍可进行销毁操作 + + +## 查询预测市场当前仓位 (USER_DATA) + +> **响应** +```javascript +[ + { + "marketName": "BTC_UP_DOWN_20260512", // 预测市场名称 + "symbol": "BTC_UP_DOWN_20260512YES", // 交易对 + "assetName": "USDT", // 结算资产 + "type": "YES", // 持仓方向: "YES" 或 "NO" + "openAvgPrice": "0.65000000", // 开仓均价 + "cumQty": "100.00000000", // 持仓总数量 + "closeAvgPrice": "0.00000000", // 平仓均价(尚未平仓则为0) + "realizedPnl": "0.00000000", // 已实现盈亏 + "closeQty": "0.00000000", // 已平仓数量 + "insertTime": 1747000000000, // 开仓时间(毫秒时间戳) + "commissionFee": "0.10000000", // 手续费 + "commissionAsset": "USDT", // 手续费资产 + "balance": "65.00000000", // 仓位价值(持仓数量 × 开仓均价) + "availableBalance": "65.00000000", // 可用余额 + } +] +``` + +`` +GET /api/v3/prediction/positions +`` + +查询当前账户的预测市场持仓列表。 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | NO | 交易对,不传则返回所有持仓 +signer | STRING | YES | API钱包地址 +nonce | STRING | YES | 当前时间的微秒值 +signature | STRING | YES | 签名 + + +## 查询预测市场历史仓位 (USER_DATA) + +> **响应** +```javascript +[ + { + "marketName": "BTC_UP_DOWN_20260501", // 预测市场名称 + "symbol": "BTC_UP_DOWN_20260501YES", // 交易对 + "asset": "USDT", // 结算资产 + "type": "YES", // 持仓方向: "YES" 或 "NO" + "openAvgPrice": "0.72000000", // 开仓均价 + "cumQty": "200.00000000", // 持仓总数量 + "closeAvgPrice": "1.00000000", // 平仓均价 + "realizedPnl": "56.00000000", // 已实现盈亏 + "closeQty": "200.00000000", // 已平仓数量 + "insertTime": 1746000000000, // 开仓时间(毫秒时间戳) + "closeTime": 1746086400000, // 平仓/结算时间(毫秒时间戳) + "status": "settled", // 仓位状态: "close"(手动平仓)或 "settled"(市场结算) + "commissionFee": "0.10000000", // 手续费 + "commissionAsset": "USDT", // 手续费资产 + "settleFee": "2.00000000", // 结算手续费(仅 status 为 "settled" 时存在) + "settleAsset": "USDT", // 结算手续费资产 + } +] +``` + +`` +GET /api/v3/prediction/positionHistories +`` + +查询当前账户的预测市场历史仓位列表(已平仓或已结算)。 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | NO | 交易对,不传则返回所有历史仓位 +startTime | LONG | NO | 开始时间(毫秒时间戳) +endTime | LONG | NO | 结束时间(毫秒时间戳) +limit | INT | NO | 返回数量,默认100,最大1000 +signer | STRING | YES | API钱包地址 +nonce | STRING | YES | 当前时间的微秒值 +signature | STRING | YES | 签名 + +注意: +* `startTime` 与 `endTime` 同时传入时,`startTime` 不得大于 `endTime` +* `limit` 取值范围为 1 ~ 1000,默认值为 100 +* `status` 字段说明: `close` 表示用户手动平仓,`settled` 表示预测市场到期结算 + +## 查询预测市场结算历史 (USER_DATA) + +> **响应** +```javascript +[ + { + "marketName": "BTC_UP_DOWN_20260501", // 预测市场名称 + "asset": "BTC_UP_DOWN_20260501YES", // 代币资产(YES 或 NO 代币) + "symbol": "BTC_UP_DOWN_20260501YES", // 交易对 + "marketStartTime": 1746000000000, // 市场开始时间(毫秒时间戳) + "marketEndTime": 1746086400000, // 市场结束/结算时间(毫秒时间戳) + "shareAmount": "200.00000000", // 结算时持有的份额数量 + "settleAsset": "USDT", // 结算资产 + "settleAmount": "200.00000000", // 结算获得金额 + "settleFeeAmount": "2.00000000", // 结算手续费 + "entryPrice": "0.72000000", // 平均入场价格 + "settlePrice": "1.00000000", // 最终结算价格 + "realizedPnl": "56.00000000", // 结算后已实现盈亏 + "status": "settled" // 结算状态 + } +] +``` + +`` +GET /api/v3/prediction/settlementHistories +`` + +查询当前账户的预测市场结算历史(已到期结算的市场)。 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | NO | 交易对,不传则返回所有结算记录 +startTime | LONG | NO | 按市场开始时间过滤(毫秒时间戳) +endTime | LONG | NO | 按市场结束时间过滤(毫秒时间戳) +limit | INT | NO | 返回数量,默认100,最大1000 +signer | STRING | YES | API钱包地址 +nonce | STRING | YES | 当前时间的微秒值 +signature | STRING | YES | 签名 + +注意: +* `startTime` 与 `endTime` 同时传入时,`startTime` 不得大于 `endTime` +* `limit` 取值范围为 1 ~ 1000,默认值为 100 +* `settleAmount` 为结算总收入,`realizedPnl` = `settleAmount` 减去成本 +* `settleFeeAmount` 从结算收入中扣除 + +## 现货提现手续费 (NONe) +> **响应** +```javascript +{ + "tokenPrice": 1.00019000, + "gasCost": 0.5000, + "gasUsdValue": 0.5 +} +``` + +`` +GET /api/v3/aster/withdraw/estimateFee +`` + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +chainId | STRING | YES | +asset | STRING | YES | + +注意: +* chainId: 1(ETH),56(BSC),42161(Arbi) +* gasCost: 提现所需的最少数量的手续费 + +## 现货提现 (USER_DATA) +> **响应** +```javascript +{ + "withdrawId": "1014729574755487744", + "hash":"0xa6d1e617a3f69211df276fdd8097ac8f12b6ad9c7a49ba75bbb24f002df0ebb" +} +``` + +`` +POST /api/v3/aster/user-withdraw`` + +**权重:** +5 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +chainId | STRING | YES | +asset | STRING | YES | +amount | STRING | YES | +fee | STRING | YES | +receiver | STRING | YES | +nonce | STRING | YES | 当前时间的微秒值 +userSignature | STRING | YES | + +注意: +* chainId: 1(ETH),56(BSC),42161(Arbi) +* receiver : 当前账户的地址 +* 如果期货余额不足,会从spot账户划转到期货账户,进行提现 +* userSignature demo + +```shell +const domain = { + name: 'Aster', + version: '1', + chainId: 56, + verifyingContract: ethers.ZeroAddress, + } + +const currentTime = Date.now() * 1000 + +const types = { + Action: [ + {name: "type", type: "string"}, + {name: "destination", type: "address"}, + {name: "destination Chain", type: "string"}, + {name: "token", type: "string"}, + {name: "amount", type: "string"}, + {name: "fee", type: "string"}, + {name: "nonce", type: "uint256"}, + {name: "aster chain", type: "string"}, + ], + } + const value = { + 'type': 'Withdraw', + 'destination': '0xD9cA6952F1b1349d27f91E4fa6FB8ef67b89F02d', + 'destination Chain': 'BSC', + 'token': 'USDT', + 'amount': '10.123400', + 'fee': '1.234567891', + 'nonce': currentTime, + 'aster chain': 'Mainnet', + } + + +const signature = await signer.signTypedData(domain, types, value) +``` + +## 账户信息 (USER_DATA) +> **响应** +```javascript +{ + "feeTier": 0, + "canTrade": true, + "canDeposit": true, + "canWithdraw": true, + "canBurnAsset": true, + "updateTime": 0, +   "balances": [ + { + "asset": "BTC", + "free": "4723846.89208129", + "locked": "0.00000000" + }, + { + "asset": "LTC", + "free": "4763368.68006011", + "locked": "0.00000000" + } + ] +} +``` + +`` +GET /api/v3/account`` + +获取当前账户信息。 + +**权重:** +5 + +**参数:** + +名称 | 类型 | 是否必需| 描述 +------------ | ------------ | ------------ | ------------ + + +## 账户成交历史 (USER_DATA) +> **响应** +```javascript +[ + { + "symbol": "BTC_UP_DOWN_5M_1778483280_YUSDT", + "id": 1002, + "orderId": 266358, + "side": "BUY", + "price": "1", + "qty": "2", + "quoteQty": "2", + "commission": "0.00105000", + "commissionAsset": "BNB", + "time": 1755656788798, + "counterpartyId": 19, + "createUpdateId": null, + "maker": false, + "buyer": true + } +] +``` + +`` +GET /api/v3/userTrades `` + +获取账户指定交易对的成交历史 + +**权重:** +5 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +symbol | STRING | NO | +orderId|LONG|NO| 必须要和参数`symbol`一起使用. +startTime | LONG | NO | +endTime | LONG | NO | +fromId | LONG | NO | 起始Trade id。 默认获取最新交易。 +limit | INT | NO | 默认 500; 最大 1000. + +* 如果`startTime` 和 `endTime` 均未发送, 只会返回最近7天的数据。 +* startTime 和 endTime 的最大间隔为7天 +* 不能同时传`fromId`与`startTime` 或 `endTime` +       + + + + +--- +# Websocket 行情推送 + +* 本篇所列出的所有wss接口的baseurl为: **wss://pstream.asterdex.com** +* Streams有单一原始 stream 或组合 stream +* 单一原始 streams 格式为 **/ws/\** +* 组合streams的URL格式为 **/stream?streams=\/\/\** +* 订阅组合streams时,事件payload会以这样的格式封装: **{"stream":"\","data":\}** +* stream名称中所有交易对均为 **小写** +* 每个到 **pstream.asterdex.com** 的链接有效期不超过24小时,请妥善处理断线重连。 +* 每3分钟,服务端会发送ping帧,客户端应当在10分钟内回复pong帧,否则服务端会主动断开链接。允许客户端发送不成对的pong帧(即客户端可以以高于10分钟每次的频率发送pong帧保持链接)。 + +## 实时订阅/取消数据流 + +* 以下数据可以通过websocket发送以实现订阅或取消订阅数据流。示例如下。 +* 响应内容中的`id`是无符号整数,作为往来信息的唯一标识。 +* 如果相应内容中的 `result` 为 `null`,表示请求发送成功。 + + +### 订阅一个信息流 +> **响应** + ```javascript + { + "result": null, + "id": 1 + } + ``` +* **请求** + { + "method": "SUBSCRIBE", + "params": + [ + "btc_up_dowm_5m_1778483280_yusdt@aggTrade", + "btc_up_dowm_5m_1778483280_yusdt@depth" + ], + "id": 1 + } + + +### 取消订阅一个信息流 + +> **响应** + + ```javascript + { + "result": null, + "id": 312 + } + ``` + +* **请求** + { + "method": "UNSUBSCRIBE", + "params": + [ + "btc_up_dowm_5m_1778483280_yusdt@depth" + ], + "id": 312 + } + + +### 已订阅信息流 + +> **响应** + + ```javascript + { + "result": [ + "btc_up_dowm_5m_1778483280_yusdt@aggTrade" + ], + "id": 3 + } + ``` + +* **请求** + + { + "method": "LIST_SUBSCRIPTIONS", + "id": 3 + } + + +### 设定属性 +当前,唯一可以设置的属性是设置是否启用`combined`("组合")信息流。 +当使用`/ws/`("原始信息流")进行连接时,combined属性设置为`false`,而使用 `/stream/`进行连接时则将属性设置为`true`。 + +> **响应** + + ```javascript +{ + "result": null, + "id": 5 +} + ``` + +* **请求** + { + "method": "SET_PROPERTY", + "params": + [ + "combined", + true + ], + "id": 5 + } + + +### 检索属性 + +> **响应** + ```javascript + { + "result": true, // Indicates that combined is set to true. + "id": 2 + } + ``` + +* **请求** + + { + "method": "GET_PROPERTY", + "params": + [ + "combined" + ], + "id": 2 + } + + +###错误信息 + +错误信息 | 描述 +---|--- +{"code": 0, "msg": "Unknown property"} | `SET_PROPERTY` 或 `GET_PROPERTY`中应用的参数无效 +{"code": 1, "msg": "Invalid value type: expected Boolean", "id": '%s'} | 仅接受`true`或`false` +{"code": 2, "msg": "Invalid request: property name must be a string"}| 提供的属性名无效 +{"code": 2, "msg": "Invalid request: request ID must be an unsigned integer"}| 参数`id`未提供或`id`值是无效类型 +{"code": 2, "msg": "Invalid request: unknown variant %s, expected one of `SUBSCRIBE`, `UNSUBSCRIBE`, `LIST_SUBSCRIPTIONS`, `SET_PROPERTY`, `GET_PROPERTY` at line 1 column 28"} | 错字提醒,或提供的值不是预期类型 +{"code": 2, "msg": "Invalid request: too many parameters"}| 数据中提供了不必要参数 +{"code": 2, "msg": "Invalid request: property name must be a string"} | 未提供属性名 +{"code": 2, "msg": "Invalid request: missing field `method` at line 1 column 73"} | 数据未提供`method` +{"code":3,"msg":"Invalid JSON: expected value at line %s column %s"} | JSON 语法有误. + + +## 归集交易流 + + +> **Payload:** +```javascript +{ + "e": "aggTrade", // 事件类型 + "E": 123456789, // 事件时间 + "s": "BTC_UP_DOWN_5M_1778483280_YUSDT", // 交易对 + "a": 12345, // 归集交易ID + "p": "0.001", // 成交价格 + "q": "100", // 成交数量 + "f": 100, // 被归集的首个交易ID + "l": 105, // 被归集的末次交易ID + "T": 123456785, // 成交时间 + "m": true, // 买方是否是做市方。如true,则此次成交是一个主动卖出单,否则是一个主动买入单。 +} +``` + +归集交易 stream 推送交易信息,是对单一订单的集合。 + +**Stream 名称:** `@aggTrade` + +**Update Speed:** 实时 + + +## 逐笔交易 + + +> **Payload:** +```javascript +{ + "e": "trade", // 事件类型 + "E": 123456789, // 事件时间 + "s": "BTC_UP_DOWN_5M_1778483280_YUSDT", // 交易对 + "t": 12345, // 交易ID + "p": "0.001", // 成交价格 + "q": "100", // 成交数量 + "T": 123456785, // 成交时间 + "m": true, // 买方是否是做市方。如true,则此次成交是一个主动卖出单,否则是一个主动买入单。 +} +``` + +**Stream Name:** `@trade` + +逐笔交易推送每一笔成交的信息。**成交**,或者说交易的定义是仅有一个吃单者与一个挂单者相互交易 + + +## K线 Streams +> **Payload:** +```javascript +{ + "e": "kline", // 事件类型 + "E": 123456789, // 事件时间 + "s": "BTC_UP_DOWN_5M_1778483280_YUSDT", // 交易对 + "k": { + "t": 123400000, // 这根K线的起始时间 + "T": 123460000, // 这根K线的结束时间 + "s": "BTC_UP_DOWN_5M_1778483280_YUSDT", // 交易对 + "i": "1m", // K线间隔 + "f": 100, // 这根K线期间第一笔成交ID + "L": 200, // 这根K线期间末一笔成交ID + "o": "0.0010", // 这根K线期间第一笔成交价 + "c": "0.0020", // 这根K线期间末一笔成交价 + "h": "0.0025", // 这根K线期间最高成交价 + "l": "0.0015", // 这根K线期间最低成交价 + "v": "1000", // 这根K线期间成交量 + "n": 100, // 这根K线期间成交笔数 + "x": false, // 这根K线是否完结(是否已经开始下一根K线) + "q": "1.0000", // 这根K线期间成交额 + "V": "500", // 主动买入的成交量 + "Q": "0.500", // 主动买入的成交额 + "B": "123456" // 忽略此参数 + } +} +``` + +K线stream逐秒推送所请求的K线种类(最新一根K线)的更新。 + +**Stream Name:** `@kline_` + +**Update Speed:** 2000ms + +**K线图间隔参数:** + +m -> 分钟; h -> 小时; d -> 天; w -> 周; M -> 月 + +* 1m +* 3m +* 5m +* 15m +* 30m +* 1h +* 2h +* 4h +* 6h +* 8h +* 12h +* 1d +* 3d +* 1w +* 1M + + +## 按 Symbol 的精简Ticker + +> **Payload:** +```javascript + { + "e": "24hrMiniTicker", // 事件类型 + "E": 123456789, // 事件时间 + "s": "BTC_UP_DOWN_5M_1778483280_YUSDT", // 交易对 + "c": "0.0025", // 最新成交价格 + "o": "0.0010", // 24小时前开始第一笔成交价格 + "h": "0.0025", // 24小时内最高成交价 + "l": "0.0010", // 24小时内最低成交价 + "v": "10000", // 成交量 + "q": "18" // 成交额 + } +``` + +按Symbol刷新的最近24小时精简ticker信息 + +**Stream 名称:** `@miniTicker` + +**Update Speed:** 1000ms + + +## 全市场所有Symbol的精简Ticker + +> **Payload:** +```javascript +[ + { + // 数组每一个元素对应一个交易对,内容与 \@miniTicker相同 + } +] +``` + +同上,只是推送所有交易对.需要注意的是,只有更新的ticker才会被推送. + +**Stream名称:** !miniTicker@arr + +**Update Speed:** 1000ms + +## 按Symbol的完整Ticker + +> **Payload:** +```javascript +{ + "e": "24hrTicker", // 事件类型 + "E": 123456789, // 事件时间 + "s": "BTC_UP_DOWN_5M_1778483280_YUSDT", // 交易对 + "p": "0.0015", // 24小时价格变化 + "P": "250.00", // 24小时价格变化(百分比) + "w": "0.0018", // 平均价格 + "c": "0.0025", // 最新成交价格 + "Q": "10", // 最新成交交易的成交量 + "o": "0.0010", // 整整24小时前,向后数的第一次成交价格 + "h": "0.0025", // 24小时内最高成交价 + "l": "0.0010", // 24小时内最低成交价 + "v": "10000", // 24小时内成交量 + "q": "18", // 24小时内成交额 + "O": 0, // 统计开始时间 + "C": 86400000, // 统计结束时间 + "F": 0, // 24小时内第一笔成交交易ID + "L": 18150, // 24小时内最后一笔成交交易ID + "n": 18151 // 24小时内成交数 +} +``` + +每秒推送单个交易对的过去24小时滚动窗口标签统计信息。 + +**Stream 名称:** `@ticker` + +**Update Speed:** 1000ms + +## 全市场所有交易对的完整Ticker + +> **Payload:** +```javascript +[ + { + // Same as @ticker payload + } +] +``` + +推送全市场所有交易对刷新的24小时完整ticker信息。需要注意的是,没有更新的ticker不会被推送。 + +**Stream Name:** `!ticker@arr` + +**Update Speed:** 1000ms + + +## 按Symbol的最优挂单信息 + +> **Payload:** +```javascript +{ + "u":400900217, // order book updateId + "s":"BTC_UP_DOWN_5M_1778483280_YUSDT", // 交易对 + "b":"25.35190000", // 买单最优挂单价格 + "B":"31.21000000", // 买单最优挂单数量 + "a":"25.36520000", // 卖单最优挂单价格 + "A":"40.66000000" // 卖单最优挂单数量 +} +``` + +实时推送指定交易对最优挂单信息 + +**Stream Name:** `@bookTicker` + +**Update Speed:** 实时 + +## 全市场最优挂单信息 +> **Payload:** +```javascript +{ + // 同 @bookTicker payload +} +``` + +实时推送所有交易对最优挂单信息 + +**Stream Name:** `!bookTicker` + +**Update Speed:** 实时 + + +## 有限档深度信息 + +> **Payload:** +```javascript +{ + "e": "depthUpdate", // Event type + "E": 123456789, // Event time + "T": 123456788, // Transaction time + "s": "BTC_UP_DOWN_5M_1778483280_YUSDT", // Symbol + "U": 100, // First update ID in event + "u": 120, // Final update ID in event + "pu": 99, // Final update Id in last stream(ie `u` in last stream) +  "bids": [ // Bids to be updated + [ + "0.0024", // Price level to be updated + "10" // Quantity + ] + ], + "asks": [ // Asks to be updated + [ + "0.0026", // Price level to be updated + "100" // Quantity + ] + ] +} +``` + +每秒或每100毫秒推送有限档深度信息。levels表示几档买卖单信息, 可选 5/10/20档 + +**Stream Names:** `@depth` 或 `@depth@100ms`. + +**Update Speed:** 1000ms 或 100ms + + +## 增量深度信息 +> **Payload:** +```javascript +{ + "e": "depthUpdate", // Event type + "E": 123456789, // Event time + "T": 123456788, // Transaction time + "s": "BTC_UP_DOWN_5M_1778483280_YUSDT", // Symbol + "U": 100, // First update ID in event + "u": 120, // Final update ID in event + "pu": 99, // Final update Id in last stream(ie `u` in last stream) + "b": [ // Bids to be updated + [ + "5.4", // Price level to be updated + "10" // Quantity + ] + ], + "a": [ // Asks to be updated + [ + "5.6", // Price level to be updated + "100" // Quantity + ] + ] +} +``` + +每秒或每100毫秒推送orderbook的变化部分(如果有) + +**Stream Name:** `@depth` 或 `@depth@100ms` + +**Update Speed:** 1000ms 或 100ms + +## 如何正确在本地维护一个orderbook副本 +1. 订阅 **wss://pstream.asterdex.com/ws/btc_up_dowm_5m_1778483280_yusdt@depth** +2. 开始缓存收到的更新。同一个价位,后收到的更新覆盖前面的。 +3. 访问Rest接口 **https://papi.asterdex.com/api/v3/depth?symbol=BTC_UP_DOWN_5M_1778483280_YUSDT&limit=1000** 获得一个1000档的深度快照 +4. 将目前缓存到的信息中`u` <= 步骤3中获取到的快照中的`lastUpdateId`的部分丢弃(丢弃更早的信息,已经过期)。 +5. 将深度快照中的内容更新到本地orderbook副本中,并从websocket接收到的第一个`U` <= `lastUpdateId`+1 **且** `u` >= `lastUpdateId`+1 的event开始继续更新本地副本。 +6. 每一个新event的`U`应该恰好等于上一个event的`u`+1,否则可能出现了丢包,请从step3重新进行初始化。 +7. 每一个event中的挂单量代表这个价格目前的挂单量**绝对值**,而不是相对变化。 +8. 如果某个价格对应的挂单量为0,表示该价位的挂单已经撤单或者被吃,应该移除这个价位。 + + + + + + +# Websocket账户信息推送 + +* 本篇所列出API接口的base url : **https://papi.asterdex.com** +* 用于订阅账户数据的 `listenKey` 从创建时刻起有效期为60分钟 +* 可以通过 `PUT` 一个 `listenKey` 延长60分钟有效期 +* 可以通过`DELETE`一个 `listenKey` 立即关闭当前数据流,并使该`listenKey` 无效 +* 在具有有效`listenKey`的帐户上执行`POST`将返回当前有效的`listenKey`并将其有效期延长60分钟 +* websocket接口的baseurl: **wss://pstream.asterdex.com** +* U订阅账户数据流的stream名称为 **/ws/\** +* 每个链接有效期不超过24小时,请妥善处理断线重连。 + + +## Listen Key(现货账户) + +### 生成 Listen Key (USER_STREAM) + +> **响应** +```javascript +{ + "listenKey": "pqia91ma19a5s61cv6a81va65sdf19v8a65a1a5s61cv6a81va65sdf19v8a65a1" +} +``` + +`` +POST /api/v3/listenKey +`` + +开始一个新的数据流。除非发送 keepalive,否则数据流于60分钟后关闭。如果该帐户具有有效的`listenKey`,则将返回该`listenKey`并将其有效期延长60分钟。 + +**权重:** +1 + +**参数:** +NONE + +### 延长 Listen Key 有效期 (USER_STREAM) + +> **响应** +```javascript +{} +``` + +`` +PUT /api/v3/listenKey +`` + +有效期延长至本次调用后60分钟,建议每30分钟发送一个 ping 。 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +listenKey | STRING | YES + + +### 关闭 Listen Key (USER_STREAM) + +> **响应** +```javascript +{} +``` + +`` +DELETE /api/v3/listenKey +`` + +关闭用户数据流。 + +**权重:** +1 + +**参数:** + +名称 | 类型 | 是否必需 | 描述 +------------ | ------------ | ------------ | ------------ +listenKey | STRING | YES + + +## Payload: 账户更新 + +每当帐户余额发生更改时,都会发送一个事件`outboundAccountPosition`,其中包含可能由生成余额变动的事件而变动的资产。 + +> **Payload** +```javascript +{ + "B":[// 余额 + { + "a":"SLP25",   // 资产名称 + "f":"10282.42029415",   // 可用余额 + "l":"653.00000001"   // 冻结余额 + }, + { + "a":"ADA25", + "f":"9916.96229880", + "l":"34.00510000" + } + ], + "e":"outboundAccountPosition",   // 事件类型 + "T":1649926447190,   // 账户末次更新时间戳 + "E":1649926447205   // 事件时间 + "m":"WITHDRAW" // 事件推出原因 +} +``` + + +## Payload: 订单更新 + +订单通过`executionReport`事件进行更新。 + +> **Payload** + +```javascript +{ + "s":"BTC_UP_DOWN_5M_1778483280_YUSDT",   // 交易对 + "c":"Xzh0gnxT41PStbwqOtXnjD",  // 客户端自定订单ID + "S":"SELL",   // 订单方向 + "o":"LIMIT",   // 订单类型 + "f":"GTC",   // 有效方式 + "q":"10.001000",   // 订单原始数量 + "p":"19.1000000000",   // 订单原始价格 + "ap":"19.0999999955550656", //平均价格 + "P":"0",  // 条件订单触发价格 + "x":"TRADE",   // 本次事件的具体执行类型 + "X":"PARTIALLY_FILLED",   // 订单的当前状态 + "i":27,   // 订单ID + "l":"1",     // 订单末次成交量 + "z":"8.999000",   // 订单累计已成交量 + "L":"19.1000000000",   // 订单末次成交价格 + "n":"0.00382000",   // 手续费数量 + "N":"SLP25",   // 手续费资产类型 + "T":1649926447190,   // 成交时间 + "t":18,   // 成交ID + "m":true,   // 该成交是作为挂单成交吗? + "ot":"LIMIT", //初始订单类型 + "O":0,   // 订单时间 + "Z":"171.88089996",   // 累计报价资产交易数量 + "Y":"19.1000000000000000",   // 最近报价交易数量 + "Q":"0",   // 报价数量 + "e":"executionReport",   // 事件类型 + "E":1649926447209  // 事件时间 +} +``` + + +**执行类型:** +* NEW 新订单 +* CANCELED 订单被取消 +* REJECTED 新订单被拒绝 +* TRADE 订单有新成交 +* EXPIRED 订单失效(根据订单的Time In Force参数) + + + +## Event: TradePro + +> **Topic Subscribe:** + +```javascript +{ + "method": "SUBSCRIBE", + "params": [ + "btc_up_dowm_5m_1778483280_yusdt@tradepro" + ], + "id": 3 +} +``` + +> **Payload:** + +```javascript +{ + "stream": "btc_up_dowm_5m_1778483280_yusdt@tradepro", + "data": { + "e": "tradepro", + "E": 1773751963081, + "T": 1773751963079, + "s": "BTC_UP_DOWN_5M_1778483280_YUSDT", + "t": 128884613, + "p": "73685.5", + "q": "0.297", + "h": "0X0000000000000000000000000000000000000000000000000000000000000000", + "m": [ + "hidden", + "hidden" + ] + } +} +``` + +* h: 该笔交易的交易哈希(Transaction hash) + +* m: 包含交易参与方地址的数组: + + * m[0]: Taker 地址(主动成交方) + + * m[1]: Maker 地址(挂单方) + + + +## Event: 预测市场结算Twap数据更新 + +> **Topic Subscribe:** + +* eventName@event + +```javascript +{ + "method": "SUBSCRIBE", + "params": [ + "btc_up_down_5m@event" + ], + "id": 3 +} +``` + +> **Payload:** + +```javascript +{ + 'e': 'market_start', // 事件开始,推送初始价格 + 'm': 'ETH_UP_DOWN_5M_1779846360', // 事件名称 + 'y': 'ETH_UP_DOWN_5M_1779846360_YUSDT', // 上涨 symbol 名称 + 'n': 'ETH_UP_DOWN_5M_1779846360_NUSDT', // 下跌 symbol 名称 + 'p': '2073.68023256', // 初始价格 + 't': 1779846360000 // 推送时间 +} + +{ + 'e': 'market_twap', // 事件 TWAP 数据更新,推送每次的 TWAP 取点数据 + 'm': 'ETH_UP_DOWN_5M_1779846660', // 事件名称 + 'y': 'ETH_UP_DOWN_5M_1779846660_YUSDT', // 上涨 symbol 名称 + 'n': 'ETH_UP_DOWN_5M_1779846660_NUSDT', // 下跌 symbol 名称 + 'p': '2076.40762162', // 价格 + 'r': 0, // 剩余数据点数量 + 't': 1779846960000, // 推送时间 + 'w': 'Y' // 获胜结果(仅在最后一条推送中出现):Y 代表上涨,N 代表下跌 +} +``` + + +#错误代码 + +> error JSON payload: + +```javascript +{ + "code":-1121, + "msg":"Invalid symbol." +} +``` + +错误由两部分组成:错误代码和消息。 代码是通用的,但是消息可能会有所不同。 + + +## 10xx - 常规服务器或网络问题 +### -1000 UNKNOWN + * An unknown error occurred while processing the request. + * 处理请求时发生未知错误。 + +### -1001 DISCONNECTED + * Internal error; unable to process your request. Please try again. + * 内部错误; 无法处理您的请求。 请再试一次. + +### -1002 UNAUTHORIZED + * You are not authorized to execute this request. + * 您无权执行此请求。 + +### -1003 TOO_MANY_REQUESTS + * Too many requests queued. + * 排队的请求过多。 + * Too many requests; please use the websocket for live updates. + * 请求权重过多; 请使用websocket获取最新更新。 + * Too many requests; current limit is %s requests per minute. Please use the websocket for live updates to avoid polling the API. + * 请求权重过多; 当前限制为每分钟%s请求权重。 请使用websocket进行实时更新,以避免轮询API。 + * Way too many requests; IP banned until %s. Please use the websocket for live updates to avoid bans. + * 请求权重过多; IP被禁止,直到%s。 请使用websocket进行实时更新,以免被禁。 + +### -1004 DUPLICATE_IP + * This IP is already on the white list + * IP地址已经在白名单 + +### -1005 NO_SUCH_IP + * No such IP has been white listed + * 白名单上没有此IP地址 + +### -1006 UNEXPECTED_RESP + * An unexpected response was received from the message bus. Execution status unknown. + * 从消息总线收到意外的响应。执行状态未知。 + +### -1007 TIMEOUT + * Timeout waiting for response from backend server. Send status unknown; execution status unknown. + * 等待后端服务器响应超时。 发送状态未知; 执行状态未知。 + +### -1014 UNKNOWN_ORDER_COMPOSITION + * Unsupported order combination. + * 不支持当前的下单参数组合 + +### -1015 TOO_MANY_ORDERS + * Too many new orders. + * 新订单太多。 + * Too many new orders; current limit is %s orders per %s. + * 新订单太多; 当前限制为每%s %s个订单。 + +### -1016 SERVICE_SHUTTING_DOWN + * This service is no longer available. + * 该服务不可用。 + +### -1020 UNSUPPORTED_OPERATION + * This operation is not supported. + * 不支持此操作。 + +### -1022 INVALID_SIGNATURE + * Signature for this request is not valid. + * 此请求的签名无效。 + +### -1023 START_TIME_GREATER_THAN_END_TIME + * Start time is greater than end time. + * 参数里面的开始时间在结束时间之后 + + +## 11xx - Request issues +### -1100 ILLEGAL_CHARS + * Illegal characters found in a parameter. + * 在参数中发现非法字符。 + * Illegal characters found in parameter '%s'; legal range is '%s'. + * 在参数`%s`中发现非法字符; 合法范围是`%s`。 + +### -1101 TOO_MANY_PARAMETERS + * Too many parameters sent for this endpoint. + * 为此端点发送的参数太多。 + * Too many parameters; expected '%s' and received '%s'. + * 参数太多;预期为`%s`并收到了`%s`。 + * Duplicate values for a parameter detected. + * 检测到的参数值重复。 + +### -1102 MANDATORY_PARAM_EMPTY_OR_MALFORMED + * A mandatory parameter was not sent, was empty/null, or malformed. + * 未发送强制性参数,该参数为空/空或格式错误。 + * Mandatory parameter '%s' was not sent, was empty/null, or malformed. + * 强制参数`%s`未发送,为空/空或格式错误。 + * Param '%s' or '%s' must be sent, but both were empty/null! + * 必须发送参数`%s`或`%s`,但两者均为空! + +### -1103 UNKNOWN_PARAM + * An unknown parameter was sent. + * 发送了未知参数。 + +### -1104 UNREAD_PARAMETERS + * Not all sent parameters were read. + * 并非所有发送的参数都被读取。 + * Not all sent parameters were read; read '%s' parameter(s) but was sent '%s'. + * 并非所有发送的参数都被读取; 读取了`%s`参数,但被发送了`%s`。 + +### -1105 PARAM_EMPTY + * A parameter was empty. + * 参数为空。 + * Parameter '%s' was empty. + * 参数`%s`为空。 + +### -1106 PARAM_NOT_REQUIRED + * A parameter was sent when not required. + * 发送了不需要的参数。 + * Parameter '%s' sent when not required. + * 发送了不需要参数`%s`。 + +### -1111 BAD_PRECISION + * Precision is over the maximum defined for this asset. + * 精度超过为此资产定义的最大值。 + +### -1112 NO_DEPTH + * No orders on book for symbol. + * 交易对没有挂单。 + +### -1114 TIF_NOT_REQUIRED + * TimeInForce parameter sent when not required. + * 发送的`TimeInForce`参数不需要。 + +### -1115 INVALID_TIF + * Invalid timeInForce. + * 无效的`timeInForce` + +### -1116 INVALID_ORDER_TYPE + * Invalid orderType. + * 无效订单类型。 + +### -1117 INVALID_SIDE + * Invalid side. + * 无效买卖方向。 + +### -1118 EMPTY_NEW_CL_ORD_ID + * New client order ID was empty. + * 新的客户订单ID为空。 + +### -1119 EMPTY_ORG_CL_ORD_ID + * Original client order ID was empty. + * 客户自定义的订单ID为空。 + +### -1120 BAD_INTERVAL + * Invalid interval. + * 无效时间间隔。 + +### -1121 BAD_SYMBOL + * Invalid symbol. + * 无效的交易对。 + +### -1125 INVALID_LISTEN_KEY + * This listenKey does not exist. + * 此`listenKey`不存在。 + +### -1127 MORE_THAN_XX_HOURS + * Lookup interval is too big. + * 查询间隔太大。 + * More than %s hours between startTime and endTime. + * 从开始时间到结束时间之间超过`%s`小时。 + +### -1128 OPTIONAL_PARAMS_BAD_COMBO + * Combination of optional parameters invalid. + * 可选参数组合无效。 + +### -1130 INVALID_PARAMETER + * Invalid data sent for a parameter. + * 发送的参数为无效数据。 + * Data sent for parameter '%s' is not valid. + * 发送参数`%s`的数据无效。 + +### -1136 INVALID_NEW_ORDER_RESP_TYPE + * Invalid newOrderRespType. + * 无效的 newOrderRespType。 + + +## 20xx - Processing Issues +### -2010 NEW_ORDER_REJECTED + * NEW_ORDER_REJECTED + * 新订单被拒绝 + +### -2011 CANCEL_REJECTED + * CANCEL_REJECTED + * 取消订单被拒绝 + +### -2013 NO_SUCH_ORDER + * Order does not exist. + * 订单不存在。 + +### -2014 BAD_API_KEY_FMT + * API-key format invalid. + * API-key 格式无效。 + +### -2015 REJECTED_MBX_KEY + * Invalid API-key, IP, or permissions for action. + * 无效的API密钥,IP或操作权限。 + +### -2016 NO_TRADING_WINDOW + * No trading window could be found for the symbol. Try ticker/24hrs instead. + * 找不到该交易对的交易窗口。 尝试改为24小时自动报价。 + +### -2018 BALANCE_NOT_SUFFICIENT + * Balance is insufficient. + * 余额不足 + +### -2020 UNABLE_TO_FILL + * Unable to fill. + * 无法成交 + +### -2021 ORDER_WOULD_IMMEDIATELY_TRIGGER + * Order would immediately trigger. + * 订单可能被立刻触发 + +### -2022 REDUCE_ONLY_REJECT + * ReduceOnly Order is rejected. + * `ReduceOnly`订单被拒绝 + +### -2024 POSITION_NOT_SUFFICIENT + * Position is not sufficient. + * 持仓不足 + +### -2025 MAX_OPEN_ORDER_EXCEEDED + * Reach max open order limit. + * 挂单量达到上限 + +### -2026 REDUCE_ONLY_ORDER_TYPE_NOT_SUPPORTED + * This OrderType is not supported when reduceOnly. + * 当前订单类型不支持`reduceOnly` + +## 40xx - Filters and other Issues +### -4000 INVALID_ORDER_STATUS + * Invalid order status. + * 订单状态不正确 + +### -4001 PRICE_LESS_THAN_ZERO + * Price less than 0. + * 价格小于0 + +### -4002 PRICE_GREATER_THAN_MAX_PRICE + * Price greater than max price. + * 价格超过最大值 + +### -4003 QTY_LESS_THAN_ZERO + * Quantity less than zero. + * 数量小于0 + +### -4004 QTY_LESS_THAN_MIN_QTY + * Quantity less than min quantity. + * 数量小于最小值 + +### -4005 QTY_GREATER_THAN_MAX_QTY + * Quantity greater than max quantity. + * 数量大于最大值 + +### -4006 STOP_PRICE_LESS_THAN_ZERO + * Stop price less than zero. + * 触发价小于最小值 + +### -4007 STOP_PRICE_GREATER_THAN_MAX_PRICE + * Stop price greater than max price. + * 触发价大于最大值 + +### -4008 TICK_SIZE_LESS_THAN_ZERO + * Tick size less than zero. + * 价格精度小于0 + +### -4009 MAX_PRICE_LESS_THAN_MIN_PRICE + * Max price less than min price. + * 最大价格小于最小价格 + +### -4010 MAX_QTY_LESS_THAN_MIN_QTY + * Max qty less than min qty. + * 最大数量小于最小数量 + +### -4011 STEP_SIZE_LESS_THAN_ZERO + * Step size less than zero. + * 步进值小于0 + +### -4012 MAX_NUM_ORDERS_LESS_THAN_ZERO + * Max num orders less than zero. + * 最大订单量小于0 + +### -4013 PRICE_LESS_THAN_MIN_PRICE + * Price less than min price. + * 价格小于最小价格 + +### -4014 PRICE_NOT_INCREASED_BY_TICK_SIZE + * Price not increased by tick size. + * 价格增量不是价格精度的倍数。 + +### -4015 INVALID_CL_ORD_ID_LEN + * Client order id is not valid. + * 客户订单ID有误。 + * Client order id length should not be more than 36 chars + * 客户订单ID长度应该不多于36字符 + +### -4016 PRICE_HIGHTER_THAN_MULTIPLIER_UP + * Price is higher than mark price multiplier cap. + +### -4017 MULTIPLIER_UP_LESS_THAN_ZERO + * Multiplier up less than zero. + * 价格上限小于0 + +### -4018 MULTIPLIER_DOWN_LESS_THAN_ZERO + * Multiplier down less than zero. + * 价格下限小于0 + +### -4019 COMPOSITE_SCALE_OVERFLOW + * Composite scale too large. + +### -4020 TARGET_STRATEGY_INVALID + * Target strategy invalid for orderType '%s',reduceOnly '%b'. + * 目标策略值不适合`%s`订单状态, 只减仓`%b`。 + +### -4021 INVALID_DEPTH_LIMIT + * Invalid depth limit. + * 深度信息的`limit`值不正确。 + * '%s' is not valid depth limit. + * `%s`不是合理的深度信息的`limit`值。 + +### -4022 WRONG_MARKET_STATUS + * market status sent is not valid. + * 发送的市场状态不正确。 + +### -4023 QTY_NOT_INCREASED_BY_STEP_SIZE + * Qty not increased by step size. + * 数量的递增值不是步进值的倍数。 + +### -4024 PRICE_LOWER_THAN_MULTIPLIER_DOWN + * Price is lower than mark price multiplier floor. + +### -4025 MULTIPLIER_DECIMAL_LESS_THAN_ZERO + * Multiplier decimal less than zero. + +### -4026 COMMISSION_INVALID + * Commission invalid. + * 收益值不正确 + * `%s` less than zero. + * `%s`少于0 + * `%s` absolute value greater than `%s` + * `%s`绝对值大于`%s` + +### -4027 INVALID_ACCOUNT_TYPE + * Invalid account type. + * 账户类型不正确。 + +### -4029 INVALID_TICK_SIZE_PRECISION + * Tick size precision is invalid. + * 价格精度小数点位数不正确。 + +### -4030 INVALID_STEP_SIZE_PRECISION + * Step size precision is invalid. + * 步进值小数点位数不正确。 + +### -4031 INVALID_WORKING_TYPE + * Invalid parameter working type + * 不正确的参数类型 + * Invalid parameter working type: `%s` + * 不正确的参数类型: `%s` + +### -4032 EXCEED_MAX_CANCEL_ORDER_SIZE + * Exceed maximum cancel order size. + * 超过可以取消的最大订单量。 + * Invalid parameter working type: `%s` + * 不正确的参数类型: `%s` + +### -4044 INVALID_BALANCE_TYPE + * Balance Type is invalid. + * 余额类型不正确。 + +### -4045 MAX_STOP_ORDER_EXCEEDED + * Reach max stop order limit. + * 达到止损单的上限。 + +### -4055 AMOUNT_MUST_BE_POSITIVE + * Amount must be positive. + * 数量必须是正整数 + +### -4056 INVALID_API_KEY_TYPE + * Invalid api key type. + * API key的类型不正确 + +### -4057 INVALID_RSA_PUBLIC_KEY + * Invalid api public key + * API key不正确 + +### -4058 MAX_PRICE_TOO_LARGE + * maxPrice and priceDecimal too large,please check. + * maxPrice和priceDecimal太大,请检查。 + +### -4060 INVALID_POSITION_SIDE + * Invalid position side. + * 仓位方向不正确。 + +### -4061 POSITION_SIDE_NOT_MATCH + * Order's position side does not match user's setting. + * 订单的持仓方向和用户设置不一致。 + +### -4062 REDUCE_ONLY_CONFLICT + * Invalid or improper reduceOnly value. + * 仅减仓的设置不正确。 + +### -4084 UPCOMING_METHOD + * Method is not allowed currently. Upcoming soon. + * 方法不支持 + +### -4086 INVALID_PRICE_SPREAD_THRESHOLD + * Invalid price spread threshold + * 无效的价差阀值 + +### -4087 REDUCE_ONLY_ORDER_PERMISSION + * User can only place reduce only order + * 用户只能下仅减仓订单 + +### -4088 NO_PLACE_ORDER_PERMISSION + * User can not place order currently + * 用户当前不能下单 + +### -4114 INVALID_CLIENT_TRAN_ID_LEN + * clientTranId is not valid + * clientTranId不正确 + * Client tran id length should be less than 64 chars + * 客户的tranId长度应该小于64个字符 + +### -4115 DUPLICATED_CLIENT_TRAN_ID + * clientTranId is duplicated + * clientTranId重复 + * Client tran id should be unique within 7 days + * 客户的tranId应在7天内唯一 + +### -4118 REDUCE_ONLY_MARGIN_CHECK_FAILED + * ReduceOnly Order Failed. Please check your existing position and open orders + * 仅减仓订单失败。请检查现有的持仓和挂单 + +### -4131 MARKET_ORDER_REJECT + * The counterparty's best price does not meet the PERCENT_PRICE filter limit + * 交易对手的最高价格未达到PERCENT_PRICE过滤器限制 + +### -4135 INVALID_ACTIVATION_PRICE + * Invalid activation price + * 无效的激活价格 + +### -4137 QUANTITY_EXISTS_WITH_CLOSE_POSITION + * Quantity must be zero with closePosition equals true + * 数量必须为0,当closePosition为true时 + +### -4138 REDUCE_ONLY_MUST_BE_TRUE + * Reduce only must be true with closePosition equals true + * Reduce only 必须为true,当closePosition为true时 + +### -4139 ORDER_TYPE_CANNOT_BE_MKT + * Order type can not be market if it's unable to cancel + * 订单类型不能为市价单如果不能取消 + +### -4140 INVALID_OPENING_POSITION_STATUS + * Invalid symbol status for opening position + * 无效的交易对状态 + +### -4141 SYMBOL_ALREADY_CLOSED + * Symbol is closed + * 交易对已下架 + +### -4142 STRATEGY_INVALID_TRIGGER_PRICE + * REJECT: take profit or stop order will be triggered immediately + * 拒绝:止盈止损单将立即被触发 + +### -4164 MIN_NOTIONAL + * Order's notional must be no smaller than 5.0 (unless you choose reduce only) + * 订单的名义价值不可以小于5,除了使用reduce only + * Order's notional must be no smaller than %s (unless you choose reduce only) + * 订单的名义价值不可以小于`%s`,除了使用reduce only + +### -4165 INVALID_TIME_INTERVAL + * Invalid time interval + * 无效的间隔 + * Maximum time interval is %s days + * 最大的时间间隔为 `%s` 天 + +### -4183 PRICE_HIGHTER_THAN_STOP_MULTIPLIER_UP + * Price is higher than stop price multiplier cap. + * 止盈止损订单价格不应高于触发价与报价乘数上限的乘积 + * Limit price can't be higher than %s. + * 止盈止损订单价格不应高于 `%s` + +### -4184 PRICE_LOWER_THAN_STOP_MULTIPLIER_DOWN + * Price is lower than stop price multiplier floor. + * 止盈止损订单价格不应低于触发价与报价乘数下限的乘积 + * Limit price can't be lower than %s. + * 止盈止损订单价格不应低于 `%s`f From 04ddfed86048069d74fd26ed51ab10e84de8796f Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Fri, 5 Jun 2026 15:05:10 +0800 Subject: [PATCH 129/131] announcement --- announcement.md | 109 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 109 insertions(+) create mode 100644 announcement.md diff --git a/announcement.md b/announcement.md new file mode 100644 index 0000000..cf092be --- /dev/null +++ b/announcement.md @@ -0,0 +1,109 @@ +# Announcement API + +响应数据有 **1 分钟本地缓存**。 + +`title`、`subtitle`、`content` 根据请求头语言自动返回对应语言版本;语言含 `zh` 时返回中文,其次匹配精确语言,兜底返回英文 `en`。 + +--- + +## AnnouncementResp(公共响应字段) + +| 字段 | 类型 | 说明 | +|------|------|------| +| `id` | Long | 公告 ID | +| `category` | String | 分类,见下方枚举 | +| `title` | String | 标题 | +| `subtitle` | String | 副标题 | +| `content` | String | 正文内容 | +| `publishTime` | Date | 发布时间 | +| `jumpLink` | String | 跳转链接 | + +## category 枚举值 + +| 值 | 说明 | +|----|------| +| `ACTIVITY` | 活动公告 | +| `NEW_LISTING` | 新币上线 | +| `DELISTING` | 下架公告 | +| `UPDATES` | 更新公告 | + +--- + +## Public 接口 + +### GET `/v1/public/composite/ae/announcement/get` + +根据 ID 获取单条公告详情。 + +**请求参数** + +| 参数 | 类型 | 必填 | 说明 | +|------|------|------|------| +| `id` | Long | 是 | 公告 ID | + +**响应** `CommonRet` + +--- + +### POST `/v1/public/composite/ae/announcement/search` + +分页查询公告列表,支持按分类筛选。 + +**请求体** + +| 参数 | 类型 | 必填 | 说明 | +|------|------|------|------| +| `page` | Integer | 是 | 页码(从 1 开始) | +| `size` | Integer | 是 | 每页条数 | +| `category` | String | 否 | 公告分类,不传则返回所有分类 | + +**响应** `CommonRet>` + +| 字段 | 类型 | 说明 | +|------|------|------| +| `total` | Long | 总条数 | +| `rows` | List\ | 公告列表 | + +--- + +## Private 接口(需登录) + +### POST `/v1/private/composite/ae/announcement/search-direct` + +分页查询当前用户的定向公告。用户地址从登录态自动获取,无需传参。 + +**请求体** + +| 参数 | 类型 | 必填 | 说明 | +|------|------|------|------| +| `page` | Integer | 是 | 页码(从 1 开始) | +| `size` | Integer | 是 | 每页条数 | + +**响应** `CommonRet>` + +| 字段 | 类型 | 说明 | +|------|------|------| +| `total` | Long | 总条数 | +| `rows` | List\ | 公告列表 | + +--- + +### GET `/v1/private/composite/ae/announcement/direct-list` + +获取当前用户的定向公告列表(不分页)。 + +**响应** `CommonRet>` + +--- + +### GET `/v1/private/composite/ae/announcement/get-direct` + +根据 ID 获取当前用户的单条定向公告详情。 + +**请求参数** + +| 参数 | 类型 | 必填 | 说明 | +|------|------|------|------| +| `id` | Long | 是 | 公告 ID | + +**响应** `CommonRet` From bf2cef8720eccc5df3b75b15d4dad16b13a53e83 Mon Sep 17 00:00:00 2001 From: "ivan.z-apx" Date: Fri, 5 Jun 2026 15:20:37 +0800 Subject: [PATCH 130/131] announcement --- announcement-en.md | 140 +++++++++++++++++++++++++++++++++++++++++++++ announcement-zh.md | 140 +++++++++++++++++++++++++++++++++++++++++++++ announcement.md | 109 ----------------------------------- 3 files changed, 280 insertions(+), 109 deletions(-) create mode 100644 announcement-en.md create mode 100644 announcement-zh.md delete mode 100644 announcement.md diff --git a/announcement-en.md b/announcement-en.md new file mode 100644 index 0000000..dcd4f60 --- /dev/null +++ b/announcement-en.md @@ -0,0 +1,140 @@ +# Announcement API + +## AnnouncementResp (Common Response Fields) + +| Field | Type | Description | +|-------|------|-------------| +| `id` | Long | Announcement ID | +| `category` | String | Category, see enum values below | +| `title` | String | Title | +| `subtitle` | String | Subtitle | +| `content` | String | Body content | +| `publishTime` | Date | Publish time (Unix timestamp in milliseconds) | +| `jumpLink` | String | Detail page URL | + +## Category Enum Values + +| Value | Description | +|-------|-------------| +| `ACTIVITY` | Activity announcements | +| `NEW_LISTING` | New token listings | +| `DELISTING` | Delisting notices | +| `UPDATES` | Platform updates | + +--- + +## Public Endpoints + +### GET `/bapi/composite/v1/public/composite/ae/announcement/get` + +Retrieve a single announcement by ID. + +**Request Parameters** + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `id` | Long | Yes | Announcement ID | + +**Request Example** + +```bash +curl -X GET "https://www.asterdex.com/bapi/composite/v1/public/composite/ae/announcement/get?id=12345" +``` + +**Response Example** + +```json +{ + "code": "000000", + "message": null, + "data": { + "id": 12345, + "category": "NEW_LISTING", + "title": "AsterDex Will List XYZ Token", + "subtitle": "XYZ/USDT Trading Pair Now Available", + "content": "AsterDex is pleased to announce the listing of XYZ Token...", + "publishTime": 1717545600000, + "jumpLink": "https://www.asterdex.com/en/support/announcement/detail/12345" + }, + "success": true +} +``` + +--- + +### POST `/bapi/composite/v1/public/composite/ae/announcement/search` + +Paginated search for announcements with optional category filtering. + +**Request Body** + +| Parameter | Type | Required | Description | +|-----------|------|----------|-------------| +| `page` | Integer | Yes | Page number (starts from 1) | +| `size` | Integer | Yes | Number of items per page | +| `category` | String | No | Announcement category; returns all categories if omitted | + +**Request Examples** + +Fetch all categories, page 1, 10 items per page: + +```bash +curl -X POST "https://www.asterdex.com/bapi/composite/v1/public/composite/ae/announcement/search" \ + -H "Content-Type: application/json" \ + -d '{ + "page": 1, + "size": 10 + }' +``` + +Filter by category (new listings): + +```bash +curl -X POST "https://www.asterdex.com/bapi/composite/v1/public/composite/ae/announcement/search" \ + -H "Content-Type: application/json" \ + -d '{ + "page": 1, + "size": 10, + "category": "NEW_LISTING" + }' +``` + +**Response** `CommonRet>` + +| Field | Type | Description | +|-------|------|-------------| +| `total` | Long | Total number of records | +| `rows` | List\ | List of announcements | + +**Response Example** + +```json +{ + "code": "000000", + "message": null, + "data": { + "total": 128, + "rows": [ + { + "id": 12345, + "category": "NEW_LISTING", + "title": "AsterDex Will List XYZ Token", + "subtitle": "XYZ/USDT Trading Pair Now Available", + "content": "AsterDex is pleased to announce the listing of XYZ Token...", + "publishTime": 1717545600000, + "jumpLink": "https://www.asterdex.com/en/support/announcement/detail/12345" + }, + { + "id": 12344, + "category": "NEW_LISTING", + "title": "AsterDex Will List ABC Token", + "subtitle": "ABC/USDT Trading Pair Now Available", + "content": "AsterDex is pleased to announce the listing of ABC Token...", + "publishTime": 1717459200000, + "jumpLink": "https://www.asterdex.com/en/support/announcement/detail/12344" + } + ] + }, + "success": true +} +``` diff --git a/announcement-zh.md b/announcement-zh.md new file mode 100644 index 0000000..66330bc --- /dev/null +++ b/announcement-zh.md @@ -0,0 +1,140 @@ +# 公告 API + +## AnnouncementResp(公共响应字段) + +| 字段 | 类型 | 说明 | +|------|------|------| +| `id` | Long | 公告 ID | +| `category` | String | 分类,见下方枚举 | +| `title` | String | 标题 | +| `subtitle` | String | 副标题 | +| `content` | String | 正文内容 | +| `publishTime` | Date | 发布时间(毫秒时间戳) | +| `jumpLink` | String | 跳转链接 | + +## category 枚举值 + +| 值 | 说明 | +|----|------| +| `ACTIVITY` | 活动公告 | +| `NEW_LISTING` | 新币上线 | +| `DELISTING` | 下架公告 | +| `UPDATES` | 更新公告 | + +--- + +## Public 接口 + +### GET `/bapi/composite/v1/public/composite/ae/announcement/get` + +根据 ID 获取单条公告详情。 + +**请求参数** + +| 参数 | 类型 | 必填 | 说明 | +|------|------|------|------| +| `id` | Long | 是 | 公告 ID | + +**请求示例** + +```bash +curl -X GET "https://www.asterdex.com/bapi/composite/v1/public/composite/ae/announcement/get?id=12345" +``` + +**响应示例** + +```json +{ + "code": "000000", + "message": null, + "data": { + "id": 12345, + "category": "NEW_LISTING", + "title": "AsterDex Will List XYZ Token", + "subtitle": "XYZ/USDT Trading Pair Now Available", + "content": "AsterDex is pleased to announce the listing of XYZ Token...", + "publishTime": 1717545600000, + "jumpLink": "https://www.asterdex.com/en/support/announcement/detail/12345" + }, + "success": true +} +``` + +--- + +### POST `/bapi/composite/v1/public/composite/ae/announcement/search` + +分页查询公告列表,支持按分类筛选。 + +**请求体** + +| 参数 | 类型 | 必填 | 说明 | +|------|------|------|------| +| `page` | Integer | 是 | 页码(从 1 开始) | +| `size` | Integer | 是 | 每页条数 | +| `category` | String | 否 | 公告分类,不传则返回所有分类 | + +**请求示例** + +查询所有分类,第 1 页,每页 10 条: + +```bash +curl -X POST "https://www.asterdex.com/bapi/composite/v1/public/composite/ae/announcement/search" \ + -H "Content-Type: application/json" \ + -d '{ + "page": 1, + "size": 10 + }' +``` + +按分类筛选(新币上线): + +```bash +curl -X POST "https://www.asterdex.com/bapi/composite/v1/public/composite/ae/announcement/search" \ + -H "Content-Type: application/json" \ + -d '{ + "page": 1, + "size": 10, + "category": "NEW_LISTING" + }' +``` + +**响应** `CommonRet>` + +| 字段 | 类型 | 说明 | +|------|------|------| +| `total` | Long | 总条数 | +| `rows` | List\ | 公告列表 | + +**响应示例** + +```json +{ + "code": "000000", + "message": null, + "data": { + "total": 128, + "rows": [ + { + "id": 12345, + "category": "NEW_LISTING", + "title": "AsterDex Will List XYZ Token", + "subtitle": "XYZ/USDT Trading Pair Now Available", + "content": "AsterDex is pleased to announce the listing of XYZ Token...", + "publishTime": 1717545600000, + "jumpLink": "https://www.asterdex.com/en/support/announcement/detail/12345" + }, + { + "id": 12344, + "category": "NEW_LISTING", + "title": "AsterDex Will List ABC Token", + "subtitle": "ABC/USDT Trading Pair Now Available", + "content": "AsterDex is pleased to announce the listing of ABC Token...", + "publishTime": 1717459200000, + "jumpLink": "https://www.asterdex.com/en/support/announcement/detail/12344" + } + ] + }, + "success": true +} +``` diff --git a/announcement.md b/announcement.md deleted file mode 100644 index cf092be..0000000 --- a/announcement.md +++ /dev/null @@ -1,109 +0,0 @@ -# Announcement API - -响应数据有 **1 分钟本地缓存**。 - -`title`、`subtitle`、`content` 根据请求头语言自动返回对应语言版本;语言含 `zh` 时返回中文,其次匹配精确语言,兜底返回英文 `en`。 - ---- - -## AnnouncementResp(公共响应字段) - -| 字段 | 类型 | 说明 | -|------|------|------| -| `id` | Long | 公告 ID | -| `category` | String | 分类,见下方枚举 | -| `title` | String | 标题 | -| `subtitle` | String | 副标题 | -| `content` | String | 正文内容 | -| `publishTime` | Date | 发布时间 | -| `jumpLink` | String | 跳转链接 | - -## category 枚举值 - -| 值 | 说明 | -|----|------| -| `ACTIVITY` | 活动公告 | -| `NEW_LISTING` | 新币上线 | -| `DELISTING` | 下架公告 | -| `UPDATES` | 更新公告 | - ---- - -## Public 接口 - -### GET `/v1/public/composite/ae/announcement/get` - -根据 ID 获取单条公告详情。 - -**请求参数** - -| 参数 | 类型 | 必填 | 说明 | -|------|------|------|------| -| `id` | Long | 是 | 公告 ID | - -**响应** `CommonRet` - ---- - -### POST `/v1/public/composite/ae/announcement/search` - -分页查询公告列表,支持按分类筛选。 - -**请求体** - -| 参数 | 类型 | 必填 | 说明 | -|------|------|------|------| -| `page` | Integer | 是 | 页码(从 1 开始) | -| `size` | Integer | 是 | 每页条数 | -| `category` | String | 否 | 公告分类,不传则返回所有分类 | - -**响应** `CommonRet>` - -| 字段 | 类型 | 说明 | -|------|------|------| -| `total` | Long | 总条数 | -| `rows` | List\ | 公告列表 | - ---- - -## Private 接口(需登录) - -### POST `/v1/private/composite/ae/announcement/search-direct` - -分页查询当前用户的定向公告。用户地址从登录态自动获取,无需传参。 - -**请求体** - -| 参数 | 类型 | 必填 | 说明 | -|------|------|------|------| -| `page` | Integer | 是 | 页码(从 1 开始) | -| `size` | Integer | 是 | 每页条数 | - -**响应** `CommonRet>` - -| 字段 | 类型 | 说明 | -|------|------|------| -| `total` | Long | 总条数 | -| `rows` | List\ | 公告列表 | - ---- - -### GET `/v1/private/composite/ae/announcement/direct-list` - -获取当前用户的定向公告列表(不分页)。 - -**响应** `CommonRet>` - ---- - -### GET `/v1/private/composite/ae/announcement/get-direct` - -根据 ID 获取当前用户的单条定向公告详情。 - -**请求参数** - -| 参数 | 类型 | 必填 | 说明 | -|------|------|------|------| -| `id` | Long | 是 | 公告 ID | - -**响应** `CommonRet` From 0401110597fe27987a6659bfc21d68b127356cd7 Mon Sep 17 00:00:00 2001 From: Valisthea Date: Fri, 5 Jun 2026 10:50:03 -0400 Subject: [PATCH 131/131] Harden demo scripts: imports, nonce, success check - aster-code.py, sol_agent.py: migrate encode_structured_data to encode_typed_data (removed in eth-account >= 0.13; the demos failed to import on a fresh install). Output is byte-identical, cross-checked against ethers signTypedData. - nonce: use microsecond time.time_ns()//1000, locked and strictly monotonic, so concurrent workers or a restart never reuse a nonce. The previous int(time.time()) gave 1-second resolution and could collide (server returns -4225 Nonce Expired). - sol_agent.py: print the nonce actually sent instead of calling get_nonce() a second time. - consolidation.js: fix `if (x = 'SUCCESS')` (assignment, not comparison) and guard error returns so a failed transfer or withdraw no longer reports success. - add requirements.txt and package.json to pin runnable dependencies. --- demo/aster-code.py | 30 +++++++++++++++--------------- demo/consolidation.js | 4 ++-- demo/package.json | 10 ++++++++++ demo/requirements.txt | 7 +++++++ demo/sol_agent.py | 27 ++++++++++++--------------- 5 files changed, 46 insertions(+), 32 deletions(-) create mode 100644 demo/package.json create mode 100644 demo/requirements.txt diff --git a/demo/aster-code.py b/demo/aster-code.py index a367a0a..edfe030 100644 --- a/demo/aster-code.py +++ b/demo/aster-code.py @@ -1,8 +1,9 @@ import time +import threading import requests from eth_account import Account -from eth_account.messages import encode_structured_data +from eth_account.messages import encode_typed_data from copy import deepcopy import json @@ -113,7 +114,7 @@ def sign_v3_eip712(private_key, message, primary_type) -> str: print(data) print(sign_data) - msg = encode_structured_data(sign_data) + msg = encode_typed_data(full_message=sign_data) signed = Account.sign_message(msg, private_key=private_key) return signed.signature.hex() @@ -151,26 +152,25 @@ def sign_v3(private_key, message) -> str: # print(typed_data_sign) # print(message) - msg = encode_structured_data(typed_data_sign) + msg = encode_typed_data(full_message=typed_data_sign) signed = Account.sign_message(msg, private_key=private_key) print(signed.signature.hex()) return signed.signature.hex() -_last_ms = 0 -_i = 0 +_last_nonce = 0 +_nonce_lock = threading.Lock() def get_nonce(): - global _last_ms, _i - now_ms = int(time.time()) - - if now_ms == _last_ms: - _i += 1 - else: - _last_ms = now_ms - _i = 0 - - return now_ms * 1_000_000 + _i + # Microsecond timestamp; the server requires microsecond precision within 10s. + # Locked and strictly monotonic so concurrent callers never reuse a nonce. + global _last_nonce + with _nonce_lock: + n = time.time_ns() // 1000 + if n <= _last_nonce: + n = _last_nonce + 1 + _last_nonce = n + return n def send_by_url(method_config): param = method_config['params'] diff --git a/demo/consolidation.js b/demo/consolidation.js index aaf5136..5b43fbe 100644 --- a/demo/consolidation.js +++ b/demo/consolidation.js @@ -195,7 +195,7 @@ async function main() { sendToMainAddressRes = await send(spot_send_toAddress, { 'asset': config.asset, "amount": config.amount, "toAddress": main_address }) console.log('sendToMainAddressRes:', sendToMainAddressRes) use_new_apikey = false - if(sendToMainAddressRes['status'] = 'SUCCESS'){ + if(sendToMainAddressRes && sendToMainAddressRes['status'] === 'SUCCESS'){ console.log('归集成功:', config.address); }else{ console.log('归集失败:', config.address); @@ -221,7 +221,7 @@ async function main() { 'userSignature': withdraw_ignature, 'receiver': main_address, 'asset': withdraw_asset, 'amount': withdraw_amount }) - if(spotWithdraw['hash'] != ''){ + if(spotWithdraw && spotWithdraw['hash']){ console.log('提现成功:', spotWithdraw['hash']); }else{ console.log('提现失败:', spotWithdraw); diff --git a/demo/package.json b/demo/package.json new file mode 100644 index 0000000..6b728b6 --- /dev/null +++ b/demo/package.json @@ -0,0 +1,10 @@ +{ + "name": "aster-api-demo", + "version": "1.0.0", + "private": true, + "description": "Aster API demo scripts (consolidation, api-key creation, withdrawal).", + "dependencies": { + "axios": "^1.7.0", + "ethers": "^6.13.0" + } +} diff --git a/demo/requirements.txt b/demo/requirements.txt new file mode 100644 index 0000000..8797312 --- /dev/null +++ b/demo/requirements.txt @@ -0,0 +1,7 @@ +# Pinned dependencies for the Python demos (aster-code.py, sol_agent.py). +# eth-account >= 0.13 is required: encode_typed_data() replaced the older +# encode_structured_data() API that earlier examples imported. +eth-account>=0.13.0 +requests>=2.31.0 +base58>=2.1.1 +PyNaCl>=1.5.0 diff --git a/demo/sol_agent.py b/demo/sol_agent.py index 201db78..7fba218 100644 --- a/demo/sol_agent.py +++ b/demo/sol_agent.py @@ -3,7 +3,7 @@ import base58 from eth_account import Account -from eth_account.messages import encode_structured_data +from eth_account.messages import encode_typed_data from nacl.signing import SigningKey import time import requests @@ -92,22 +92,19 @@ def sign(message, all_bytes=None) : print("signature hex:", signature.hex()) return base58.b58encode(signature).decode() -_last_ms = 0 -_i = 0 +_last_nonce = 0 _nonce_lock = threading.Lock() def get_nonce(): - global _last_ms, _i + # Microsecond timestamp; the server requires microsecond precision within 10s. + # Locked and strictly monotonic so concurrent callers never reuse a nonce. + global _last_nonce with _nonce_lock: - now_ms = int(time.time()) - - if now_ms == _last_ms: - _i += 1 - else: - _last_ms = now_ms - _i = 0 - - return now_ms * 1_000_000 + _i + n = time.time_ns() // 1000 + if n <= _last_nonce: + n = _last_nonce + 1 + _last_nonce = n + return n def send_by_url(api) : my_dict = api['params'] @@ -117,7 +114,7 @@ def send_by_url(api) : my_dict['nonce'] = str(get_nonce()) my_dict['user'] = user - print(str(get_nonce())) + print(my_dict['nonce']) signature = '' param = '' @@ -130,7 +127,7 @@ def send_by_url(api) : param = urllib.parse.urlencode(my_dict) print(param) typed_data['message']['msg'] = param - message = encode_structured_data(typed_data) + message = encode_typed_data(full_message=typed_data) signature = Account.sign_message(message, private_key=signer_pri_key).signature.hex() url = url + '?' + param + '&signature=' + signature