v1.3.0 Last updated: December 2024

XO Markets API Documentation

Welcome to the XO Markets API documentation. Build prediction market trading applications with our comprehensive, institution-grade API.

About XO Markets

XO Markets is the leading prediction market infrastructure provider, offering a robust API that enables developers to embed prediction market trading functionality into their applications.

Key Features

Use Cases

Use Case Description
Trading Apps Build consumer-facing apps that let users trade on world events
Research Platforms Access probability data for forecasting and analysis
Portfolio Management Integrate event risk into investment strategies
Algorithmic Trading Build automated trading strategies on prediction markets

Quick Start

Step 1: Create an Account

Sign up for an XO Markets account at app.xotrade.co. You'll receive API credentials immediately upon registration.

Step 2: Get Your API Keys

After registration, navigate to the API Keys section in your dashboard.

Environment Base URL Purpose
Sandbox https://sandbox.xotrade.co/v1 Testing and development
Production https://api.xotrade.co/v1 Live trading
Important: Never expose your API Secret Key in client-side code or public repositories.

Step 3: Install the SDK

Python
pip install xo-trade
TypeScript / Node.js
npm install @xo-trade/sdk

Step 4: Make Your First Request

Python
from xo_trade import XO

# Initialize client
client = XO.Client(
    api_key='pk_live_your_key',
    api_secret='sk_live_your_secret'
)

# Get account info
account = client.get_account()
print(f"Balance: ${account.balance}")
print(f"Buying Power: ${account.buying_power}")

# List available markets
markets = client.list_markets(status='open', limit=10)
for market in markets:
    print(f"{market.title}: {market.outcomes}")
TypeScript
import { XOClient } from '@xo-trade/sdk';

const client = new XOClient({
  apiKey: 'pk_live_your_key',
  apiSecret: 'sk_live_your_secret'
});

// Get account info
const account = await client.getAccount();
console.log(`Balance: $${account.balance}`);

// List available markets
const markets = await client.listMarkets({ status: 'open', limit: 10 });
markets.forEach(m => console.log(`${m.title}: ${m.outcomes}`));

Authentication

All API requests require authentication via your API credentials. XO Markets uses HMAC-SHA256 signatures for secure request authentication.

Required Headers

Header Description
XO-API-KEY Your API Key ID
XO-TIMESTAMP Current Unix timestamp (seconds)
XO-SIGNATURE HMAC-SHA256 signature

Signature Generation

Python
import hmac
import hashlib
import time

def generate_signature(secret_key, timestamp, method, path, body=''):
    message = f"{timestamp}{method}{path}{body}"
    signature = hmac.new(
        secret_key.encode(),
        message.encode(),
        hashlib.sha256
    ).hexdigest()
    return signature
Tip: The SDKs handle authentication automatically. Manual signature generation is only needed for direct API calls.

Core Concepts

Markets

A market represents a question about a future event. Each market has:

Outcomes

An outcome is a possible result of a market:

Positions

A position represents your holdings in a specific outcome:

Orders

An order is an instruction to buy or sell shares:

Order Type Description
market Execute immediately at best available price
limit Execute at specified price or better
GTC Good-Til-Canceled: remains open until filled or canceled
IOC Immediate-Or-Cancel: fill immediately or cancel
FOK Fill-Or-Kill: fill entirely or cancel

API Reference

Account

Get Account

Retrieve account information including balance and buying power.

GET /v1/account
Response
{
  "id": "acc_8a9b2c3d",
  "email": "trader@example.com",
  "status": "active",
  "balance": 10000.00,
  "buying_power": 8500.00,
  "pending_orders_value": 1500.00,
  "realized_pnl": 2340.50,
  "unrealized_pnl": -150.00,
  "created_at": "2024-01-15T10:30:00Z"
}

Markets

List Markets

Retrieve available prediction markets.

GET /v1/markets

Query Parameters

Parameter Type Description
status string Filter by status: open, closed, resolved
category string Filter by category: politics, finance, sports, etc.
search string Search by title or description
limit integer Max results (default: 50, max: 500)
Response
{
  "markets": [
    {
      "id": "us-election-2028",
      "title": "Who will win the 2028 US Presidential Election?",
      "category": "politics",
      "status": "open",
      "volume_24h": 1250000.00,
      "total_volume": 45000000.00,
      "outcomes": [
        { "id": "vance", "name": "JD Vance", "price": 0.35 },
        { "id": "newsom", "name": "Gavin Newsom", "price": 0.28 },
        { "id": "other", "name": "Other", "price": 0.37 }
      ]
    }
  ],
  "next_cursor": "eyJpZCI6InVzLWVsZWN0aW9uLTIwMjgifQ=="
}

Get Market

GET /v1/markets/{market_id}

Get Order Book

GET /v1/markets/{market_id}/outcomes/{outcome_id}/orderbook

Orders

Place Order

Submit a new order.

POST /v1/orders
Request Body
{
  "market_id": "us-election-2028",
  "outcome_id": "vance",
  "side": "buy",
  "type": "limit",
  "amount_usd": 5000.00,
  "limit_price": 0.35,
  "time_in_force": "GTC",
  "client_order_id": "my-order-123"
}

Parameters

Parameter Type Required Description
market_id string Yes Market identifier
outcome_id string Yes Outcome identifier
side string Yes buy or sell
type string Yes market or limit
amount_usd number Yes Order size in USD
limit_price number For limit Price between 0.01-0.99

List Orders

GET /v1/orders

Cancel Order

DELETE /v1/orders/{order_id}

Positions

List Positions

GET /v1/positions
Response
{
  "positions": [
    {
      "market_id": "us-election-2028",
      "market_title": "Who will win the 2028 US Presidential Election?",
      "outcome_id": "vance",
      "outcome_name": "JD Vance",
      "side": "long",
      "qty": 14285.71,
      "avg_entry_price": 0.35,
      "current_price": 0.38,
      "market_value": 5428.57,
      "cost_basis": 5000.00,
      "unrealized_pnl": 428.57,
      "unrealized_pnl_percent": 8.57
    }
  ]
}

Close Position

DELETE /v1/positions/{market_id}/{outcome_id}

WebSocket Streaming

XO Markets provides real-time streaming data via WebSocket connections.

Connection

WebSocket URL
wss://stream.xotrade.co/v1

Subscribe to Market Data

Subscribe Message
{
  "action": "subscribe",
  "channel": "market",
  "market_id": "us-election-2028"
}

Python Example

Python
import asyncio
from xo_trade import XO

async def main():
    client = XO.Client('pk_live_your_key', 'sk_live_your_secret')
    
    async def on_price(data):
        print(f"{data['outcome_id']}: {data['price']:.2%}")
    
    # Subscribe to market prices
    await client.stream.subscribe('market', 'us-election-2028', on_price)
    
    # Keep connection alive
    await client.stream.run_forever()

asyncio.run(main())

Sandbox Environment

Use the sandbox environment for development and testing without risking real funds.

Sandbox Features

Environment URL
API https://sandbox.xotrade.co/v1
WebSocket wss://sandbox-stream.xotrade.co/v1

SDKs & Tools

Official SDKs

Language Package Install
Python xo-trade pip install xo-trade
TypeScript @xo-trade/sdk npm install @xo-trade/sdk
C++ xo-trade vcpkg install xo-trade

Community Libraries

Rate Limits

Tier Requests/Minute WebSocket Connections
Free 100 1
Starter 300 3
Pro 1,000 10
Enterprise Unlimited Unlimited

Rate limit headers are included in every response:

Response Headers
X-RateLimit-Limit: 300
X-RateLimit-Remaining: 295
X-RateLimit-Reset: 1699900060

Error Handling

HTTP Status Codes

Code Meaning
200Success
201Created
400Bad Request - Invalid parameters
401Unauthorized - Invalid credentials
403Forbidden - Insufficient permissions
404Not Found - Resource doesn't exist
429Too Many Requests - Rate limited
500Internal Server Error

Error Response Format

JSON
{
  "error": {
    "code": "insufficient_balance",
    "message": "Insufficient buying power for this order",
    "details": {
      "required": 5000.00,
      "available": 2500.00
    }
  },
  "request_id": "req_a1b2c3d4"
}

FAQ

General

What are prediction markets?

Prediction markets are exchange-traded markets where participants buy and sell shares based on the outcome of future events. Share prices reflect the market's collective probability estimate.

How do payouts work?

Each share pays $1 if the outcome occurs, $0 otherwise. If you buy "Yes" shares at $0.35 and the outcome happens, you receive $1 per share (profit of $0.65/share).

Trading

What are the trading hours?

Markets are open 24/7, 365 days a year. Individual markets may close before their resolution date.

What's the minimum order size?

The minimum order is $1.00 USD.

Are there trading fees?

XO Markets charges no commission on trades. There is a small spread built into market prices.

Technical

What's the API latency?

Median order execution latency is under 50ms. WebSocket updates are delivered within 10ms of market changes.