API Architecture Overview
The AsterDEX API provides a direct gateway to the decentralized exchange's matching engine, bypassing the standard Web3 interface. This allows latencies comparable to centralized exchanges (CEX) while keeping asset custody non-custodial.
API Security: Your Top Priority
Your API keys grant programmatic access to your trading account. Treat them with the same level of security as your private keys. A compromised API key can lead to significant financial losses.
Key security practices:
- IP whitelist: Always bind your API key to the static IP address from which you will send requests.
- Permission restrictions: Grant the key only the minimum necessary rights. If the key is meant solely for reading data, do not give it trading permissions.
- Secure storage: Never hard-code keys into your code. Use environment variables or dedicated secret-management services.
- Regular audits: Periodically review active API keys, their permissions and bound IP addresses. Remove keys that are no longer in use.
API Use Cases: AI Trading and Algorithmic Strategies
The AsterDEX API is the foundation for algorithmic derivatives trading. Instead of manual trading, quant funds and AI models use our API for:
- Funding Rate Arbitrage: Monitoring the
Premium Indexendpoint to profit from rate differences between platforms. - High-frequency market making (HFT): Maintaining liquidity in the order book using WebSockets to minimize latency.
- Liquidation Hunting: Analyzing
Mark PriceandIndex Priceto enter positions automatically during other participants' liquidations.
Generating API Keys and Linking an API Wallet
On AsterDEX, the classic REST API works in tandem with your Web3 profile.
- Connect your Web3 wallet (MetaMask or WalletConnect) in the main DEX interface. Your wallet acts as the base API Wallet.
- Go to the API Management section. Using a cryptographic signature via
Web3.jsorEthers.js(handled under the hood by the UI), confirm ownership of the address. - Click "Create API". The system will generate an API Key and a Secret Key.
- Important: The Secret Key is displayed only once. Copy it. Unlike interaction with Smart Contracts ABI, where you sign each transaction with your wallet, high-frequency trading via the API uses an HMAC-SHA256 signature created with the Secret Key.
API Architecture
The AsterDEX API offers two main interfaces for interaction, covered in detail in our article "REST API vs. WebSocket":
- REST API (pull model): A request-response interface, ideal for actions you initiate yourself, such as placing an order, checking a balance or canceling an order.
- WebSocket API (push model): Establishes a persistent connection, allowing the server to push real-time data to you. This is essential for tracking the order book, trades and other market events without delays.
Quick reference: environments and libraries
- Mainnet:
https://fapi.asterdex.com| WS:wss://fstream.asterdex.com/ws - Testnet:
https://testnet.asterdex.com— use it to debug bots without risking funds. - SDK & Utilities: For fast Node.js integration, use official and community
NPMandYarnpackages. For example:yarn add asterdex-api. - Authentication: HMAC SHA256
Error Handling (Error Codes) and Debugging
When automating trading strategies, it is important to handle server responses correctly. Below are the most common AsterDEX API error codes and how to resolve them:
| Code | Message | Solution |
|---|---|---|
| -1021 | Timestamp for this request is outside of the recvWindow. | Clock desynchronization. Synchronize your server time with the AsterDEX system time (/fapi/v1/time endpoint) or increase the recvWindow parameter. |
| -2015 | Invalid API-key, IP, or permissions for action. | Check the IP whitelist. Make sure the "Enable Trading" permission is enabled for the key. |
| -2019 | Margin is insufficient. | Not enough margin to open a position. Check your current balance or reduce the order size based on the configured leverage. |
Guides and Code Examples
To help you get started faster, we have prepared a series of detailed guides and articles:
- Building a Simple Trading Bot in Python — A step-by-step guide with code examples showing how to connect to the API, fetch market data and place orders.
- Streaming Data over WebSocket with Node.js — receive real-time trade and order book data.
- Automatic Portfolio Rebalancing — A tutorial on creating a script that automatically rebalances assets according to a predefined strategy.
- Integration Examples and Building API Clients — Ready-made code samples in different languages to serve as a basis for your own clients.
- REST API vs. WebSocket — Which technology should you choose for your trading strategy?
- Everything About HMAC-SHA256 Authentication — A detailed explanation of how and why to generate signatures to protect your requests.
- Rate Limits Guide — How to write efficient code without getting blocked.
First Steps: Connecting and Examples
Checking Connectivity (Ping)
To verify that you can connect to the API, use the `/fapi/v1/ping` endpoint, which requires no authentication.
curl -X GET "https://fapi.asterdex.com/fapi/v1/ping"
A successful response returns an empty JSON object: `{}`.
Subscribing to Data over WebSocket
To receive real-time data, for example aggregated trades for the BTC/USDT pair, connect to the WebSocket and send a `SUBSCRIBE` message.
URL: `wss://fstream.asterdex.com/ws`
Subscription example:
{
"method": "SUBSCRIBE",
"params": [
"btcusdt@aggTrade"
],
"id": 1
}
Quick Start with the NPM Package (Node.js)
Instead of manually crafting HMAC-SHA256 signatures, you can use the ready-made asterdex-api package. Example of fetching a futures account balance:
const AsterDEX = require('asterdex-api');
// Инициализация клиента
const client = new AsterDEX({
apiKey: 'ВАШ_API_KEY',
apiSecret: 'ВАШ_SECRET_KEY',
baseURL: 'https://fapi.asterdex.com' // Используйте testnet URL для отладки
});
// Асинхронный запрос баланса
async function getBalance() {
try {
const balance = await client.futuresAccountBalance();
console.log("Доступный баланс USDT:", balance.find(b => b.asset === 'USDT').availableBalance);
} catch (error) {
console.error("Ошибка API:", error.message);
}
}
getBalance();
Key Endpoints Overview
Exchange Information (`/fapi/v1/exchangeinfo`)
This endpoint is your entry point. It provides all the necessary information about trading rules, pairs, price filters and lot sizes. It is crucial to request this data before you start trading so you understand constraints such as `tickSize` (minimum price increment) and `stepSize` (minimum order quantity).
Market Data
- /fapi/v1/depth: Order book depth. Lets you see current bids and asks.
- /fapi/v1/klines: Historical candlestick data for analyzing price movements.
- /fapi/v1/historicalTrades: Historical trade feed.
Margin and Futures Position Management
- POST /fapi/v1/marginType: Change the margin type for a symbol. Choose between Cross Margin and Isolated Margin.
- POST /fapi/v1/leverage: Set the initial leverage for a trading pair.
- GET /fapi/v1/premiumIndex: Retrieve the current Mark Price, Index Price and Funding Rate.
Account and Order Management
- /fapi/v2/balance: Fetch your account balance.
- /fapi/v2/positionRisk: Information about your open positions.
- POST /fapi/v1/order: Place an order. Advanced types are supported: LIMIT, MARKET, Take Profit Market, Trailing Stop. Be sure to specify the Time in Force parameter (GTC, IOC, FOK) for limit orders.
- DELETE /fapi/v1/order: Cancel an open order.
For the complete list of endpoints and their parameters, see the official AsterDex API documentation on GitHub.
Third-Party Integrations: Terminals and On-Chain Analytics
Connecting Trading Terminals (MetaScalp)
If you do manual scalping, you can connect AsterDEX to professional front ends such as MetaScalp or CScalp. In the connection settings, select "AsterDEX", choose the network type (Mainnet) and paste the API Key and Secret Key you generated earlier. The terminal will automatically route your orders through the API with minimal ping.
On-Chain Data via Bitquery (GraphQL)
For deep quantitative analytics, the standard REST API may not be enough. AsterDEX is integrated with blockchain indexing protocols such as Bitquery. Using GraphQL queries, you can retrieve raw historical data from the decentralized exchange directly from its smart contracts: liquidity pool volumes, token routing paths and global liquidation events across the network.
Choosing a Data Source: REST API vs Bitquery (GraphQL)
To build a full-fledged analytical system, it is important to know where to get data from. AsterDEX offers two independent data layers:
- AsterDEX REST & WebSocket (Off-chain Engine):
Ideal for: Trading bots, HFT, scalping (MetaScalp), fetching the live order book (Order Book L2) with < 10 ms latency.
Limitations: Stores only aggregated trade history. - Bitquery GraphQL API (On-chain Data):
Ideal for: Deep strategy backtesting, auditing AsterDEX smart contracts, tracking real whale transactions on-chain (TX Hashes) and liquidity routing.
Limitations: Latency tied to block time; not suitable for instant order placement.
Frequently Asked Questions (FAQ) about the AsterDEX API
What is the base URL of the AsterDEX REST API?
The base URL for REST requests (Mainnet): https://fapi.asterdex.com. For streaming data over WebSocket use wss://fstream.asterdex.com/ws. For the test environment use https://testnet.asterdex.com.
What are the AsterDEX API rate limits?
The base rate limit is 1200 requests per minute per IP address. Exceeding it results in a temporary IP ban (HTTP 429 Too Many Requests).
How do I keep my API keys secure?
Use an IP whitelist, bind keys to your Web3 API Wallet, restrict permissions (for example, "read-only" for on-chain analytics), and never store the Secret Key in publicly visible code on GitHub.