AI trading agents executed over $44 billion in notional volume across prediction and DeFi markets in 2025, and agent capabilities are improving roughly fourfold year-over-year. This guide shows you how to build an ai trading agent crypto developers can actually deploy: an LLM-powered agent that takes natural language instructions, fetches real-time swap quotes from swapapi.dev, and returns executable transaction data -- all without API keys, paid tiers, or complex authentication flows.
You will wire up OpenAI function calling (or Claude tool use) so your agent can autonomously quote and prepare token swaps across 46 EVM chains with a single GET request.
What You Will Need
Before writing any code, make sure you have these dependencies ready:
-
Python 3.10+ with
requestsandopenai(oranthropic) installed - A wallet address on any supported EVM chain (for quoting -- no private key needed for quotes)
- An OpenAI or Anthropic API key for the LLM layer
pip install openai requests web3
No swapapi.dev API key is required. The API is free, unauthenticated, and rate-limited to approximately 30 requests per minute per IP.
Step 1: Define the Swap Tool for Your LLM
Function calling lets the LLM decide when to invoke an external tool and what arguments to pass. 93% of IT executives are exploring agentic AI, and tool-use is the mechanism that turns a chatbot into an agent.
Define a tool schema that maps directly to the swapapi.dev endpoint:
swap_tool = {
"type": "function",
"function": {
"name": "get_swap_quote",
"description": "Get a DEX swap quote with executable calldata",
"parameters": {
"type": "object",
"properties": {
"chain_id": {
"type": "integer",
"description": "EVM chain ID (1=Ethereum, 42161=Arbitrum, 8453=Base)"
},
"token_in": {
"type": "string",
"description": "Input token contract address"
},
"token_out": {
"type": "string",
"description": "Output token contract address"
},
"amount": {
"type": "string",
"description": "Amount in smallest unit (wei for ETH)"
},
"sender": {
"type": "string",
"description": "Wallet address that will execute the swap"
}
},
"required": ["chain_id", "token_in", "token_out", "amount", "sender"]
}
}
}
The amount field takes raw units -- 1 ETH is "1000000000000000000" (18 decimals), while 100 USDC is "100000000" (6 decimals). Your agent needs to know token decimals to construct correct amounts.
Step 2: Implement the Swap Function
This function calls the swapapi.dev API and returns structured data that the LLM can interpret and present to the user. The API returns everything needed to execute the swap on-chain, including the transaction calldata and recommended RPC endpoints.
import requests
def get_swap_quote(chain_id, token_in, token_out, amount, sender):
url = f"https://api.swapapi.dev/v1/swap/{chain_id}"
params = {
"tokenIn": token_in,
"tokenOut": token_out,
"amount": amount,
"sender": sender,
}
resp = requests.get(url, params=params, timeout=15)
data = resp.json()
if not data.get("success"):
return {"error": data.get("error", {}).get("message", "Unknown error")}
status = data["data"]["status"]
if status == "NoRoute":
return {"status": "NoRoute", "message": "No swap route found"}
result = {
"status": status,
"token_in": data["data"]["tokenFrom"]["symbol"],
"token_out": data["data"]["tokenTo"]["symbol"],
"amount_in": data["data"]["amountIn"],
"expected_out": data["data"]["expectedAmountOut"],
"min_out": data["data"]["minAmountOut"],
"price_impact": data["data"]["priceImpact"],
"decimals_out": data["data"]["tokenTo"]["decimals"],
}
if status == "Partial":
result["warning"] = "Only a partial fill is available"
return result
Try it yourself -- verify the endpoint works before wiring up the agent:
curl "https://api.swapapi.dev/v1/swap/42161?tokenIn=0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE&tokenOut=0xaf88d065e77c8cC2239327C5EDb3A432268e5831&amount=1000000000000000000&sender=0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"
That fetches a quote for swapping 1 ETH to USDC on Arbitrum. The response includes tx.data (the encoded calldata), tx.to (the router contract), and expectedAmountOut in raw units.
Step 3: Wire Up the Agent Loop
The agent loop is where everything connects. The LLM receives user messages, decides whether to call the swap tool, processes the result, and responds in natural language. According to OpenAI's agent documentation, function calling is the recommended pattern for giving models structured access to external APIs.
import openai
import json
client = openai.OpenAI()
TOOLS = [swap_tool]
SYSTEM_PROMPT = """You are a DeFi trading assistant. You help users get swap quotes.
Common token addresses:
- ETH native: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE
- USDC (Ethereum): 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48
- USDC (Arbitrum): 0xaf88d065e77c8cC2239327C5EDb3A432268e5831
- USDC (Base): 0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913
- WETH (Arbitrum): 0x82aF49447D8a07e3bd95BD0d56f35241523fBab1
- WETH (Base): 0x4200000000000000000000000000000000000006
Always confirm the quote details before suggesting execution.
Warn the user if price impact exceeds 5%."""
def run_agent(user_message, wallet_address):
messages = [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": user_message},
]
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=TOOLS,
)
msg = response.choices[0].message
if msg.tool_calls:
for call in msg.tool_calls:
args = json.loads(call.function.arguments)
args["sender"] = wallet_address
result = get_swap_quote(**args)
messages.append(msg)
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps(result),
})
final = client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=TOOLS,
)
return final.choices[0].message.content
return msg.content
Run it with a natural language instruction:
print(run_agent("Swap 0.5 ETH to USDC on Arbitrum", "0xYourWalletAddress"))
The LLM will call get_swap_quote with chain_id=42161, the native ETH address, the Arbitrum USDC address, and amount="500000000000000000", then summarize the quote in plain English.
Step 4: Add Safety Checks and Price Impact Validation
In production, an ai trading agent crypto system needs guardrails. CoinDesk reports that autonomous agents now handle significant volume on prediction markets, but unchecked execution on low-liquidity pairs can cause severe slippage. Add pre-execution validation:
def validate_quote(quote):
if quote.get("error"):
return False, f"API error: {quote['error']}"
if quote["status"] == "NoRoute":
return False, "No route found for this pair"
if quote["status"] == "Partial":
return False, "Only partial fill available -- reduce amount"
impact = abs(quote.get("price_impact", 0))
if impact > 0.05:
return False, f"Price impact too high: {impact:.2%}"
return True, "Quote validated"
The swapapi.dev API returns priceImpact as a decimal (e.g., -0.0012 means -0.12%). Negative values indicate unfavorable impact. The API also provides minAmountOut, which is expectedAmountOut * (1 - maxSlippage) -- the on-chain transaction reverts if the actual output falls below this threshold.
Try it yourself -- check a quote on Base:
curl "https://api.swapapi.dev/v1/swap/8453?tokenIn=0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE&tokenOut=0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913&amount=1000000000000000000&sender=0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"
Step 5: Choose Your AI Agent Framework
The framework you pick determines how your agent handles multi-step reasoning, memory, and tool orchestration. LangChain holds roughly 30% of the AI agent framework market, but the right choice depends on your use case. Here is a comparison:
| Framework | Best For | Tool Calling | Multi-Agent | GitHub Stars |
|---|---|---|---|---|
| LangChain/LangGraph | Custom pipelines, production apps | Native | Yes (LangGraph) | 75,000+ |
| CrewAI | Multi-agent orchestration | Native | Yes (core feature) | 39,000+ |
| OpenAI Agents SDK | Simple single-agent flows | Native | Limited | N/A |
| AutoGPT | Fully autonomous agents | Plugin-based | No | 167,000+ |
| Direct API | Minimal overhead, full control | Manual | No | N/A |
For a swap-quoting agent, the direct OpenAI/Anthropic API approach (shown in Step 3) gives you maximum control with minimal dependencies. If you need multi-agent orchestration -- say, one agent for market analysis and another for execution -- CrewAI saw 280% adoption growth in 2025 and is purpose-built for that pattern.
Here is the same swap tool registered in LangChain:
from langchain_core.tools import tool
@tool
def swap_quote(chain_id: int, token_in: str, token_out: str, amount: str, sender: str) -> dict:
"""Get a DEX swap quote from swapapi.dev with executable calldata."""
return get_swap_quote(chain_id, token_in, token_out, amount, sender)
Step 6: Handle Multi-Chain Token Decimals
A common pitfall: token decimals vary across chains. USDC is 6 decimals on Ethereum, Arbitrum, and Base, but 18 decimals on BSC. The same applies to USDT on BSC. Getting this wrong means your agent will request swaps for amounts that are off by 12 orders of magnitude.
DECIMALS_OVERRIDE = {
56: {
"0x8AC76a51cc950d9822D68b83fE1Ad97B32Cd580d": 18,
"0x55d398326f99059fF775485246999027B3197955": 18,
}
}
def to_raw_amount(amount_human, decimals):
return str(int(float(amount_human) * (10 ** decimals)))
The swapapi.dev response always includes tokenFrom.decimals and tokenTo.decimals, so you can use these to convert expectedAmountOut back to human-readable values:
def to_human_amount(raw_amount, decimals):
return int(raw_amount) / (10 ** decimals)
For example, an expectedAmountOut of "2500000000" with decimals: 6 is 2,500 USDC. On BSC, the same USDC amount would be "2500000000000000000000" because BSC USDC uses 18 decimals.
Step 7: Deploy and Monitor Your Agent
85% of enterprises plan to deploy AI agents by end of 2026, and production deployment requires monitoring. Here is a minimal deployment pattern:
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("swap_agent")
def monitored_swap(user_message, wallet):
logger.info(f"Request: {user_message}")
result = run_agent(user_message, wallet)
logger.info(f"Response: {result[:200]}")
return result
Key production considerations:
- Rate limiting: swapapi.dev allows ~30 requests/minute per IP. Space your agent's requests accordingly.
- Timeout handling: Set a 15-second HTTP timeout. The API typically responds in 1-5 seconds.
- Quote freshness: Swap calldata expires after ~30 seconds. Always fetch a fresh quote immediately before execution.
-
Simulation: Use
eth_callwith the returnedtxobject before submitting. If it reverts, the on-chain transaction would fail too.
Try it yourself -- check that the API is up:
curl https://api.swapapi.dev/health
Frequently Asked Questions
What is an AI trading agent in crypto?
An ai trading agent crypto system is software that uses a large language model (LLM) to interpret trading instructions, fetch market data, and prepare or execute on-chain transactions autonomously. Unlike rule-based bots, AI agents handle natural language input and can reason about multi-step workflows like approving tokens before swapping.
Do I need an API key to use swapapi.dev?
No. The swapapi.dev API is completely free and requires no API keys, accounts, or authentication. You make a GET request with your swap parameters and receive executable transaction data. The only limit is approximately 30 requests per minute per IP address.
Which blockchains does swapapi.dev support?
The API supports 46 EVM chains including Ethereum (1), Arbitrum (42161), Base (8453), Optimism (10), Polygon (137), BSC (56), Avalanche (43114), Sonic (146), Berachain (80094), Monad (143), MegaETH (4326), and many others. The full list is available in the API documentation.
Can my AI agent execute swaps automatically?
The API returns ready-to-execute transaction data (tx.to, tx.data, tx.value), but signing and submitting the transaction requires a private key. Most production setups have the agent prepare and validate the swap, then require human approval (or a separate signer service) for the actual on-chain submission.
How do I handle partial fills and no-route responses?
Check data.status in every response. "Successful" means a full route was found. "Partial" means only part of your requested amount can be filled -- the response reflects the reduced amounts. "NoRoute" means no swap path exists for that pair. Your agent should handle all three cases and communicate the result clearly to the user.
Get Started
Everything you need to build an AI trading agent is available right now:
-
API Base URL:
https://api.swapapi.dev - OpenAPI Spec: https://swapapi.dev/openapi.json -- import this directly into your LLM tool definitions
- Documentation: https://swapapi.dev/docs -- interactive Swagger UI
- Chains: 46 EVM networks, no configuration needed
- Cost: Free, no API key required
Grab a quote right now:
curl "https://api.swapapi.dev/v1/swap/1?tokenIn=0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE&tokenOut=0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48&amount=1000000000000000000&sender=0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"
That single GET request returns executable swap calldata for 1 ETH to USDC on Ethereum. Wire it into your agent's tool definitions, add safety checks, and you have a production-ready AI trading agent.
Top comments (0)