# dYdX API in Python: Indexer reads, node orders, limits

URL: https://fincodelabs.com/en/blog/dydx-api-python · Publisher: Fincode (Fincode Yazılım ve Teknoloji A.Ş.), Istanbul, Turkey · Category: Exchange APIs · Published: 2026-11-26 · Updated: 2026-11-26

dYdX API in Python, read 26 Nov 2026: v4 Indexer and node endpoints, tested read-only code, 100 requests per 10 s, block order limits and wallet signing.

**Short answer:** The **dYdX API in Python** has two parts: the v4 Indexer, a public HTTP and WebSocket service for reads that needs no key, and validator nodes, which accept orders signed by a mnemonic-derived wallet. The Python client the documentation installs is the PyPI package `dydx-v4-client` (1.1.6, 12 February 2026). As read on 26 November 2026, Indexer calls are limited to 100 per 10 seconds per IP, and orders are limited per block.

Many dYdX API tutorials still describe v3, which used API keys. dYdX v4 is its own blockchain: reads come from an Indexer, writes are signed transactions sent to a node, and there is no API key. Everything below comes from docs.dydx.xyz, PyPI, a GitHub advisory and the dYdX Trading Inc. terms, read on 26 November 2026, plus calls made that day to the public mainnet and testnet Indexers and node REST endpoints. No wallet was used, so order placement is described from the documentation, not run.

This is a technical guide, not a recommendation of dYdX, any market or any strategy. Perpetual futures are leveraged derivatives and carry a high risk of fast losses. Article 99/A of Capital Markets Law No. 6362 treats activity by foreign crypto-asset platforms directed at Turkish residents as unauthorized. The terms of dYdX Trading Inc. (updated 12 March 2026), which says it does not itself deploy the software for public use, also restrict persons in the United States, Canada and the United Kingdom from the dYdX perpetuals trading software; API access is not a way around those rules.

## dYdX v4 API basics: Indexer for reads, node for writes

A Python program reads data from the Indexer and sends signed order messages to a validator node; the two have different hosts and limits.

**Endpoints listed on docs.dydx.xyz, read 26 November 2026**

| Purpose | Mainnet | Testnet |
| --- | --- | --- |
| Indexer HTTP | `https://indexer.dydx.trade/v4` | `https://indexer.v4testnet.dydx.exchange` (paths under `/v4`) |
| Indexer WebSocket | `wss://indexer.dydx.trade/v4/ws` | `wss://indexer.v4testnet.dydx.exchange/v4/ws` |
| Node gRPC (OEGS) | `oegs.dydx.trade:443` | `oegs-testnet.dydx.exchange:443` |
| Faucet | None | `https://faucet.v4testnet.dydx.exchange` |

The page also lists node endpoints from named infrastructure operators, some limited to 300 or 350 requests a minute, without saying which dYdX runs or what service level any offers. Keep a second endpoint configured. Account reads such as `/v4/addresses/{address}` and `/v4/fills` need no signature either, so anyone who knows an address can read its positions. On 26 November 2026, mainnet `/v4/perpetualMarkets` returned 296 markets with statuses `ACTIVE` and `FINAL_SETTLEMENT`: filter by status before treating a market as tradable.

## dYdX Indexer API in Python: a tested read-only client

The Indexer needs no client library: this standard-library code reads block height, market parameters and the top of the book, and raises an error on each failure case in the table below.

```python
import json
import urllib.error
import urllib.parse
import urllib.request
from decimal import Decimal, InvalidOperation

INDEXER = {"mainnet": "https://indexer.dydx.trade/v4",
           "testnet": "https://indexer.v4testnet.dydx.exchange/v4"}

class IndexerError(Exception):
    pass

def get(net, path, **params):
    url = INDEXER[net] + path + ("?" + urllib.parse.urlencode(params) if params else "")
    req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
    try:
        with urllib.request.urlopen(req, timeout=10) as resp:
            body, left = resp.read(), resp.headers.get("RateLimit-Remaining")
    except urllib.error.HTTPError as e:
        raise IndexerError(f"HTTP {e.code} on {path}: {e.read()[:300].decode(errors='replace')}") from None
    except (urllib.error.URLError, TimeoutError) as e:
        raise IndexerError(f"network error on {path}: {e}") from None
    try:
        return json.loads(body), left
    except ValueError:
        raise IndexerError(f"non-JSON reply on {path}") from None

def dec(value, field):
    try:
        d = Decimal(str(value))
    except InvalidOperation:
        raise IndexerError(f"{field} is not a number: {value}") from None
    if not d.is_finite():
        raise IndexerError(f"{field} is not finite: {value}")
    return d

def market(net, ticker):
    if not ticker:
        raise ValueError("ticker is empty")
    found = get(net, "/perpetualMarkets", market=ticker)[0].get("markets") or {}
    if not (len(found) == 1 and ticker in found):
        raise IndexerError(f"expected only {ticker}, got {sorted(found)[:5]}")
    m = found[ticker]
    step = dec(m["stepBaseQuantums"], "stepBaseQuantums") * Decimal(10) ** int(m["atomicResolution"])
    if not step == dec(m["stepSize"], "stepSize"):
        raise IndexerError(f"stepSize {m['stepSize']} does not match quantums {step}")
    return m

def top_of_book(net, ticker):
    book, left = get(net, "/orderbooks/perpetualMarket/" + urllib.parse.quote(ticker))
    if not (book.get("bids") and book.get("asks")):
        raise IndexerError(f"{ticker}: one side of the book is empty")
    bid, ask = dec(book["bids"][0]["price"], "bid"), dec(book["asks"][0]["price"], "ask")
    if bid >= ask:
        raise IndexerError(f"{ticker}: crossed book {bid} >= {ask}")
    return bid, ask, left

if __name__ == "__main__":
    for net in INDEXER:
        h = get(net, "/height")[0]
        m = market(net, "BTC-USD")
        bid, ask, left = top_of_book(net, "BTC-USD")
        print(f"{net}: height {h['height']} at {h['time']}")
        print(f"  {m['ticker']} {m['status']} oracle {m['oraclePrice']} "
              f"tick {m['tickSize']} step {m['stepSize']}")
        print(f"  bid {bid} ask {ask} spread {ask - bid}; RateLimit-Remaining {left}")
```

Output on 26 November 2026 (Python 3.11, public endpoints, no key):

```
mainnet: height 115484983 at 2026-11-26T18:05:23.527Z
  BTC-USD ACTIVE oracle 60491.18515 tick 1 step 0.0001
  bid 60472 ask 60482 spread 10; RateLimit-Remaining 88
testnet: height 93822910 at 2026-11-26T18:05:24.362Z
  BTC-USD ACTIVE oracle 60469.93307 tick 1 step 0.0001
  bid 60437 ask 60497 spread 60; RateLimit-Remaining 97
```

**Failure cases run on 26 November 2026**

| Input | Result |
| --- | --- |
| Unknown ticker `NOPE-USD` | HTTP 400 with the Indexer's `errors` text, no `KeyError` |
| Empty ticker | `ValueError` before any request; sent anyway, `market=` returned HTTP 400, and a wrapper that drops empty parameters would get all markets |
| Two markets in the reply | Rejected, not the last one used silently |
| DNS failure; HTML reply | Network error; non-JSON error |
| `Infinity`, `NaN`, `abc`, `None` as a price | Rejected; `Decimal` keeps `1e400` finite where `float` gives `inf` |
| Empty or crossed book; wrong step size | Rejected |

On-chain sizes are integers called quantums: the live `stepBaseQuantums` (1,000,000) times 10 to the power of `atomicResolution` (-10) equals the displayed step of 0.0001, so the code stops if a response ever breaks that relationship instead of sizing orders from the wrong field. The remaining-request count is per IP, so other programs on the same server use it too.

## dYdX WebSocket API: subscribing to trades

The Indexer WebSocket sends a `connected` message, then a `subscribed` snapshot, then updates.

The documentation's subscribe example is `{"type": "subscribe", "channel": "v4_trades", "id": "BTC-USD", "batched": false}`. Sent with the `websockets` package (13.1) on 26 November 2026, it returned a snapshot of 1,000 BTC-USD trades covering about 18 hours, each with `id`, `side`, `size`, `price`, `type`, `createdAt` and `createdAtHeight`. No new trade arrived in the next 20 seconds: on a quiet market silence does not prove the connection died, so pair a timeout with the checks in [reconnect handling for trading WebSockets](https://fincodelabs.com/en/blog/websocket-heartbeat-reconnect). A misspelled channel returned `{"type":"error","message":"Invalid channel: v4_nosuch"}` on the open connection, so a reader loop must treat `error` messages as failures. The WebSocket reference read today does not document heartbeat rules.

## dYdX API rate limit: Indexer per IP, orders per block

The Indexer limits HTTP requests per IP, and the chain separately limits order messages per account over a number of blocks.

The rate limits page states 100 Indexer requests per 10 seconds per IP and WebSocket subscription caps per connection: 256 for the accounts channels, 32 each for candles, markets, orderbook and trades. Live headers on 26 November 2026 showed `ratelimit-limit: 100` and a `ratelimit-reset` in epoch milliseconds about 10 seconds ahead; the candles path showed `ratelimit-limit: 1000`, which the page does not mention. A [token bucket in Python](https://fincodelabs.com/en/blog/token-bucket-rate-limiter-python) keeps a client under the limit.

**Order rate limits: documentation example vs live nodes, 26 November 2026**

| Setting | Docs example | Live `/dydxprotocol/clob/block_rate` |
| --- | --- | --- |
| Stateful (long-term) placements | 2 per block and 20 per 100 blocks | 50 per 100 blocks |
| Short-term placements and cancels | 4,000 per 5 blocks | 4,000 per 5 blocks |

Four public REST nodes from three operators, on mainnet and testnet, returned the same live values, which differ from the documentation's example for stateful orders. The page says all limits can change and tells readers to query that endpoint, so read it at startup. Failed attempts count too, subaccounts share their account's limit, and an order must pass every configured limit. See also [rate limit errors across crypto exchange APIs](https://fincodelabs.com/en/blog/api-rate-limit-exceeded-crypto-exchanges).

## dYdX v4 signing: mnemonic, wallet and permissioned keys

Orders are transactions signed by a wallet derived from a 24-word mnemonic, and whoever holds the mnemonic controls the account and its funds.

The wallet setup page derives the address with `Wallet(KeyPair.from_mnemonic(mnemonic), 0, 0).address()`, then loads trading details with `await Wallet.from_mnemonic(node, mnemonic, address)`. It warns against sharing the mnemonic or committing it to a public repository such as GitHub; its sample reads it from a text file, which is not how a server should hold it.

For a bot, a permissioned key is the better option. The owner adds an authenticator combining, with `AllOf`, a `SignatureVerification` holding the bot's public key and, in the documentation's example, a `MessageFilter` allowing only `/dydxprotocol.clob.MsgPlaceOrder`, and can remove it at any time. The page does not say whether such a key is barred from transfers or withdrawals, so test that on testnet. The rules in [API key security for trading bots](https://fincodelabs.com/en/blog/api-key-security-trading-bots) apply more strongly here: a leaked mnemonic cannot be revoked like a key.

> **Supply chain check.** GitHub advisory GHSA-4f84-67cv-qrv3, published 6 February 2026, says `dydx-v4-client` 1.1.5.post1 on PyPI contained a highly obfuscated multi-stage loader that executes code on the host, likely to download and run further payloads. On 26 November 2026 PyPI listed 1.1.6 as the latest release. Pin an exact version with hashes, and keep code that can read a mnemonic away from casually installed tools.

## Placing dYdX orders from Python: what the docs require

An order needs a client ID, an order flag, the market's CLOB pair ID and an expiry in blocks or time; this part was not run because it needs a funded wallet.

**Order types in the trading guide, read 26 November 2026**

| Item | Short-term | Long-term (stateful) |
| --- | --- | --- |
| Order flag | `0` | `64` (conditional `32`, TWAP `128`) |
| Expiry | Good-til-block, at most height + 40 blocks | Good-til-block-time, at most 95 days |
| Rate limit | Per 5 blocks, with cancels | Per 100 blocks |

The documentation calls 40 blocks about 30 seconds. On mainnet on 26 November 2026, 149 blocks took 95.9 seconds, about 0.64 seconds each, so 40 blocks was nearer 26 seconds; derive expiry from the latest height, as the example's `await node.latest_block_height() + 10` does, before `node.place_order(wallet, order)`.

The order ID combines subaccount, a 32-bit client ID, flag and CLOB pair ID, and two orders cannot share a client ID. One documentation example draws it with `random.randint(0, 100000000)`; a restarted bot drawing random IDs can collide with an open order, so persist the [client order IDs](https://fincodelabs.com/en/blog/client-order-id) you issue. Broadcast is not fill: confirm through `/v4/orders` or the subaccounts channel, and handle [time-in-force](https://fincodelabs.com/en/blog/time-in-force) and expiry explicitly.

## dYdX testnet: what it proves and what it does not

The testnet runs the same Indexer API and order rules with faucet funds, so it tests signing, IDs and error handling, not fills or slippage.

Both networks returned the same BTC-USD tick and step, but spreads of 10 on mainnet and 60 on testnet in the run above, and 3,620 and 272 on testnet in other runs that day. The endpoints page notes that testnet funds work only there and that IBC relayers may be inactive on testnets. Read [how to test trading bots](https://fincodelabs.com/en/blog/how-to-test-trading-bots) and keep a [kill switch](https://fincodelabs.com/en/blog/trading-bot-kill-switch) that does not depend on the Indexer.

Fincode builds exchange connectors from rules a customer has written, as described on the [Fincode exchange API integration page](https://fincodelabs.com/en/services/exchange-api-integration); naming dYdX here does not mean Fincode integrates it or has built on it. Another on-chain venue is covered in the [Hyperliquid API Python guide](https://fincodelabs.com/en/blog/hyperliquid-api-python).

## Frequently asked questions

### Does the dYdX v4 API need an API key?

No. Indexer reads are public and orders are signed by a mnemonic-derived wallet, as read on docs.dydx.xyz on 26 November 2026. Permissioned keys give a bot a restricted signing key instead of the mnemonic.

### What is the dYdX Indexer API rate limit?

The documentation states 100 requests per 10 seconds per IP, matching live headers on 26 November 2026. The candles path returned a limit of 1000, which the documentation does not mention.

### Which Python package is the official dYdX v4 client?

dydx-v4-client on PyPI, the package the dYdX Python quick start installs; 1.1.6 was the latest on 26 November 2026. Version 1.1.5.post1 was malicious per GitHub advisory GHSA-4f84-67cv-qrv3, so pin versions.

### What is the dYdX testnet Indexer URL?

https://indexer.v4testnet.dydx.exchange for HTTP and wss://indexer.v4testnet.dydx.exchange/v4/ws for WebSocket, per the endpoints page read 26 November 2026.

## Sources

- [dYdX documentation: Connecting to dYdX (endpoints), read 26 November 2026](https://docs.dydx.xyz/interaction/endpoints)
- [dYdX documentation: Indexer HTTP API](https://docs.dydx.xyz/indexer-client/http)
- [dYdX documentation: Indexer WebSocket API](https://docs.dydx.xyz/indexer-client/websockets)
- [dYdX documentation: Rate limits](https://docs.dydx.xyz/concepts/trading/limits/rate-limits)
- [dYdX documentation: Quick start with Python](https://docs.dydx.xyz/interaction/client/quick-start-py)
- [dYdX documentation: Wallet setup](https://docs.dydx.xyz/interaction/wallet-setup)
- [dYdX documentation: Trading guide (order types, IDs, expiry)](https://docs.dydx.xyz/interaction/trading)
- [dYdX documentation: Permissioned keys](https://docs.dydx.xyz/interaction/permissioned-keys)
- [PyPI: dydx-v4-client release history](https://pypi.org/project/dydx-v4-client/)
- [GitHub Advisory GHSA-4f84-67cv-qrv3: malicious dydx-v4-client 1.1.5.post1](https://github.com/advisories/GHSA-4f84-67cv-qrv3)
- [dYdX Trading Inc.: v4 Terms of Use (last updated 12 March 2026)](https://dydx.exchange/v4-terms)

> This guide is general information about software and markets, not investment, legal or tax advice. Automated trading can lose money, past or backtested performance does not guarantee future results, and the rules that apply depend on your jurisdiction and your exchange's terms. Sources, checks and corrections: see the [editorial policy](https://fincodelabs.com/en/editorial-policy).

---

Published by Fincode (Fincode Yazılım ve Teknoloji A.Ş.), a software company in Istanbul, Turkey: https://fincodelabs.com/en/blog/dydx-api-python

Cite as: Fincode, "dYdX API in Python: Indexer reads, node orders, limits", updated November 26, 2026, https://fincodelabs.com/en/blog/dydx-api-python
