Skip to main content
Glama
dydx-agent-gateway

dydx-agent-gateway

dYdX Agent Gateway

tests PyPI PyPI downloads MCP Catalog Python 3.11+ License: MIT

One MCP server, 22 read-only tools, and your agent suddenly reads dYdX v4 the way a desk analyst does: live funding, trader PnL it can actually trust, anomaly detectors, leaderboards. No API keys anywhere. The gateway signs nothing, stores nothing, and cannot move funds even if it wanted to.

Use cases

Copy-trading is where this pays off first. Before you follow anyone, trader_pnl_stats reconciles their equity curve against deposits and transfers; the residual tells you if the numbers are real. We built it after watching a "top trader of the week" who turned out to be down $1,271 all-time with a 77% drawdown.

Funding analytics: a heatmap ranked by |rate| with OI context on every row, realized 1h funding history, and detectors for the patterns that precede pain, like OI spiking while price goes flat, or the |Δprice|↑ + OI↓ cascade signature.

Discovery is on-chain, not scraped: block-scanned trader registry, funded-accounts probe, farmer-bot flags so you copy a trader and not a rewards farmer. One market_digest call gives you the day's events, funding extremes and the leaderboard top in a single response. When you're ready to enter, suggest_stops returns an ATR-based stop, take-profit, breakeven trigger and trailing level for your side.

Full walkthroughs with real outputs: examples/use-cases.md.

Related MCP server: Crypto Options Desk MCP

Install

Claude Code:

claude mcp add dydx -- uvx dydx-agent-gateway

Claude Desktop / Cursor / any mcp.json:

{"mcpServers": {"dydx": {
  "command": "uvx",
  "args": ["dydx-agent-gateway"]}}}
[mcp_servers.dydx]
command = "uvx"
args = ["dydx-agent-gateway"]
# 1) start the gateway (keep it running)
uvx dydx-agent-gateway --http --port 8901 &

# 2) register it (merges into ~/.zcode/cli/config.json; workspace .zcode/config.json works too)
python3 - <<'PY'
import json, os
p = os.path.expanduser("~/.zcode/cli/config.json")
os.makedirs(os.path.dirname(p), exist_ok=True)
cfg = json.load(open(p)) if os.path.exists(p) else {}
cfg.setdefault("mcp", {}).setdefault("servers", {})["dydx"] = {
    "type": "http", "url": "http://127.0.0.1:8901/mcp"}
json.dump(cfg, open(p, "w"), indent=2)
print("dydx MCP server registered:", p)
PY

# 3) copy the agent skill (tool guide + data gotchas)
git clone -q --depth 1 https://github.com/alekskram/dydx-agent-gateway /tmp/dag
cp -r /tmp/dag/.agents/skills/dydx-gateway ~/.zcode/skills/ && rm -rf /tmp/dag
echo "ZCode setup done, restart your session and call any dydx tool"

Plain Python:

pip install dydx-agent-gateway
python -c "from dydx_mcp import server; import json; print(json.dumps(server.market_digest(), default=str)[:400])"

Hosted (streamable HTTP): dydx-agent-gateway --http --port 8901, then any client:

{"mcpServers": {"dydx": {"type": "http", "url": "http://host:8901/mcp"}}}

Requires Python ≥ 3.11. Deps (fastmcp, pycryptodome, ecdsa) install automatically. See examples/ for ready-made configs and a working autonomous agent script.

Tools (22 — read-only, keyless)

Group

Tools

Market data

list_markets, market_detail, candles, recent_trades, height, historical_funding

Analytics

funding_heatmap, market_ta, suggest_stops, cvd, correlation

Traders

trader_profile, trader_pnl_stats, fills_review, raw_fills

Discovery

discover_traders, leaderboard, list_traders, registry_stats

Signals

latest_events (funding extremes, OI spikes, liquidation cascades, equity jumps)

Briefing

market_digest: one call with events + funding + leaderboard top. Start here.

Meta

usage_stats: tool-call counters (traction/uptime of your instance)

Real outputs of every tool: examples/tool-output.md.

Solving real trader problems, five scenarios with live data: examples/use-cases.md.

What makes it different

PnL you can audit. trader_pnl_stats reconciles the identity equity-Δ = Δpnl + ΣnetTransfers on every account; when the residual is not zero, the numbers lie, and the tool says so instead of averaging the lie away. We ran it against real accounts and the residual lands at $0.0000. Deposit-adjusted maxDD, day-winrate and a sharpe-like ratio come out of the same pass.

Detectors instead of dashboards. Funding extremes, OI spikes without price, equity jumps, and the liquidation-cascade signature (|Δprice|↑ + OI↓). Live catches sit in reports/.

The rest is analyst gear: realized funding history, CVD from the trades tape, cross-market correlation with beta, raw fills for execution review, MACD/VWAP/realized-vol enrichments, sortino-like downside risk.

And a habit of writing down what bites. Five indexer gotchas that silently corrupt naive analytics are documented in .agents/skills/dydx-gateway/references/data-gotchas.md; 129 tests (now 133) run in CI on 3.11 and 3.13.

Why a gateway and not the raw indexer API?

Point an agent at indexer.dydx.trade directly and see how far it gets before the fun starts:

Raw indexer gives you

You would have to build

paginated endpoints (≤1000/req)

per-endpoint pagination logic

a funding endpoint that intermittently returns EMPTY or rpc-times out

retry + cached-series fallback

per-bucket (non-cumulative) netTransfers, newest-first PnL, an unreliable priceChange24H field

reconciliation math; this gateway verifies equity-Δ = Δpnl + ΣnetTransfers per account (phantom-PnL detection)

raw candles and trades

detectors (funding extremes, OI spikes, cascade signature), a TA pack (RSI/MACD/ATR/Bollinger/VWAP), CVD, correlation, ATR stop plans

address strings in blocks

a validated bech32 trader registry with farmer-bot flags and a verified leaderboard

The five documented indexer gotchas: .agents/skills/dydx-gateway/references/data-gotchas.md.

Data notes

Indicators are computed over the current candle window and move with every new bar. nextFundingRate is the exchange's live preview, recomputed continuously; volume24H rolls. Two calls a minute apart will legitimately differ, and that is not a bug.

Safety model

Every tool is read-only and keyless. The gateway signs nothing and holds no credentials. An offline-tested EIP-712 signer stays in dydx_mcp/signer.py as a library for anyone building their own execution layer; it is wired to no MCP tool.

FAQ

  • Does it trade? No, analytics only. That was the design brief.

  • API keys? None. Public indexer endpoints.

  • Rate limits? No auth; a 60s markets cache keeps the traffic polite.

  • How do I vet a trader before copying? trader_profile, then trader_pnl_stats, then fills_review. Check the identity residual and the maker/taker mix before anything else.

Part of the suite

Four sibling read-only MCP gateways, one style: keyless, cached, honest degradation.

Gateway

Focus

dydx-agent-gateway (you are here)

dYdX v4: verified trader PnL, funding/OI anomaly detectors, leaderboard

arcus-agent-gateway

194 tokenized US equities on Robinhood Chain: quotes, holders, whale transfers

hyperliquid-agent-gateway

Hyperliquid: 233 perps + spot, funding carry, account risk, HyperEVM

aster-agent-gateway

Aster DEX: ~580 futures incl. 24/7 TradFi perps, funding caps/floors

All four are on glama.ai and PyPI; any of them installs with uvx <name>.

License

MIT. Not affiliated with dYdX Trading Inc.

Available Tools

22 tools
candlesCandlesA
Read-only

OHLCV candles with open interest for a market. resolution: 1MIN|5MIN|15MIN|30MIN|1HOUR|4HOURS|1DAY. Each candle: startedAt, open/high/low/close (price), baseTokenVolume (base-coin size), usdVolume (USD), startingOpenInterest. Rows are ordered oldest -> newest (the indexer sends newest-first; we normalize). limit is capped at 1000. Example: candles(ticker="ETH-USD", resolution="1HOUR", limit=100)

Inputs: ticker (required), limit, resolution.

correlationCorrelationA
Read-only

Pearson correlation of two markets' log returns over candles: r in [-1, 1] plus beta(a|b) — the sensitivity of a to b (a moves beta x b's move, both in log space). Candle series are JOINED by startedAt (only candles with the same timestamp on both sides are compared), so partially-overlapping histories pair correctly. Both tickers are validated; call list_markets for the valid set (format: 'ETH-USD'). Returns {"error": ...} when there is insufficient or constant data. Example: correlation(ticker_a="BTC-USD", ticker_b="ETH-USD")

Inputs: ticker_a (required), ticker_b (required), limit, resolution. Returns: object

cvdCvdA
Read-only

Cumulative Volume Delta from the latest public trades: running sum of +size on BUY / -size on SELL, oldest -> newest within the sample. Rising CVD = aggressive buying dominating. Volumes are in the base coin. Returns cvd_final (net aggressive flow), buy_volume / sell_volume, trade window bounds (t_first / t_last), trades_sampled and cvd_series_last (the last 50 running values — full series stays out of the response to keep it compact). An unknown or delisted ticker raises an error (MCP isError) — call list_markets for the valid set (format: 'ETH-USD'). Example: cvd(ticker="BTC-USD", trades_limit=500)

Inputs: ticker (required), trades_limit. Returns: object

discover_tradersDiscover TradersA
Read-only

Screener: funded, recently active traders discovered from the chain — registry candidates probed for live equity. Start here, then analyze each with trader_profile. Each row: address, equity (USD, >= min_equity), registry_hits, last_seen. Example: discover_traders(limit=5, min_equity=100.0)

Inputs: limit, min_equity. Returns: result

fills_reviewFills ReviewA
Read-only

Execution review from the latest fills: maker/taker split, per-market distribution, traded volume, avg fill size. (Per-fill PnL is not exposed by the indexer; use trader_pnl_stats for win-rate.) Key fields: fills_sampled (count), maker_share_pct (0-100), sampled_volume_USD, avg_fill_USD, top_markets (top 5 by fill count). Returns {"summary": "no fills"} for accounts with no fills. Example: fills_review(address="dydx1m9hg73dtn5ku8ulmj8rjmdqh0hk7uuhawc69cn")

Inputs: address (required), limit, subaccount. Returns: object

funding_heatmapFunding HeatmapA
Read-only

All markets ranked by |next funding rate| (1h, annualized). Shows which sides pay: positive = longs pay shorts. Rows carry OI so agents can ignore micro-markets; raise min_oi_usd to filter noise. Each row: ticker, funding_pct_1h (pct per hour), funding_pct_annualized (1h rate x 24 x 365), oi_usd, oraclePrice, and exactly one of longs_pay / shorts_pay = True. Zero-rate markets and markets below min_oi_usd are skipped. Returns {"count_nonzero", "top", "summary", "offset", "has_more"} — page with offset when has_more is true. Example: funding_heatmap(limit=15, min_oi_usd=100000.0)

Inputs: limit, offset, min_oi_usd. Returns: object

heightHeightA
Read-onlyIdempotent

Current dYdX chain height and time — use for liveness checks. Returns {"height": current block number, "time": block timestamp}. Example: height()

Inputs: no named parameters. Returns: object

historical_fundingHistorical FundingA
Read-only

Raw 1h funding rate history of a market (as realized, not the next-rate preview in market_detail): each point is the rate actually paid that hour; annualized_pct = rate x 24 x 365 for scale. Default 168 points = 7 days. Points are ordered oldest -> newest (candles convention); limit capped at 500. Positive = longs paid shorts. An unknown or delisted ticker raises an error (MCP isError) — call list_markets for the valid set (format: 'ETH-USD'). Example: historical_funding(ticker="ETH-USD", limit=168)

Inputs: ticker (required), limit. Returns: object

latest_eventsLatest EventsA
Read-onlyIdempotent

Latest anomaly events from our detectors: funding_extreme, oi_spike_no_price, equity_jump, liq_cascade_signature. Each row: ts, kind, subject (ticker or address) and payload (dict of detector numbers). Optional kind filter; offset pages past the newest slice (events are pruned at 5000 — offset+limit beyond that returns []). Subscribe via webhooks/Telegram (alerts). Example: latest_events(limit=20, kind="funding_extreme")

Inputs: kind, limit, offset. Returns: result

leaderboardLeaderboardA
Read-only

Verified trader leaderboard from our registry + PnL engine (batch-computed). metric: pnl_window | pnl_total | equity | day_winrate. Farmer flags mark likely rewards-farming bots (heuristic v0). Each row (USD where monetary): address, equity, pnl_total, pnl_window, day_winrate (pct 0-100), max_dd (pct), maker_share, avg_fill, farmer_flag (bool), identity_residual. Requires a batch run — otherwise returns {"error": "no leaderboard run yet — run leaderboard.py first"}. Example: leaderboard(limit=20, metric="pnl_window")

Inputs: limit, metric, offset. Returns: object

list_marketsList MarketsA
Read-only

All dYdX v4 perpetual markets: oracle price, 24h volume, open interest, next funding rate. Sorted by 24h USD volume by default (or 'oi'). Each row: ticker, oraclePrice, volume24h_USD, openInterest_USD (size x oracle price) and nextFundingRate_pct_1h (pct per hour). Returns {"count_total", "count", "offset", "has_more", "next_offset", "markets", "summary"}; only ACTIVE markets — delisted/settled ones are excluded. Page with offset when has_more is true. Example: list_markets(limit=20, sort="volume")

Inputs: sort, limit, offset. Returns: object

list_tradersList TradersA
Read-only

Recently active trader addresses from the block-scanner registry (high-frequency validator committers filtered out by max_hits). Each row: address, hits (chain appearances), first_seen / last_seen, last_height. Returns {"total", "count", "offset", "has_more", "next_offset", "traders"}; traders == [] when the registry is not built on this host. Page with offset when has_more is true. Feed an address into trader_profile / trader_pnl_stats next. Example: list_traders(limit=10, max_hits=100)

Inputs: limit, offset, max_hits. Returns: object

market_detailMarket DetailA
Read-only

One perpetual market in depth: prices, 24h stats computed from candles (the raw API priceChange field is unreliable), OI, funding. Returns oraclePrice, openInterest, nextFundingRate_pct_1h (pct/hour), volume24h_USD, change24h_pct_from_candles (24h pct change, computed from 25 x 1h candles), trades24h, basis_pct (mark-vs-oracle deviation in pct: (last candle close - oraclePrice) / oraclePrice x 100), and the latest three 1h candles (t/open/close/usdVolume). An unknown or delisted ticker raises an error (MCP isError) — settled markets are not served. Example: market_detail(ticker="BTC-USD")

Inputs: ticker (required). Returns: object

market_digestMarket DigestA
Read-onlyIdempotent

One-call market briefing: latest detector events + funding extremes (liquid markets only) + verified leaderboard top. The daily briefing an agent (or human) needs before anything else. Returns: events (up to 5, payload flattened into each row), funding (top-5 funding rows, markets with >= $100k OI) and leaderboard_top (top-3 by pnl_window: address, pnl_window, equity, day_winrate). Example: market_digest()

Inputs: no named parameters. Returns: object

market_taMarket TaA
Read-only

Technical snapshot computed from dYdX candles: RSI(14), EMA20/EMA50 trend, ATR(14) volatility, Bollinger(20,2) position, MACD(12,26,9), VWAP(20) and annualized realized vol. Pure local math — no external TA library. Key fields: price, trend_ema20_50 ("up"/"down"), rsi14 (0-100) and rsi_zone (overbought >70 / oversold <30 / neutral), atr14 (absolute) and atr_pct_of_price (pct), bollinger_pctB (0 = lower band, 1 = upper band), macd_line/signal_line/macd_hist (classic 12/26/9; hist > 0 = bullish momentum), vwap_20 (volume-weighted average price over the last 20 candles: typical price (H+L+C)/3 weighted by usdVolume) and realized_vol_annualized_pct (population std of log returns x sqrt(candles-per-year), scaled by resolution). Needs >=55 candles; returns {"error": ...} for thin markets. Example: market_ta(ticker="BTC-USD", resolution="1HOUR")

Inputs: ticker (required), resolution. Returns: object

raw_fillsRaw FillsA
Read-only

Raw execution tape for a subaccount — every field the indexer gives, unchanged — for agents doing their own execution-quality math (the aggregated view lives in fills_review). Each fill: t (createdAt), market, side, liquidity (MAKER/TAKER), type, price, size (base coin), usd_notional (price x size), fee, and the position context (positionSideBefore / positionSizeBefore / entryPriceBefore). Newest first; limit capped at 1000. Addresses come from discover_traders / leaderboard / list_traders. Example: raw_fills(address="dydx1m9hg73dtn5ku8ulmj8rjmdqh0hk7uuhawc69cn")

Inputs: address (required), limit, subaccount. Returns: object

recent_tradesRecent TradesA
Read-only

Latest public trades of a market (price, side, size, type, time). Newest first; limit capped at 100. side is BUY/SELL, size in base coin. Example: recent_trades(ticker="BTC-USD", limit=30)

Inputs: ticker (required), limit.

registry_statsRegistry StatsA
Read-onlyIdempotent

Live stats of our on-chain address registry (block scanner): how many active addresses collected, scan height, freshness. Returns addresses_total, scanned_up_to_height (last ingested dYdX block), seen_last_24h (addresses seen in the last 24h) and the sqlite path. On hosts where the optional scanner has not run, returns a note instead — market/trader tools still work via the public indexer. Example: registry_stats()

Inputs: no named parameters. Returns: object

suggest_stopsSuggest StopsA
Read-only

ATR-based risk plan: stop-loss, take-profit, breakeven trigger and trailing level for a long/short entry. Agent-managed position helper. Unknown ticker (no oracle price) raises an error (MCP isError); returns {"error": ...} when no ATR is available (thin market). All output prices are in market price units: stop_loss / take_profit sit atr_mult_sl / atr_mult_tp x ATR(14) from entry (entry defaults to the current oracle price); breakeven_after is the price at +1 ATR in profit (then move SL to entry and trail by 1 ATR); risk_reward = TP distance / SL distance. Example: suggest_stops(ticker="BTC-USD", side="LONG", atr_mult_sl=1.5)

Inputs: side (required), ticker (required), entry, resolution, +2 more. Returns: object

trader_pnl_statsTrader Pnl StatsA
Read-only

Deep PnL statistics from the equity curve: daily PnL, day-winrate, max drawdown (deposit-adjusted), Sharpe-like daily ratio, and the data-accuracy reconciliation residual (phantom-PnL detector). NOTE: pass limit as keyword: trader_pnl_stats(addr, limit=500), NOT positionally (second positional arg is subaccountNumber). Key fields: day_winrate_pct (0-100), max_drawdown_pct (pct, net of deposits/withdrawals) with max_drawdown_usd (same drawdown in USD) and dd_pct_unreliable (true when the deposit-adjusted peak at the worst drawdown was near zero — trust the USD figure then), avg_daily_pnl / best_day / worst_day (USD per UTC day), sharpe_like_daily, identity_max_residual_usd (expect < $1 on clean data). limit: history depth in points — 1000 ≈ 42 days (default, fast), 5000 ≈ 7 months (slower, multi-page fetch). Example: trader_pnl_stats(address="dydx1m9hg73dtn5ku8ulmj8rjmdqh0hk7uuhawc69cn", limit=5000)

Inputs: address (required), limit, subaccount. Returns: object

trader_profileTrader ProfileA
Read-only

Snapshot of any trader's subaccount: equity, open positions, and PnL curve statistics (all-time window from up to 1000 history points). Returns equity_now / totalPnl_now / totalPnl_delta_window (USD), window_start / window_end, and open_positions (market, side, size, entry, unrealizedPnl in USD). Pair with trader_pnl_stats for deeper statistics. Example: trader_profile(address="dydx1m9hg73dtn5ku8ulmj8rjmdqh0hk7uuhawc69cn")

Inputs: address (required), subaccount. Returns: object

usage_statsUsage StatsA
Read-onlyIdempotent

Tool-call counters since deployment (traction/uptime metrics). Returns calls_total, calls_24h, calls_7d and top_tools (top-5 (tool, count) pairs) recorded by this gateway instance. Example: usage_stats()

Inputs: no named parameters. Returns: object

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4/5.0

    Scored across 22 tools

    Disambiguation4/5

    Most tools target distinct data categories—market stats, candles, trades, funding, trader PnL, fills, alerts, and health—so an agent can usually pick the right one. A few pairs like trader_profile vs trader_pnl_stats and list_markets vs market_detail could be initially confused, but the detailed descriptions largely prevent misselection.

    Naming Consistency4/5

    All tool names use lowercase snake_case and are readable, with helpful prefixes like market_, trader_, and list_. However, the set mixes verb-led names such as suggest_stops and discover_traders with noun-style names like candles, height, and cvd, so no single naming pattern is maintained.

    Tool Count3/5

    At 22 tools, the server is borderline heavy and spans several subdomains—market data, trader analytics, alerts, registry health, and usage stats. Each tool seems purposeful, but the number is enough that an agent must scan many options before selecting.

    Completeness4/5

    The tool surface covers market data, funding, technical analysis, trader discovery, PnL, fills, alerts, and system health, which is strong for a read-only analytics gateway. Minor gaps like order-book depth and historical per-market PnL or positions exist, but they do not block core workflows.

    Maintenance

    ActivityStale
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      B
      quality
      B
      maintenance
      Multi-DEX perpetual futures trading MCP server (Pacifica, Hyperliquid, Lighter). 18 tools for market data, trade execution with dry-run safety, funding rate arbitrage, and portfolio analytics.
      31
      582 npm
      44
      MIT
    • A
      license
      B
      quality
      C
      maintenance
      An MCP server that gives an LLM agent a typed, audited tool surface over quant crypto-options desk analytics: gamma exposure, vanna, skew, vol surface, options flow, technicals, portfolio greeks, scenario analysis, and live positions.
      22
      2
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      Read-only crypto perps microstructure for AI agents: normalized cross-exchange market state (funding + multi-year percentile, OI, volume, CVD, order-book imbalance, liquidations, basis), OHLCV, 15-min state history, and measured conditional outcomes (historical base rates, not predictions) — 6 assets across Binance, Bybit, OKX and Hyperliquid, every metric with self-declared coverage and freshness
      MIT
    • A
      license
      Not graded
      quality
      B
      maintenance
      Enables real-time optimization of Uniswap v3/v4 concentrated liquidity ticks by balancing fee APY against impermanent loss under asset volatility, alongside L2 orderbook imbalance metrics, triangular arbitrage detection, and Bayesian portfolio rebalancing via MCP.
      7
      MIT