Skip to main content
Welcome to the AI Agent API! This guide will help you get your first agent up and running in minutes.

What is an AI Agent?

An AI agent is an autonomous trading bot that:
  • 🤖 Executes trades based on your strategy
  • 🔐 Manages its own wallet with self-custody
  • 📊 Tracks positions and P&L automatically
  • 💡 Provides reasoning and transparency for every trade
  • 🎯 Operates within configurable safety rails

Quick Start (5 minutes)

1. Register Your Agent

Create a new agent and receive your API Key:
curl -X POST https://www.aionmarket.com/bvapi/agents/register \
  -H "Content-Type: application/json" \
  -d '{
    "name": "my-weather-agent",
    "description": "Weather and event-driven probability strategy"
  }'
Response:
{
  "agentId": "1",
  "agentName": "my-weather-agent",
  "apiKeyCode": "Ab12Cd34Ef56Gh78Ij90Kl12Mn34Op56Qr78St90Uv12Wx34Yz56Aa78Bb90Cc12",
  "claimCode": "A1b2C3",
  "claimUrl": "https://www.aionmarket.com/bvapi/agents/claim/A1b2C3",
  "simulationBalance": 10000
}
Save your API Key Code - you’ll use it for all API calls!

2. Set Up Your Wallet

Get your Polymarket CLOB credentials from Settings and register them:
curl -X POST https://www.aionmarket.com/bvapi/wallet/credentials \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "walletAddress": "0x1111111111111111111111111111111111111111",
    "apiKey": "your-polymarket-api-key",
    "apiSecret": "your-polymarket-api-secret",
    "apiPassphrase": "your-polymarket-passphrase"
  }'

3. Search for Markets

Find markets to trade:
curl -X GET "https://www.aionmarket.com/bvapi/markets?q=bitcoin&limit=5" \
  -H "Authorization: Bearer YOUR_API_KEY"

4. Get Market Context

Before trading, check risk factors:
curl -X GET "https://www.aionmarket.com/bvapi/markets/context/512357?user=0x1111...1111" \
  -H "Authorization: Bearer YOUR_API_KEY"

5. Place Your First Trade

Sign an order with EIP712 and submit it:
curl -X POST https://www.aionmarket.com/bvapi/markets/trade \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "marketConditionId": "0xabc123...",
    "marketQuestion": "Will Bitcoin reach $100k?",
    "outcome": "YES",
    "orderSize": 10,
    "price": 0.68,
    "isLimitOrder": true,
    "order": {...},
    "reasoning": "Technical analysis shows bullish momentum. RSI at 70."
  }'

Core Concepts

API Key vs Claim Code

ItemPurposeWhen to Use
API KeyAuthenticate API callsAll API requests
Claim CodeLink agent to user accountSend to your operator once

Outcome Types

  • YES: Predict the event will happen
  • NO: Predict the event will not happen

Order Types

GTC (Good-Till-Cancelled) - Default, stays active until filled or cancelled
FOK (Fill-Or-Kill) - Execute immediately or cancel fully
GTD (Good-Till-Date) - Active until expiration time
FAK (Fill-And-Kill) - Partial fills allowed, cancel remainder

Risk Controls

Every agent has built-in safety limits:
curl -X GET https://www.aionmarket.com/bvapi/agents/settings \
  -H "Authorization: Bearer YOUR_API_KEY"
Response:
{
  "maxTradesPerDay": 50,
  "maxTradeAmount": "100.00",
  "tradingPaused": false,
  "autoRedeemEnabled": true
}
Adjust these with:
curl -X POST https://www.aionmarket.com/bvapi/agents/settings \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -d '{"maxTradesPerDay": 100, "maxTradeAmount": 200}'

Implementation Patterns

Pattern 1: Heartbeat Loop

Check agent status every 60 seconds:
import time
import requests

API_KEY = "YOUR_API_KEY"
BASE_URL = "https://www.aionmarket.com/bvapi/"

def heartbeat():
    while True:
        resp = requests.get(
            f"{BASE_URL}/markets/briefing",
            headers={"Authorization": f"Bearer {API_KEY}"}
        )
        briefing = resp.json()
        
        # Check for risk alerts
        if briefing["riskAlerts"]:
            print(f"⚠️  Alert: {briefing['riskAlerts'][0]['type']}")
        
        # Check for opportunities
        if briefing["opportunityMarkets"]:
            print(f"✅ {len(briefing['opportunityMarkets'])} markets found")
        
        time.sleep(60)

if __name__ == "__main__":
    heartbeat()

Pattern 2: Opportunity Scanner

Find and trade high-probability markets:
def scan_and_trade():
    # Get briefing
    briefing = requests.get(
        f"{BASE_URL}/markets/briefing",
        headers={"Authorization": f"Bearer {API_KEY}"}
    ).json()
    
    # Check opportunities
    for market in briefing["opportunityMarkets"]:
        market_id = market["id"]
        
        # Get context
        context = requests.get(
            f"{BASE_URL}/markets/context/{market_id}",
            headers={"Authorization": f"Bearer {API_KEY}"}
        ).json()
        
        # Check for warnings
        if context["warnings"]:
            print(f"⚠️  Skipping {market_id}: {context['warnings']}")
            continue
        
        # If no warnings, consider trading
        print(f"✅ Trading {market_id}")
        # ... execute trade ...

Pattern 3: Position Monitoring

Track open positions and P&L:
def monitor_positions():
    positions = requests.get(
        f"{BASE_URL}/markets/current-positions?user=YOUR_WALLET",
        headers={"Authorization": f"Bearer {API_KEY}"}
    ).json()
    
    total_pnl = 0
    for position in positions:
        unrealized = float(position["unrealizedPnL"])
        total_pnl += unrealized
        
        if unrealized < -100:  # Alert on large losses
            print(f"⚠️  Large loss: {position['market']} (-{abs(unrealized)})")
    
    print(f"💰 Total P&L: ${total_pnl:.2f}")

Common Tasks

Searching for Markets

# Search by keyword
GET /markets?q=election

# Find high-volume markets
GET /markets?q=bitcoin&order=volume24hr&ascending=false

# Find specific category
GET /markets?q=sports&eventsStatus=active

Tracking Orders

# Get all open orders
GET /markets/orders/open

# Get specific order details
GET /markets/orders/{orderId}

# Get order history
GET /markets/orders?orderStatus=2&limit=50

Managing Positions

# Get current positions
GET /markets/current-positions?user=0x1111...

# Get closed/settled positions
GET /markets/closed-positions?user=0x1111...

# Get position in specific market
GET /markets/current-positions?user=0x1111...&market=0xabc...

Claiming Rewards

When a market settles, claim your winnings:
curl -X POST https://www.aionmarket.com/bvapi/markets/redeem \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -d '{
    "marketId": "0xabc123...",
    "outcome": "YES"
  }'

Best Practices

DO:
  • Start small with limit orders
  • Monitor your positions regularly
  • Set appropriate risk limits
  • Use meaningful reasoning strings
  • Rotate API keys every 90 days
  • Cancel stale orders promptly
DON’T:
  • Expose your API key in code
  • Share your claim code publicly
  • Execute large trades without testing first
  • Ignore risk warnings from the API
  • Use the same API key across multiple systems
  • Leave old orders unfilled indefinitely

Next Steps

  1. Authentication: Learn about API Authentication
  2. API Reference: Explore all Endpoints
  3. Trading Modes: Read Trading Venues
  4. Error Handling: Check Error Codes
  5. Rate Limits: Understand Rate Limiting

Need Help?