Skip to main content

Nex-T1 Examples

Complete, production-ready examples for every Nex-T1 API endpoint. All examples include curl, Python, and TypeScript implementations.
Prerequisites:
  • Nex-T1 server running (default: http://localhost:8000)
  • Valid user credentials or registration
  • Session token for authenticated requests

1. Authentication

Register a New User

Create a new user account before accessing protected endpoints.
curl -X POST http://localhost:8000/api/v1/auth/register \
  -H 'Content-Type: application/json' \
  -d '{
    "email": "user@example.com",
    "password": "SecurePass123!"
  }'
{
  "id": 1,
  "email": "user@example.com",
  "token": {
    "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "token_type": "bearer",
    "expires_at": "2025-10-04T12:00:00Z"
  }
}

Login and Create Session

Login with existing credentials and create a chat session.
# Step 1: Login
ACCESS_TOKEN=$(curl -sS -X POST http://localhost:8000/api/v1/auth/login \
  -H "Content-Type: application/x-www-form-urlencoded" \
  --data-urlencode "username=user@example.com" \
  --data-urlencode "password=SecurePass123!" \
  | jq -r '.access_token')

# Step 2: Create session
SESSION_TOKEN=$(curl -sS -X POST http://localhost:8000/api/v1/auth/session \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  | jq -r '.token.access_token')

echo "Session Token: $SESSION_TOKEN"
{
  "session_id": "550e8400-e29b-41d4-a716-446655440000",
  "name": "",
  "token": {
    "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "token_type": "bearer",
    "expires_at": "2025-10-04T12:00:00Z"
  }
}

Manage Sessions

List, update, and delete sessions.
# List all sessions
curl -X GET http://localhost:8000/api/v1/auth/sessions \
  -H "Authorization: Bearer $SESSION_TOKEN"

# Update session name
curl -X PATCH http://localhost:8000/api/v1/auth/session/{session_id}/name \
  -H "Authorization: Bearer $SESSION_TOKEN" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  --data-urlencode "name=Research Session"

# Delete session
curl -X DELETE http://localhost:8000/api/v1/auth/session/{session_id} \
  -H "Authorization: Bearer $SESSION_TOKEN"

2. Chat & Messaging

Simple Chat Query

Send a message and receive a complete response.
curl -X POST http://localhost:8000/api/v1/chatbot/chat \
  -H "Authorization: Bearer $SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "messages": [
      {"role": "user", "content": "What is the current TVL on Ethereum?"}
    ]
  }'

Streaming Chat

Receive real-time token-by-token responses using Server-Sent Events (SSE).
curl -N -X POST http://localhost:8000/api/v1/chatbot/chat/stream \
  -H "Authorization: Bearer $SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "messages": [
      {"role": "user", "content": "Explain how Uniswap V3 works"}
    ]
  }'
Each SSE event follows this format:
data: {"role": "assistant", "content": "Uniswap V3 "}

data: {"role": "assistant", "content": "is a "}

data: {"role": "assistant", "content": "decentralized "}

data: [DONE]

Get and Clear Message History

Retrieve or clear all messages in a session.
# Get all messages
curl -X GET http://localhost:8000/api/v1/chatbot/messages \
  -H "Authorization: Bearer $SESSION_TOKEN"

# Clear chat history
curl -X DELETE http://localhost:8000/api/v1/chatbot/messages \
  -H "Authorization: Bearer $SESSION_TOKEN"

3. Research & Data

The Graph Subgraph Query

Query blockchain data from The Graph subgraphs.
curl -X POST http://localhost:8000/api/v1/multi-agent/research/preview \
  -H "Authorization: Bearer $SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "subgraph": "https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v3",
    "gql": "query($first: Int!) { pools(first: $first, orderBy: totalValueLockedUSD, orderDirection: desc) { id token0 { symbol } token1 { symbol } totalValueLockedUSD volumeUSD } }",
    "variables": { "first": 5 }
  }'

Dune Analytics Query

Execute parametrized SQL queries on Dune Analytics.
curl -X POST http://localhost:8000/api/v1/multi-agent/research/preview \
  -H "Authorization: Bearer $SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "dune_query_id": 3238237,
    "dune_params": {
      "blockchain": "ethereum",
      "days": 7
    }
  }'

DeFiLlama Multi-Source Research

Combine The Graph, Dune, and DeFiLlama data in a single request.
curl -X POST http://localhost:8000/api/v1/multi-agent/research/preview \
  -H "Authorization: Bearer $SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "subgraph": "https://api.thegraph.com/subgraphs/name/uniswap/uniswap-v3",
    "gql": "query($first: Int!) { pools(first: $first) { id totalValueLockedUSD } }",
    "variables": { "first": 3 },
    "dune_query_id": 3238237,
    "dune_params": { "blockchain": "ethereum" },
    "defi_calls": [
      {
        "tool_name": "tvl_get",
        "arguments": { "chain": "ethereum" }
      },
      {
        "tool_name": "token_price",
        "arguments": { "token": "ethereum" }
      }
    ],
    "tvl_chain": "ethereum",
    "price_symbol": "ETH",
    "pools_chain": "ethereum",
    "pools_limit": 10
  }'
{
  "graph_data": {
    "data": {
      "pools": [
        {
          "id": "0x...",
          "totalValueLockedUSD": "123456789.50"
        }
      ]
    }
  },
  "dune_rows": [...],
  "dune_state": "QUERY_STATE_COMPLETED",
  "defi_results": [
    {
      "tool": "tvl_get",
      "result": { "tvl": 50000000000 }
    },
    {
      "tool": "token_price",
      "result": { "price": 2500.50 }
    }
  ],
  "summary": "Ethereum TVL is $50B. Current ETH price: $2,500.50. Top Uniswap V3 pool has $123.4M TVL."
}

4. Trading & Quotes

Get Swap Quote (EVM)

Get a pseudo-quote for an EVM token swap (development/simulation).
curl -X POST http://localhost:8000/api/v1/multi-agent/quote/evm/pseudo \
  -H "Authorization: Bearer $SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "input": {
      "chain_id": 8453,
      "token_in_address": "0x4200000000000000000000000000000000000006",
      "token_out_address": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
      "amount_in": "0.01",
      "amount_in_currency": "token_units",
      "slippage_bps": 50
    }
  }'
{
  "route": ["0x4200000000000000000000000000000000000006", "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"],
  "expected_out": "25.5",
  "price_impact_bps": 15,
  "slippage_bps": 50,
  "fees": {
    "protocol_fee": "0.003",
    "gas_estimate": "150000"
  },
  "gas_estimate": "150000",
  "venue": "uniswap-v3",
  "quote_id": "quote_abc123",
  "expires_at": "2025-10-03T12:15:00Z"
}

Risk Assessment

Assess risk before executing a trade.
curl -X POST http://localhost:8000/api/v1/multi-agent/risk/preview \
  -H "Authorization: Bearer $SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "quote": {
      "expected_out": "25.5",
      "slippage_bps": 50,
      "venue": "uniswap-v3",
      "quote_id": "quote_abc123",
      "expires_at": "2025-10-03T12:15:00Z"
    },
    "input": {
      "chain": "evm",
      "addresses": [
        "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
      ],
      "checks": ["rug", "whale_flow", "price_sanity"]
    },
    "thresholds": {
      "max_price_impact_bps": 100,
      "min_liquidity_usd": 100000
    }
  }'
{
  "level": "low",
  "aggregate_score": 85,
  "checks": [
    {
      "name": "rug",
      "result": "pass",
      "details": { "liquidity_locked": true }
    },
    {
      "name": "whale_flow",
      "result": "pass",
      "details": { "whale_concentration": 0.15 }
    },
    {
      "name": "price_sanity",
      "result": "pass",
      "details": { "deviation_percent": 2.5 }
    }
  ],
  "flags": []
}

Execute Trade (EVM)

Execute a swap on EVM chains with safety checks.
Production Warning: Only execute trades with confirm: true when you’re ready for real transactions. Always test with simulate_only: true first.
# Simulate first
curl -X POST http://localhost:8000/api/v1/multi-agent/execute/evm \
  -H "Authorization: Bearer $SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "input": {
      "chain_id": 8453,
      "token_in_address": "0x4200000000000000000000000000000000000006",
      "token_out_address": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
      "amount_in": "0.01",
      "amount_in_currency": "token_units",
      "slippage_bps": 50,
      "simulate_only": true
    },
    "confirm": false,
    "skip_risk": false,
    "thresholds": {
      "max_price_impact_bps": 100
    }
  }'

5. Multi-Agent Workflows

Intent Routing Preview

Preview how user intent is routed to specialized teams.
curl -X POST http://localhost:8000/api/v1/multi-agent/preview \
  -H "Authorization: Bearer $SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "text": "Swap 0.5 ETH for USDC on Base with low slippage"
  }'
User InputIntentTeam
”What’s the TVL on Ethereum?”researchresearch_team
”Swap 1 ETH to USDC”tradetrading_team
”Is this token safe to buy?”risk_assessmentrisk_team
”Get quote for ETH to DAI”quotetrading_team

Full Preview Run (Research + Quote + Risk)

Execute a complete workflow including research, quote, and risk assessment.
curl -X POST http://localhost:8000/api/v1/multi-agent/preview/run \
  -H "Authorization: Bearer $SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "text": "Swap 0.1 ETH to USDC on Base",
    "evm_input": {
      "chain_id": 8453,
      "token_in_address": "0x4200000000000000000000000000000000000006",
      "token_out_address": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
      "amount_in": "0.1",
      "amount_in_currency": "token_units",
      "slippage_bps": 50
    },
    "thresholds": {
      "max_price_impact_bps": 100,
      "min_liquidity_usd": 100000
    }
  }'

6. MCP Tool Integration

DeFiLlama Tools

List and invoke DeFiLlama MCP tools for on-chain data.
# List available tools
curl -X GET http://localhost:8000/api/v1/multi-agent/defillama/tools \
  -H "Authorization: Bearer $SESSION_TOKEN"

# Get TVL for a chain
curl -X POST http://localhost:8000/api/v1/multi-agent/defillama/invoke \
  -H "Authorization: Bearer $SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "tool_name": "tvl_get",
    "arguments": { "chain": "ethereum" }
  }'

# Get token price
curl -X POST http://localhost:8000/api/v1/multi-agent/defillama/invoke \
  -H "Authorization: Bearer $SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "tool_name": "token_price",
    "arguments": { "token": "ethereum" }
  }'

Binance Market Data

Subscribe to real-time Binance market data streams.
# List Binance tools
curl -X GET http://localhost:8000/api/v1/multi-agent/binance/tools \
  -H "Authorization: Bearer $SESSION_TOKEN"

# Subscribe to BTC/USDT spot trades
curl -X POST http://localhost:8000/api/v1/multi-agent/binance/subscribe \
  -H "Authorization: Bearer $SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "symbol": "BTCUSDT",
    "market": "spot",
    "streams": ["trade", "kline"],
    "interval": "1m"
  }'

# Unsubscribe
curl -X POST http://localhost:8000/api/v1/multi-agent/binance/unsubscribe \
  -H "Authorization: Bearer $SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "subscription_id": "sub-123"
  }'

Bitcoin Tools

Access Bitcoin blockchain data and utilities.
# List Bitcoin tools
curl -X GET http://localhost:8000/api/v1/multi-agent/bitcoin/tools \
  -H "Authorization: Bearer $SESSION_TOKEN"

# Get latest block
curl -X GET http://localhost:8000/api/v1/multi-agent/bitcoin/latest-block \
  -H "Authorization: Bearer $SESSION_TOKEN"

# Decode raw transaction
curl -X POST http://localhost:8000/api/v1/multi-agent/bitcoin/tx/decode \
  -H "Authorization: Bearer $SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "raw_tx": "0100000001..."
  }'

# Validate address
curl -X POST http://localhost:8000/api/v1/multi-agent/bitcoin/address/validate \
  -H "Authorization: Bearer $SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "address": "bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh"
  }'

Get real-time oracle price data from Chainlink.
curl -X POST http://localhost:8000/api/v1/multi-agent/chainlink/price \
  -H "Authorization: Bearer $SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "chain": "ethereum",
    "pair": "ETH/USD"
  }'

7. Wallet & Positions

Get EVM Wallet Balance

Check wallet balance for EVM addresses.
curl -X POST http://localhost:8000/api/v1/multi-agent/wallet/evm/balance \
  -H "Authorization: Bearer $SESSION_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "address": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb"
  }'

List Positions

Get all open positions filtered by agent, wallet, or token.
# All positions
curl -X GET http://localhost:8000/api/v1/positions \
  -H "Authorization: Bearer $SESSION_TOKEN"

# Filter by agent
curl -X GET "http://localhost:8000/api/v1/positions?agent=trading_team" \
  -H "Authorization: Bearer $SESSION_TOKEN"

# Filter by wallet
curl -X GET "http://localhost:8000/api/v1/positions?wallet_address=0x..." \
  -H "Authorization: Bearer $SESSION_TOKEN"

8. Metrics & Analytics

Volume Metrics

Get total trading volume with optional filters.
# Total volume
curl -X GET http://localhost:8000/api/v1/metrics/volume \
  -H "Authorization: Bearer $SESSION_TOKEN"

# Volume by date range
curl -X GET "http://localhost:8000/api/v1/metrics/volume?start=2025-10-01T00:00:00Z&end=2025-10-03T23:59:59Z" \
  -H "Authorization: Bearer $SESSION_TOKEN"

# Volume by agent
curl -X GET "http://localhost:8000/api/v1/metrics/volume?agent=trading_team" \
  -H "Authorization: Bearer $SESSION_TOKEN"

PnL Metrics

Get realized and unrealized profit/loss.
# Realized PnL
curl -X GET http://localhost:8000/api/v1/metrics/pnl \
  -H "Authorization: Bearer $SESSION_TOKEN"

# Unrealized PnL
curl -X GET http://localhost:8000/api/v1/metrics/pnl/unrealized \
  -H "Authorization: Bearer $SESSION_TOKEN"

TVL Metrics

Get Total Value Locked from agent wallets or DeFiLlama.
# Agent TVL
curl -X GET "http://localhost:8000/api/v1/metrics/tvl?mode=agents" \
  -H "Authorization: Bearer $SESSION_TOKEN"

# DeFiLlama chain TVL
curl -X GET "http://localhost:8000/api/v1/metrics/tvl?mode=defillama&chain=ethereum" \
  -H "Authorization: Bearer $SESSION_TOKEN"

9. Advanced Patterns

Error Handling

Robust error handling for all API calls.
import requests
from typing import Optional, Dict, Any

def safe_api_call(
    method: str,
    endpoint: str,
    session_token: str,
    json_data: Optional[Dict[Any, Any]] = None,
    params: Optional[Dict[str, Any]] = None
) -> Optional[Dict[Any, Any]]:
    """
    Make a safe API call with proper error handling.
    """
    headers = {"Authorization": f"Bearer {session_token}"}
    url = f"{BASE_URL}{endpoint}"

    try:
        if method.upper() == "GET":
            response = requests.get(url, headers=headers, params=params, timeout=30)
        elif method.upper() == "POST":
            response = requests.post(url, headers=headers, json=json_data, timeout=30)
        elif method.upper() == "DELETE":
            response = requests.delete(url, headers=headers, timeout=30)
        else:
            raise ValueError(f"Unsupported method: {method}")

        response.raise_for_status()
        return response.json()

    except requests.exceptions.HTTPError as e:
        if e.response.status_code == 401:
            print("Authentication failed. Token may be expired.")
        elif e.response.status_code == 422:
            print(f"Validation error: {e.response.json()}")
        elif e.response.status_code == 429:
            print("Rate limit exceeded. Retry after cooldown.")
        else:
            print(f"HTTP error {e.response.status_code}: {e.response.text}")
        return None

    except requests.exceptions.ConnectionError:
        print("Connection error. Check if server is running.")
        return None

    except requests.exceptions.Timeout:
        print("Request timed out.")
        return None

    except Exception as e:
        print(f"Unexpected error: {e}")
        return None

# Usage
result = safe_api_call(
    "POST",
    "/api/v1/chatbot/chat",
    session_token,
    json_data={"messages": [{"role": "user", "content": "Hello"}]}
)

if result:
    print("Success:", result)
else:
    print("Request failed")

Retry Logic with Exponential Backoff

Handle transient failures with automatic retries.
import time
from typing import Callable, Optional, TypeVar

T = TypeVar('T')

def retry_with_backoff(
    func: Callable[[], T],
    max_retries: int = 3,
    initial_delay: float = 1.0,
    backoff_factor: float = 2.0
) -> Optional[T]:
    """
    Retry a function with exponential backoff.
    """
    delay = initial_delay

    for attempt in range(max_retries):
        try:
            return func()
        except Exception as e:
            if attempt == max_retries - 1:
                print(f"Max retries ({max_retries}) exceeded")
                raise

            print(f"Attempt {attempt + 1} failed: {e}")
            print(f"Retrying in {delay}s...")
            time.sleep(delay)
            delay *= backoff_factor

    return None

# Usage
def get_tvl():
    response = requests.get(
        f"{BASE_URL}/api/v1/metrics/tvl",
        headers={"Authorization": f"Bearer {session_token}"},
        params={"mode": "agents"}
    )
    response.raise_for_status()
    return response.json()

tvl_data = retry_with_backoff(get_tvl, max_retries=3)
if tvl_data:
    print(f"TVL: ${tvl_data['tvl_usd']:,.2f}")

Batch Operations

Execute multiple independent operations in parallel.
import asyncio
import aiohttp
from typing import List, Dict, Any

async def fetch_url(
    session: aiohttp.ClientSession,
    method: str,
    url: str,
    **kwargs
) -> Dict[Any, Any]:
    """Fetch a single URL."""
    async with session.request(method, url, **kwargs) as response:
        return await response.json()

async def batch_requests(
    session_token: str,
    requests: List[Dict[str, Any]]
) -> List[Dict[Any, Any]]:
    """
    Execute multiple API requests in parallel.

    Args:
        session_token: Authentication token
        requests: List of request configs [{"method": "GET", "endpoint": "/..."}]
    """
    headers = {"Authorization": f"Bearer {session_token}"}

    async with aiohttp.ClientSession(headers=headers) as session:
        tasks = []
        for req in requests:
            url = f"{BASE_URL}{req['endpoint']}"
            task = fetch_url(
                session,
                req.get("method", "GET"),
                url,
                json=req.get("json"),
                params=req.get("params")
            )
            tasks.append(task)

        results = await asyncio.gather(*tasks, return_exceptions=True)
        return results

# Usage
batch_requests_list = [
    {"method": "GET", "endpoint": "/api/v1/metrics/volume"},
    {"method": "GET", "endpoint": "/api/v1/metrics/pnl"},
    {"method": "GET", "endpoint": "/api/v1/metrics/tvl", "params": {"mode": "agents"}},
    {"method": "GET", "endpoint": "/api/v1/positions"}
]

results = asyncio.run(batch_requests(session_token, batch_requests_list))

volume, pnl, tvl, positions = results
print(f"Volume: ${volume['total_volume_usd']:,.2f}")
print(f"PnL: ${pnl['realized_pnl_usd']:,.2f}")
print(f"TVL: ${tvl['tvl_usd']:,.2f}")
print(f"Positions: {len(positions)}")

10. Complete Workflow Example

End-to-End Trading Flow

A complete example combining authentication, research, quote, risk assessment, and execution.
import requests
from typing import Dict, Any, Optional

BASE_URL = "http://localhost:8000"

class NexT1Client:
    def __init__(self, email: str, password: str):
        self.email = email
        self.password = password
        self.session_token: Optional[str] = None

    def authenticate(self) -> bool:
        """Login and create session."""
        # Step 1: Login
        login_resp = requests.post(
            f"{BASE_URL}/api/v1/auth/login",
            data={"username": self.email, "password": self.password}
        )

        if login_resp.status_code != 200:
            print("Login failed")
            return False

        access_token = login_resp.json()["access_token"]

        # Step 2: Create session
        session_resp = requests.post(
            f"{BASE_URL}/api/v1/auth/session",
            headers={"Authorization": f"Bearer {access_token}"}
        )

        if session_resp.status_code != 200:
            print("Session creation failed")
            return False

        self.session_token = session_resp.json()["token"]["access_token"]
        print("✓ Authenticated successfully")
        return True

    def research_token(self, token_address: str) -> Dict[Any, Any]:
        """Research a token using DeFiLlama."""
        print(f"\n=== Researching {token_address} ===")

        response = requests.post(
            f"{BASE_URL}/api/v1/multi-agent/research/preview",
            headers={"Authorization": f"Bearer {self.session_token}"},
            json={
                "defi_calls": [
                    {"tool_name": "token_price", "arguments": {"token": "ethereum"}}
                ],
                "price_symbol": "ETH"
            }
        )

        data = response.json()
        print(f"Research Summary: {data.get('summary', 'N/A')}")
        return data

    def get_quote(
        self,
        chain_id: int,
        token_in: str,
        token_out: str,
        amount: str
    ) -> Dict[Any, Any]:
        """Get swap quote."""
        print(f"\n=== Getting Quote ===")

        response = requests.post(
            f"{BASE_URL}/api/v1/multi-agent/quote/evm/pseudo",
            headers={"Authorization": f"Bearer {self.session_token}"},
            json={
                "input": {
                    "chain_id": chain_id,
                    "token_in_address": token_in,
                    "token_out_address": token_out,
                    "amount_in": amount,
                    "amount_in_currency": "token_units",
                    "slippage_bps": 50
                }
            }
        )

        quote = response.json()
        print(f"Expected Output: {quote.get('expected_out')} tokens")
        print(f"Price Impact: {quote.get('price_impact_bps', 'N/A')} bps")
        return quote

    def assess_risk(self, quote: Dict[Any, Any], token_address: str) -> Dict[Any, Any]:
        """Assess trade risk."""
        print(f"\n=== Assessing Risk ===")

        response = requests.post(
            f"{BASE_URL}/api/v1/multi-agent/risk/preview",
            headers={"Authorization": f"Bearer {self.session_token}"},
            json={
                "quote": quote,
                "input": {
                    "chain": "evm",
                    "addresses": [token_address],
                    "checks": ["rug", "whale_flow", "price_sanity"]
                },
                "thresholds": {
                    "max_price_impact_bps": 100,
                    "min_liquidity_usd": 100000
                }
            }
        )

        risk = response.json()
        print(f"Risk Level: {risk['level']}")
        print(f"Flags: {', '.join(risk.get('flags', [])) or 'None'}")
        return risk

    def execute_trade(
        self,
        chain_id: int,
        token_in: str,
        token_out: str,
        amount: str,
        simulate: bool = True
    ) -> Dict[Any, Any]:
        """Execute or simulate trade."""
        mode = "Simulating" if simulate else "Executing"
        print(f"\n=== {mode} Trade ===")

        response = requests.post(
            f"{BASE_URL}/api/v1/multi-agent/execute/evm",
            headers={"Authorization": f"Bearer {self.session_token}"},
            json={
                "input": {
                    "chain_id": chain_id,
                    "token_in_address": token_in,
                    "token_out_address": token_out,
                    "amount_in": amount,
                    "amount_in_currency": "token_units",
                    "slippage_bps": 50,
                    "simulate_only": simulate
                },
                "confirm": not simulate,
                "skip_risk": False
            }
        )

        result = response.json()
        print(f"Status: {result.get('status')}")
        if result.get('tx_hash'):
            print(f"TX Hash: {result['tx_hash']}")
            print(f"Explorer: {result.get('explorer_url')}")
        return result


# Complete workflow
def main():
    # Initialize client
    client = NexT1Client("user@example.com", "SecurePass123!")

    # Authenticate
    if not client.authenticate():
        return

    # Define trade parameters
    CHAIN_ID = 8453  # Base
    WETH = "0x4200000000000000000000000000000000000006"
    USDC = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
    AMOUNT = "0.01"

    # Step 1: Research
    research_data = client.research_token(USDC)

    # Step 2: Get Quote
    quote = client.get_quote(CHAIN_ID, WETH, USDC, AMOUNT)

    # Step 3: Assess Risk
    risk = client.assess_risk(quote, USDC)

    # Step 4: Decision
    if risk["level"] in ["low", "medium"]:
        print("\n✓ Risk acceptable, proceeding with simulation")
        result = client.execute_trade(CHAIN_ID, WETH, USDC, AMOUNT, simulate=True)

        if result.get("status") == "success":
            print("\n✓ Simulation successful!")

            # Uncomment to execute for real
            # print("\nExecuting real trade...")
            # final_result = client.execute_trade(CHAIN_ID, WETH, USDC, AMOUNT, simulate=False)
    else:
        print(f"\n✗ Risk level {risk['level']} too high, aborting trade")


if __name__ == "__main__":
    main()

Common Errors & Solutions

Problem: Authentication failed or token expired.Solutions:
  • Verify credentials are correct
  • Create a new session if token expired
  • Check Authorization: Bearer <token> header format
Problem: Invalid request parameters.Solutions:
  • Check required fields are present
  • Verify data types match schema
  • Review OpenAPI spec at /openapi.json
Problem: Too many requests in a short time.Solutions:
  • Implement exponential backoff
  • Reduce request frequency
  • Use batch operations when possible
Problem: Server not reachable.Solutions:
  • Verify server is running: http://localhost:8000/health
  • Check BASE_URL configuration
  • Ensure firewall allows connections

Next Steps