API Architecture Overview: Cosmos App-Chain & Indexer
Unlike version v3, dYdX Chain (v4) is a fully independent layer-1 blockchain built on the Cosmos SDK. There is no centralized order-matching server: the order book lives in the memory of the validator network. This means a paradigm shift for developers.
→ More about the dYdX Chain architecture
Two layers of interaction:
- Indexer API (reading): Specialized servers that index the blockchain and expose REST and WebSocket APIs (candles, order books, trade history) for fast operation without loading RPC nodes.
- RPC/gRPC (writing): Orders (placing, canceling) are blockchain transactions. You must sign them locally and submit them to validators (gas-free).
Security: The familiar "API keys" are a thing of the past. On dYdX v4 you operate with a Cosmos private key. Compromise of your subaccount key lets an attacker take control of your funds.
Key security practices:
- Subaccount separation: Create a separate Subaccount for each bot.
- Secure storage: Keep your secret mnemonic only in
.envor AWS Secrets Manager. Never hard-code keys into your code.
API Use Cases: AI Trading and Algorithmic Strategies
Thanks to zero gas fees for placing and canceling orders, dYdX Chain is ideal for sophisticated algorithmic strategies:
- Funding Rate Arbitrage: Delta-neutral strategies between dYdX and CEXs (e.g., Binance) using USD quotes.
- High-frequency market making (HFT): The validators' in-memory order book allows placing and canceling dozens of orders per second.
- Liquidation hunting: Analyzing Indexer Price to capture market imbalances during forced position closures.
Connecting: Account Derivation and Local Keys
On dYdX v4, the developer onboarding process differs significantly from classic exchanges:
- Subaccount derivation: You connect your Ethereum wallet to dYdX, and via cryptographic signature it generates a
dydx...address (Cosmos format) and the subaccount's mnemonic phrase. - Key export: From the exchange interface (the "Export Secret Phrase" section for API use) you obtain the secret phrase.
- SDK initialization: In your code you use the official libraries (
@dydxprotocol/v4-client-jsorv4-web-python-client), pass them the mnemonic, and the SDK handles all the heavy lifting of building Cosmos transactions (MsgPlaceOrder).
Important: Your bot must build and sign every order (transaction) locally before submitting it to a validator node.
API Architecture and Endpoints
dYdX provides a public cluster of Indexers for data retrieval:
Environments reference
- Mainnet Indexer REST:
https://indexer.dydx.trade - Mainnet Indexer WebSocket:
wss://indexer.dydx.trade/v4/ws - Testnet:
https://indexer.v4testnet.dydx.exchange— use it for testing strategies. - Official SDKs: We recommend using the official TypeScript and Python clients, as they automatically parse Protobuf messages and handle RPC requests.
Error Handling (Cosmos RPC Errors)
Since orders are submitted as blockchain transactions, errors are most often related to network state or transaction format:
| Error type / Message | Cause | Solution |
|---|---|---|
| Account sequence mismatch | Asynchronously submitting multiple transactions with the same nonce (sequence). | Manage the sequence locally in your code. Wait for mempool confirmation or increment the sequence correctly when sending orders in parallel. |
| Insufficient margin | Not enough collateral (USDC) for a position with the specified leverage. | Adjust the order size or check the subaccount's free balance via the Indexer API. |
| Invalid Signature | The order is signed incorrectly or was altered in transit. | Make sure you are using an up-to-date version of the official SDK that correctly builds the Protobuf bytes before signing. |
Guides and Tutorials
To get started quickly with dYdX Chain, we recommend using the official SDKs:
- Trading bot in Python (v4-client) — Wallet initialization, MsgPlaceOrder signing and submission over gRPC.
- Streaming WebSocket data (TypeScript) — Receiving Orderbook L2 and aggregated trades via the Indexer.
- Integration examples — Code snippets for managing a subaccount's cross margin.
First Steps: Reading Data via the Indexer
Fetching the list of markets (REST)
No authentication is required for public data. Get the active trading pairs (e.g., `BTC-USD`):
curl -X GET "https://indexer.dydx.trade/v4/markets"
Subscribing to Trades over WebSocket
To receive real-time market data:
URL: `wss://indexer.dydx.trade/v4/ws`
{
"type": "subscribe",
"channel": "v4_markets"
}
Node.js: Basic Request to the Indexer API
An example using axios to fetch the current order book for the BTC-USD pair:
const axios = require('axios');
async function getOrderbook() {
try {
const response = await axios.get('https://indexer.dydx.trade/v4/orderbooks/perpetualMarket/BTC-USD');
console.log("Топ заявки Ask:", response.data.asks.slice(0, 5));
} catch (error) {
console.error("Ошибка API:", error.response ? error.response.data : error.message);
}
}
getOrderbook();
Key Endpoints Overview of the Indexer API
Public Market Data
- GET /v4/markets: Market status, price indices, tick size and lot step.
- GET /v4/orderbooks/perpetualMarket/{ticker}: Order book depth.
- GET /v4/candles/perpetualMarket/{ticker}: Historical candlestick data.
Account Data (Requires a Subaccount Address)
- GET /v4/addresses/{address}/subaccounts/{subaccountNumber}: Retrieve the balance, free margin and open positions of a specific subaccount.
Reminder: To send orders and manage your account (writing), you must use an SDK to broadcast Cosmos transactions (Tx) to validators, not the Indexer API.
Third-Party Integrations: Hummingbot
Market Making with Hummingbot
For algo traders who want to run market making without writing low-level code, Hummingbot ships a fully functional connector for dYdX v4 (dYdX Chain). You can configure the bot for Pure Market Making or Cross-Exchange Arbitrage. The Hummingbot connector already works with Cosmos transactions under the hood; all you need to do is feed it your subaccount's secret mnemonic through its secure interface.
Frequently Asked Questions (FAQ) about the dYdX API
What is the base URL of the dYdX Chain REST API?
The main URL for public requests (Indexer API) on Mainnet: https://indexer.dydx.trade. For WebSocket: wss://indexer.dydx.trade/v4/ws. Testnet: https://indexer.v4testnet.dydx.exchange.
Why are there no familiar API keys in dYdX v4?
Unlike CEXs and dYdX v3, dYdX v4 is a sovereign blockchain (a Cosmos App-Chain). Placing an order is a full-fledged blockchain transaction. You sign it locally with your subaccount's private key and send it to validator nodes (RPC), not to a centralized HTTP server.
How do I stay secure when trading via the API?
The key to your funds is the subaccount's mnemonic phrase (Secret Phrase). Store it in OS-level secret managers (.env) and never publish it on GitHub. It is recommended to create separate subaccounts with limited capital for each trading bot.