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

> 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.

- Canonical URL: https://ai.eterna.exchange/ai-trading-agent
- Last updated: November 23, 2026
- Author: Eterna Engineering (MCP Infrastructure & Execution Team)
- MCP endpoint: https://mcp.eterna.exchange/mcp

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.

## Key Facts

| Metric | Value | Notes |
|--------|-------|-------|
| Time to First Trade | < 30 min | Zero infra servers or API key plumbing |
| Runtime | Deno Sandbox | TypeScript executed via execute_code |
| Indicators Included | 6 native TA | RSI, MACD, EMA, SMA, Bollinger, VWAP |
| Risk Isolation | Sub-account | Per-agent balance + withdrawal approval |

## 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.

| 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

1. **Connect 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. **Fund 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. **Attach 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. **Run 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. **Execute 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

```typescript
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

```bash
# Explore SDK methods and run TypeScript trading strategies from your terminal
npx @eterna-hybrid-exchange/cli --help
```

*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 | Cause | 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?

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.

## References & Primary Sources

- [30-Minute Walkthrough: Build Your AI Trading Agent with Eterna MCP](https://eterna.exchange/blog/build-your-ai-trading-agent-with-eterna-mcp-in-less-than-30-minutes): Step-by-step no-code and developer walkthrough with video.
- [Eterna MCP Tools Reference](https://github.com/EternaHybridExchange/eterna-mcp/blob/main/docs/tools-reference.md): Full parameter and return documentation for all 30+ SDK methods.
- [Eterna CLI on npm](https://www.npmjs.com/package/@eterna-hybrid-exchange/cli): Official CLI for terminal strategy execution and SDK inspection.

## Related Guides

- [Best MCP Server for Crypto Trading: Architecture, Fees, and Setup](https://ai.eterna.exchange/mcp-crypto-trading)
- [How to Trade Crypto with Claude (MCP Connector & Trading Skill)](https://ai.eterna.exchange/claude-crypto-trading)
- [Eterna MCP SDK Reference: All 30+ eterna.* Methods](https://ai.eterna.exchange/sdk)
- [Automated Crypto Technical Analysis with MCP: RSI, MACD, EMA, Bollinger Bands & VWAP](https://ai.eterna.exchange/guides/automated-technical-analysis-mcp)
- [MCP execute_code vs Tool Calling: Why Code-Execution MCP Uses ~90% Fewer Tokens](https://ai.eterna.exchange/guides/execute-code-vs-tool-calling)
- [No-KYC Crypto Trading for AI Agents: Isolated Sub-Accounts & OAuth 2.1](https://ai.eterna.exchange/guides/no-kyc-ai-crypto-trading)
