AI Agent Integration
Overview
4SEC API is designed for AI agents. The x402 protocol enables autonomous payment without human intervention, making it perfect for trading bots, research agents, and autonomous DeFi systems.
Agent Architecture
class TradingAgent:
def __init__(self, wallet_key):
from x402.client import X402Client
from eth_account import Account
self.api = X402Client(wallet=Account.from_key(wallet_key))
self.base = "https://api.foursec.xyz"
async def market_analysis(self, symbol):
price = self.api.get(f"{self.base}/price/{symbol}").json()
vol = self.api.get(f"{self.base}/volatility-index/{symbol}").json()
arb = self.api.get(f"{self.base}/arbitrage-opportunity").json()
return {"price": price, "risk": vol, "arbitrage": arb}
async def decide(self, symbol):
data = await self.market_analysis(symbol)
if data["risk"]["risk_level"] == "low":
if data["arbitrage"]["total_opportunities"] > 0:
return "BUY_ARBITRAGE"
return "BUY"
elif data["risk"]["risk_level"] == "high":
return "SELL"
return "HOLD"
MCP (Model Context Protocol)
Integrate 4SEC as a tool for AI agents using MCP:
{
"tools": [
{
"name": "get_crypto_price",
"description": "Get real-time aggregated crypto price from multiple DEXes",
"parameters": {
"type": "object",
"properties": {
"symbol": {
"type": "string",
"description": "Token symbol (ETH, BTC, SOL, etc.)"
}
},
"required": ["symbol"]
},
"endpoint": "https://api.foursec.xyz/price/:symbol",
"cost": "$0.01 USDC"
},
{
"name": "find_arbitrage",
"description": "Find cross-DEX arbitrage opportunities",
"parameters": {
"type": "object",
"properties": {
"min_profit_usd": {
"type": "number",
"description": "Minimum profit threshold"
}
}
},
"endpoint": "https://api.foursec.xyz/arbitrage-opportunity",
"cost": "$0.03 USDC"
},
{
"name": "assess_risk",
"description": "Get volatility and risk metrics for a token",
"parameters": {
"type": "object",
"properties": {
"symbol": { "type": "string" }
},
"required": ["symbol"]
},
"endpoint": "https://api.foursec.xyz/volatility-index/:symbol",
"cost": "$0.02 USDC"
}
]
}
LangChain Integration
from langchain.tools import Tool
from x402.client import X402Client
from eth_account import Account
wallet = Account.from_key("0x_your_key")
api = X402Client(wallet=wallet)
tools = [
Tool(
name="get_price",
func=lambda s: api.get(f"https://api.foursec.xyz/price/{s}").text,
description="Get real-time crypto price. Input: token symbol (ETH, BTC, etc.)"
),
Tool(
name="find_arbitrage",
func=lambda x: api.get("https://api.foursec.xyz/arbitrage-opportunity").text,
description="Find arbitrage opportunities across DEXes"
),
Tool(
name="assess_risk",
func=lambda s: api.get(f"https://api.foursec.xyz/volatility-index/{s}").text,
description="Get risk metrics for a token. Input: token symbol"
)
]
Cost Management for Agents
Budget Control
class BudgetedAgent:
def __init__(self, wallet, daily_budget=10.0):
self.api = X402Client(wallet=wallet)
self.daily_budget = daily_budget
self.spent = 0.0
def can_afford(self, cost):
return (self.spent + cost) <= self.daily_budget
def fetch_price(self, symbol):
if not self.can_afford(0.01):
raise Exception("Daily budget exceeded")
data = self.api.get(f"https://api.foursec.xyz/price/{symbol}").json()
self.spent += 0.01
return data
Smart Caching
# Cache prices for 60 seconds to reduce costs
# Only fetch new data when cache expires
# Expected savings: 50-70% reduction in API costs
Autonomous Trading Loop
import asyncio
import time
async def trading_loop(agent, symbols, interval=60):
"""
Continuous trading loop.
Runs every 'interval' seconds.
"""
while True:
for symbol in symbols:
decision = await agent.decide(symbol)
print(f"{symbol}: {decision}")
if decision == "BUY_ARBITRAGE":
arb = agent.api.get(
"https://api.foursec.xyz/arbitrage-opportunity"
).json()
# Execute arbitrage...
await asyncio.sleep(interval)
# Run: asyncio.run(trading_loop(agent, ['ETH', 'BTC', 'SOL']))