Appearance
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()
funding = self.api.get(f"{self.base}/funding-rate/{symbol}").json()
liqs = self.api.get(f"{self.base}/liquidation/heatmap/{symbol}").json()
return {
"price": price,
"risk": vol,
"arbitrage": arb,
"funding": funding,
"liquidations": liqs
}
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"
if abs(data["funding"]["funding_rate"]) > 0.05:
return "FUNDING_RATE_TRADE"
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.05 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.03 USDC"
},
{
"name": "get_funding_rate",
"description": "Get current perpetual funding rate for a token",
"parameters": {
"type": "object",
"properties": {
"symbol": { "type": "string" }
},
"required": ["symbol"]
},
"endpoint": "https://api.foursec.xyz/funding-rate/:symbol",
"cost": "$0.03 USDC"
},
{
"name": "get_extreme_funding_rates",
"description": "Get extreme funding rates across all markets for trading signals",
"parameters": {
"type": "object",
"properties": {}
},
"endpoint": "https://api.foursec.xyz/funding-rate/extreme",
"cost": "$0.05 USDC"
},
{
"name": "get_liquidation_heatmap",
"description": "Get liquidation price levels heatmap for risk management",
"parameters": {
"type": "object",
"properties": {
"symbol": { "type": "string" }
},
"required": ["symbol"]
},
"endpoint": "https://api.foursec.xyz/liquidation/heatmap/:symbol",
"cost": "$0.04 USDC"
},
{
"name": "get_recent_liquidations",
"description": "Get recent liquidation events and cascades",
"parameters": {
"type": "object",
"properties": {}
},
"endpoint": "https://api.foursec.xyz/liquidation/recent",
"cost": "$0.03 USDC"
},
{
"name": "get_cex_prices",
"description": "Get aggregated CEX prices for multiple symbols",
"parameters": {
"type": "object",
"properties": {
"symbols": {
"type": "string",
"description": "Comma-separated symbol IDs (e.g., btc,eth,sol)"
}
},
"required": ["symbols"]
},
"endpoint": "https://api.foursec.xyz/api/v1/prices?symbols=:symbols",
"cost": "$0.02 USDC"
},
{
"name": "get_cex_market",
"description": "Get detailed CEX market information",
"parameters": {
"type": "object",
"properties": {
"id": {
"type": "string",
"description": "Market ID (e.g., bitcoin, ethereum)"
}
},
"required": ["id"]
},
"endpoint": "https://api.foursec.xyz/api/v1/market/:id",
"cost": "$0.03 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 ($0.01). 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 ($0.05)"
),
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 ($0.03). Input: token symbol"
),
Tool(
name="get_funding_rate",
func=lambda s: api.get(f"https://api.foursec.xyz/funding-rate/{s}").text,
description="Get current funding rate ($0.03). Input: token symbol"
),
Tool(
name="get_extreme_funding",
func=lambda x: api.get("https://api.foursec.xyz/funding-rate/extreme").text,
description="Get extreme funding rates for trading signals ($0.05)"
),
Tool(
name="get_liquidation_heatmap",
func=lambda s: api.get(f"https://api.foursec.xyz/liquidation/heatmap/{s}").text,
description="Get liquidation levels heatmap ($0.04). Input: token symbol"
),
Tool(
name="get_recent_liquidations",
func=lambda x: api.get("https://api.foursec.xyz/liquidation/recent").text,
description="Get recent liquidation events ($0.03)"
),
Tool(
name="get_cex_prices",
func=lambda s: api.get(f"https://api.foursec.xyz/api/v1/prices?symbols={s}").text,
description="Get CEX prices ($0.02). Input: comma-separated IDs (btc,eth)"
),
Tool(
name="get_cex_market",
func=lambda s: api.get(f"https://api.foursec.xyz/api/v1/market/{s}").text,
description="Get CEX market details ($0.03). Input: market ID (bitcoin)"
),
]
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
def fetch_funding_rate(self, symbol):
if not self.can_afford(0.03):
raise Exception("Daily budget exceeded")
data = self.api.get(f"https://api.foursec.xyz/funding-rate/{symbol}").json()
self.spent += 0.03
return data
def fetch_liquidation_heatmap(self, symbol):
if not self.can_afford(0.04):
raise Exception("Daily budget exceeded")
data = self.api.get(f"https://api.foursec.xyz/liquidation/heatmap/{symbol}").json()
self.spent += 0.04
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...
elif decision == "FUNDING_RATE_TRADE":
funding = agent.api.get(
f"https://api.foursec.xyz/funding-rate/{symbol}"
).json()
# Execute funding rate strategy...
await asyncio.sleep(interval)
# Run: asyncio.run(trading_loop(agent, ['ETH', 'BTC', 'SOL']))