Builder Guide

How to Build an AI Crypto Trading Agent with MCP (Step-by-Step)

You do not need to maintain exchange WebSockets, sign HMAC requests, or debug rate-limit retries to ship a real AI trading agent. This guide covers the full architecture, runnable TypeScript code, risk rules, and failure handling.

Updated: By Eterna Engineering (MCP Infrastructure & Execution Team)Read as Markdown
Direct answer: How do you build an AI crypto trading agent in 2026?

Build an AI crypto trading agent in four layers: (1) an LLM planner (Claude, GPT, or Gemini), (2) a remote MCP execution server (https://mcp.eterna.exchange/mcp) using OAuth 2.1 and isolated sub-accounts, (3) deterministic TypeScript strategy logic running inside execute_code with built-in indicators (RSI, EMA, MACD, VWAP), and (4) hard risk guardrails including fixed position sizing, leverage caps, and mandatory stop-losses.

Time to First Trade< 30 minZero infra servers or API key plumbing
RuntimeDeno SandboxTypeScript executed via execute_code
Indicators Included6 native TARSI, MACD, EMA, SMA, Bollinger, VWAP
Risk IsolationSub-accountPer-agent balance + withdrawal approval
https://mcp.eterna.exchange/mcp

The 4-layer architecture of a reliable AI trading agent

Separate probabilistic LLM reasoning from deterministic order math. Let the LLM choose hypotheses and write TypeScript; let the sandbox enforce exact sizing and stops.

The most common reason DIY AI trading bots blow up accounts is asking an LLM to do floating-point position sizing in natural language across five separate tool calls. Prices move between turns, quantities violate exchange step sizes, and forgotten stop-losses leave positions naked.

A production agent splits responsibilities cleanly: the LLM reads market context and generates deterministic TypeScript code; Eterna's Deno sandbox fetches live market data, checks account equity, calculates exact contract quantity from risk percentage, validates instrument rules via eterna.getInstruments, and submits the order with stop-loss and take-profit atomically.

4-layer AI crypto trading agent architecture
LayerResponsibilityConcrete Implementation on Eterna
1. Reasoning & StrategyInterpret user intent, select setups, review trade logsClaude, ChatGPT, Cursor, Gemini, or custom agent loop
2. Protocol & AuthDiscover SDK methods, authenticate without static keysRemote MCP (https://mcp.eterna.exchange/mcp) + OAuth 2.1
3. Deterministic ExecutionFetch ticks/TA, size position, attach TP/SL in 1 callexecute_code Deno sandbox + 30+ eterna.* SDK methods
4. Liquidity & CustodyOrder matching, margin isolation, withdrawal security$10B+ USDT order books, isolated sub-account, approved withdrawals

Step-by-step: Build and deploy your first AI trading agent

  1. 01Connect your AI client or CLI to Eterna MCP

    Add https://mcp.eterna.exchange/mcp in Claude, Cursor, or ChatGPT, or install the terminal CLI with npx @eterna-hybrid-exchange/cli. Complete OAuth sign-in to auto-provision your isolated sub-account.

  2. 02Fund the isolated agent wallet

    Query eterna.getAllowedDepositCoins and eterna.getDepositAddress to get a deposit address for USDT (or another supported coin, then convert with eterna.swapToUsdt). Move funds into the trading wallet with eterna.transferToTrading.

  3. 03Attach explicit risk rules in your system prompt or skill

    Define hard invariants: max risk per trade (for example 1% of account equity), maximum leverage (for example 3x to 5x), maximum concurrent open positions, and mandatory stop-loss on every entry. Install Eterna's Claude trading skill bundle from ai.eterna.exchange/claude-skills as a baseline.

  4. 04Run multi-indicator screening inside one execute_code script

    Instead of calling one market per message, scan a watchlist (BTCUSDT, ETHUSDT, SOLUSDT, AVAXUSDT) in parallel using Promise.all inside execute_code and return only ranked candidates.

  5. 05Execute with automated position sizing and stop-loss

    Fetch instrument tick/step size with eterna.getInstruments, calculate quantity from your risk budget divided by stop distance, set leverage with eterna.setLeverage, and submit via eterna.placeOrder with stopLoss and takeProfit.

Complete runnable strategy: Risk-sized trend-pullback agent script

This single execute_code script screens BTC, ETH, and SOL using EMA trend alignment + RSI pullback, sizes the position to 1% equity risk, and places an order with hard TP/SL.

execute_code / risk-sized-pullback-agent.ts
const watchlist = ["BTCUSDT", "ETHUSDT", "SOLUSDT"];
const maxRiskPct = 0.01; // 1% account equity risk per trade
const maxLeverage = 3;

const [balance, openPositions] = await Promise.all([
  eterna.getBalance(),
  eterna.getPositions(),
]);

if (openPositions.length >= 2) {
  return { action: "hold", reason: "Max concurrent positions (2) reached", openCount: openPositions.length };
}

const equity = Number(balance.totalEquity ?? balance.availableBalance ?? 0);
if (equity < 20) {
  return { action: "hold", reason: "Insufficient equity for strategy minimum", equity };
}

const scans = await Promise.all(
  watchlist.map(async (symbol) => {
    const [tickers, ema20, ema50, rsi14] = await Promise.all([
      eterna.getTickers({ symbol }),
      eterna.getEma({ symbol, interval: "1h", period: 20 }),
      eterna.getEma({ symbol, interval: "1h", period: 50 }),
      eterna.getRsi({ symbol, interval: "1h", period: 14 }),
    ]);
    const price = Number(tickers[0]?.lastPrice ?? 0);
    const e20 = Number(ema20.value ?? 0);
    const e50 = Number(ema50.value ?? 0);
    const rsi = Number(rsi14.value ?? 50);
    const bullishPullback = price > e50 && e20 > e50 && rsi >= 32 && rsi <= 45;
    return { symbol, price, e20, e50, rsi, bullishPullback };
  }),
);

const candidate = scans.find((s) => s.bullishPullback);
if (!candidate) {
  return { action: "scan_only", reason: "No bullish pullback setup", scans };
}

const instruments = await eterna.getInstruments({ symbol: candidate.symbol });
const step = Number(instruments[0]?.lotSizeFilter?.qtyStep ?? 0.001);
const minQty = Number(instruments[0]?.lotSizeFilter?.minOrderQty ?? step);

const stopPrice = candidate.price * 0.985; // 1.5% stop
const takeProfitPrice = candidate.price * 1.03; // 3.0% target (2R)
const riskUsd = equity * maxRiskPct;
const rawQty = riskUsd / (candidate.price - stopPrice);
const qty = Math.max(minQty, Math.floor(rawQty / step) * step);

await eterna.setLeverage({ symbol: candidate.symbol, leverage: maxLeverage });
const order = await eterna.placeOrder({
  symbol: candidate.symbol,
  side: "Buy",
  orderType: "Market",
  qty: qty.toFixed(6).replace(/\.?0+$/, ""),
  stopLoss: stopPrice.toFixed(2),
  takeProfit: takeProfitPrice.toFixed(2),
});

return {
  action: "entered_long",
  symbol: candidate.symbol,
  entryRef: candidate.price,
  qty,
  riskUsd: Number(riskUsd.toFixed(2)),
  stopPrice: Number(stopPrice.toFixed(2)),
  takeProfitPrice: Number(takeProfitPrice.toFixed(2)),
  order,
};
Returns: Returns a deterministic audit object showing either scan_only with all indicator readings or entered_long with exact qty, USD risk, stop/target prices, and exchange order receipt.

Running strategies from the terminal with Eterna CLI

Developers who want repeatable scripts, CI checks, or local terminal workflows can pair the MCP server with the official Eterna CLI.

terminal / eterna-cli.sh
# Explore SDK methods and run TypeScript trading strategies from your terminal
npx @eterna-hybrid-exchange/cli --help
Note: Published on npm as @eterna-hybrid-exchange/cli. Uses the same eterna.* SDK mental model as MCP execute_code.

Common agent errors and exact fixes

Avoid the five most common mistakes coding agents make when wiring up crypto execution.

Error messages, root causes, and exact fixes
Error / Failure ModeRoot CauseExact Fix
Unknown tool: register_agentAgent hallucinates an account-registration tool before trading.Remove the call. Eterna has only 3 MCP tools (search_sdk, search_examples, execute_code). Sub-accounts are created automatically during OAuth 2.1 sign-in.
Method called as top-level MCP tool (e.g. placeOrder)Agent expects every SDK method to be registered as an individual MCP tool.Wrap eterna.placeOrder(...) inside execute_code TypeScript instead of calling it directly as an MCP tool.
Invalid quantity / qty step errorRaw floating-point qty does not match the symbol's lotSizeFilter.qtyStep or minOrderQty.Query eterna.getInstruments({ symbol }) inside the same execute_code script and floor qty to a multiple of qtyStep.
Insufficient balance after depositDeposited funds sit in the funding wallet until moved to the trading wallet.Call eterna.transferToTrading({ coin: 'USDT', amount }) before submitting orders. Convert non-USDT deposits first with eterna.swapToUsdt.
Calling closePosition or setLeverage on a spot symbolLinear perpetual helpers are used on spot holdings.Use market: 'spot' on placeOrder to buy spot and call eterna.sellSpotBalance(symbol) to exit spot holdings.
FAQ

Frequently asked questions

Do I need to know how to code to build an AI crypto trading agent?
No. With Claude or ChatGPT connected to Eterna MCP and the Eterna Trading Skill installed, you describe your strategy and risk limits in plain English. The LLM writes and runs the TypeScript execute_code script on your behalf, and you approve every execution.
Which programming language does Eterna MCP execute?
Eterna's execute_code sandbox runs TypeScript inside an isolated Deno runtime with the typed eterna.* SDK preloaded. You do not need to install npm packages or manage local Node or Python environments.
How do I prevent an AI trading agent from over-leveraging or losing my whole account?
Use three layers of defense: (1) fund only the isolated agent sub-account with capital you allocate to the strategy, (2) hard-code risk percentage, max leverage, and mandatory stopLoss parameters in your strategy prompt/skill, and (3) rely on Eterna's withdrawal approval gate so funds cannot leave automatically.
Can I trade tokenized stocks and altcoins with an AI agent on Eterna?
Yes. Eterna lists 800+ USDT perpetual futures pairs including BTC and ETH (up to 150x), SOL and XRP (up to 100x), major DeFi and meme coins, and tokenized equity perpetuals (such as NVDA, TSLA, AAPL, MSFT, COIN, MSTR), plus 380+ USDT spot pairs.
Primary Sources

References & verification links

Start Trading via MCP

Connect your AI agent in 30 seconds

One remote MCP URL. 800+ USDT perpetuals, 380+ spot pairs, 0.014% maker / 0.035% taker, no KYC.

View on GitHub