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.
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.
https://mcp.eterna.exchange/mcpThe 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.
| Layer | Responsibility | Concrete Implementation on Eterna |
|---|---|---|
| 1. Reasoning & Strategy | Interpret user intent, select setups, review trade logs | Claude, ChatGPT, Cursor, Gemini, or custom agent loop |
| 2. Protocol & Auth | Discover SDK methods, authenticate without static keys | Remote MCP (https://mcp.eterna.exchange/mcp) + OAuth 2.1 |
| 3. Deterministic Execution | Fetch ticks/TA, size position, attach TP/SL in 1 call | execute_code Deno sandbox + 30+ eterna.* SDK methods |
| 4. Liquidity & Custody | Order 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
- 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.
- 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.
- 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.
- 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.
- 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.
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,
};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.
# Explore SDK methods and run TypeScript trading strategies from your terminal
npx @eterna-hybrid-exchange/cli --helpCommon agent errors and exact fixes
Avoid the five most common mistakes coding agents make when wiring up crypto execution.
| Error / Failure Mode | Root Cause | Exact Fix |
|---|---|---|
| Unknown tool: register_agent | Agent 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 error | Raw 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 deposit | Deposited 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 symbol | Linear perpetual helpers are used on spot holdings. | Use market: 'spot' on placeOrder to buy spot and call eterna.sellSpotBalance(symbol) to exit spot holdings. |
Frequently asked questions
Do I need to know how to code to build an AI crypto trading agent?
Which programming language does Eterna MCP execute?
How do I prevent an AI trading agent from over-leveraging or losing my whole account?
Can I trade tokenized stocks and altcoins with an AI agent on Eterna?
References & verification links
- 30-Minute Walkthrough: Build Your AI Trading Agent with Eterna MCPStep-by-step no-code and developer walkthrough with video.
- Eterna MCP Tools ReferenceFull parameter and return documentation for all 30+ SDK methods.
- Eterna CLI on npmOfficial CLI for terminal strategy execution and SDK inspection.
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.