EXAMPLES
20+
LANGUAGES
3

[ Examples & Tutorials ]

Learn how to integrate EVENT TRADER into your applications with comprehensive code examples in Python, JavaScript, and cURL.

⚔ Quick Start

Get up and running with EVENT TRADER in under 5 minutes.

1. Install the SDK

Bash
pip install event-trader
Bash
npm install @event-trader/sdk

2. Initialize the Client

Python
from event_trader import EventTraderClient

# Initialize with your API key
client = EventTraderClient(
    base_url="http://localhost:8000",
    api_key="your-api-key-here"
)

# Fetch all active markets
markets = await client.markets.list(status="active")
for market in markets:
    print(f"{market.name}: {market.contract_address}")
JavaScript
import { EventTraderClient } from '@event-trader/sdk';

// Initialize with your API key
const client = new EventTraderClient({
    baseUrl: 'http://localhost:8000',
    apiKey: 'your-api-key-here'
});

// Fetch all active markets
const markets = await client.markets.list({ status: 'active' });
markets.forEach(market => {
    console.log(`${market.name}: ${market.contract_address}`);
});
cURL
# List all active markets
curl -H "X-API-Key: your-api-key-here" \
     "http://localhost:8000/api/v1/markets?status=active"
Tip: Get a free API key from the API Docs page or use the default testing key: user-secret-key

šŸ” Authentication

All API requests require authentication using an API key.

Generate an API Key

cURL
# Generate a new API key
curl -X POST "http://localhost:8000/api/v1/api_keys/generate" \
     -H "Content-Type: application/json" \
     -d '{"name": "My Trading Bot", "tier": "standard"}'

Response

{ "key": "evt_a1b2c3d4e5f6...", "name": "My Trading Bot", "tier": "standard", "rate_limit_per_minute": 100, "created_at": "2025-01-15T10:30:00Z" }

Using Your API Key

Python
# Pass API key in header for all requests
import httpx

headers = {"X-API-Key": "evt_a1b2c3d4e5f6..."}

async with httpx.AsyncClient() as client:
    response = await client.get(
        "http://localhost:8000/api/v1/markets",
        headers=headers
    )
    markets = response.json()
Security: Never expose your API key in client-side code or public repositories. Store keys securely as environment variables.

āš ļø Error Handling

Handle API errors gracefully in your applications.

Python
from event_trader import EventTraderClient
from event_trader.exceptions import (
    APIError,
    NotFoundError,
    RateLimitError,
    ValidationError
)

client = EventTraderClient(api_key="your-key")

try:
    market = await client.markets.get("0xinvalid")
except NotFoundError as e:
    print(f"Market not found: {e.message}")
except RateLimitError as e:
    print(f"Rate limited. Retry after {e.retry_after}s")
except ValidationError as e:
    print(f"Invalid request: {e.errors}")
except APIError as e:
    print(f"API error {e.status_code}: {e.message}")

Error Response Format

{ "error": { "code": "MARKET_NOT_FOUND", "message": "Market with contract address 0xinvalid not found", "details": {} } }

Common Error Codes

400 - Bad Request

Invalid parameters or malformed request body

401 - Unauthorized

Missing or invalid API key

404 - Not Found

Resource doesn't exist

429 - Rate Limited

Too many requests, slow down

šŸ“Š List Markets

Retrieve prediction markets with optional filtering and pagination.

Python
# List active crypto markets
markets = await client.markets.list(
    status="active",
    asset_type="crypto",
    limit=50
)

for market in markets:
    print(f"šŸ“ˆ {market.name}")
    print(f"   Contract: {market.contract_address}")
    print(f"   Assets: {', '.join(market.assets)}")
    print(f"   Total Volume: ${market.total_pool:,.2f}")
    print(f"   Ends: {market.end_time}")
    print()

Pagination with Cursor

Python
# Paginate through all markets
cursor = None
all_markets = []

while True:
    response = await client.markets.list(
        limit=100,
        cursor=cursor
    )
    all_markets.extend(response.markets)

    if not response.cursor:
        break
    cursor = response.cursor

print(f"Total markets: {len(all_markets)}")

Filter Parameters

status

pending, active, completed

asset_type

crypto, stock

tickers

Comma-separated contract addresses

limit

Results per page (1-1000)

šŸŽÆ Create Market

Create a new prediction market with multiple assets.

Python
from datetime import datetime, timedelta

# Create a crypto prediction market
market = await client.markets.create(
    name="Q1 2025 Top Performer",
    description="Which cryptocurrency will have the highest gains in Q1 2025?",
    assets=["BTC", "ETH", "SOL", "AVAX", "LINK"],
    asset_type="crypto",
    token="USDC",
    start_time=datetime.utcnow(),
    end_time=datetime.utcnow() + timedelta(days=90),
    min_bet=10.0,
    max_bet=10000.0
)

print(f"āœ… Market created!")
print(f"   Contract: {market.contract_address}")
print(f"   Name: {market.name}")
Tip: Markets require at least 2 assets and cannot have overlapping time periods with identical configurations.

šŸ† Get Market Results

Retrieve current standings and winner for a market.

Python
# Get market results
results = await client.markets.results(contract_address)

print(f"šŸ“Š {results.market_name}")
print(f"Status: {results.status}")
print()

for i, asset in enumerate(results.standings, 1):
    medal = "šŸ„‡" if i == 1 else "🄈" if i == 2 else "šŸ„‰" if i == 3 else "  "
    change = "+" if asset.price_change_pct >= 0 else ""
    print(f"{medal} #{i} {asset.symbol}: {change}{asset.price_change_pct:.2f}%")

if results.winner:
    print(f"\nšŸ† Winner: {results.winner}")

Example Output

šŸ“Š Q4 2024 Crypto Champions Status: active šŸ„‡ #1 SOL: +45.23% 🄈 #2 AVAX: +32.15% šŸ„‰ #3 ETH: +18.67% #4 BTC: +12.34% #5 LINK: +8.91%

šŸ’° Place a Bet

Bet on which asset will win in a prediction market.

Python
# Place a bet on Bitcoin
bet = await client.trading.place_bet(
    contract_address="0x1234...",
    user_id="user_abc123",
    asset="BTC",
    amount=100.0
)

print(f"āœ… Bet placed!")
print(f"   Bet ID: {bet.id}")
print(f"   Asset: {bet.asset}")
print(f"   Amount: ${bet.amount}")
print(f"   Odds: {bet.current_odds:.2f}")
Important: Bets are final and cannot be cancelled once placed. Make sure to verify the market and asset before confirming.

šŸ“š Order Book

View the order book with bids and asks for any asset.

Python
# Get order book for BTC
orderbook = await client.markets.orderbook(
    contract_address="0x1234...",
    asset="BTC"
)

print("=== ORDER BOOK: BTC ===")
print(f"Spread: {orderbook.spread:.4f}")
print()

print("ASKS (Sell Orders)")
for ask in orderbook.asks[:5]:
    print(f"  {ask.price:.4f} | {ask.quantity:,.2f}")

print(f"\n--- Spread: {orderbook.spread:.4f} ---\n")

print("BIDS (Buy Orders)")
for bid in orderbook.bids[:5]:
    print(f"  {bid.price:.4f} | {bid.quantity:,.2f}")

Example Output

=== ORDER BOOK: BTC === Spread: 0.0200 ASKS (Sell Orders) 0.6800 | 500.00 0.6700 | 1,250.00 0.6600 | 800.00 --- Spread: 0.0200 --- BIDS (Buy Orders) 0.6400 | 1,000.00 0.6300 | 750.00 0.6200 | 2,000.00

šŸ“ Limit Orders

Place and manage limit orders on the order book.

Place a Limit Order

Python
# Place a buy limit order
order = await client.trading.place_order(
    contract_address="0x1234...",
    user_id="user_abc123",
    asset="BTC",
    side="buy",
    price=0.60,  # Buy at 60% probability
    quantity=500.0
)

print(f"āœ… Order placed!")
print(f"   Order ID: {order.id}")
print(f"   Side: {order.side.upper()}")
print(f"   Price: {order.price}")
print(f"   Quantity: {order.quantity}")
print(f"   Status: {order.status}")

View Open Orders

Python
# Get all open orders
orders = await client.trading.open_orders(
    user_id="user_abc123",
    contract_address="0x1234..."  # Optional: filter by market
)

for order in orders:
    print(f"{order.side.upper()} {order.asset} @ {order.price}")
    print(f"  Qty: {order.quantity} | Filled: {order.filled_quantity}")
    print()

Cancel an Order

Python
# Cancel a specific order
result = await client.trading.cancel_order(
    order_id="order_xyz789"
)

if result.success:
    print("āœ… Order cancelled successfully")
else:
    print(f"āŒ Failed to cancel: {result.error}")

šŸ”Œ WebSocket Real-Time Feeds

Subscribe to real-time market updates via WebSocket.

Connect to WebSocket

Python
import asyncio
import websockets
import json

async def connect_to_market():
    uri = "ws://localhost:8000/ws/market/0x1234..."

    async with websockets.connect(uri) as ws:
        print("āœ… Connected to WebSocket")

        # Subscribe to orderbook updates
        await ws.send(json.dumps({
            "action": "subscribe",
            "channel": "orderbook",
            "asset": "BTC"
        }))

        # Listen for updates
        async for message in ws:
            data = json.loads(message)

            if data["type"] == "orderbook_update":
                print(f"šŸ“Š Orderbook Update: {data['asset']}")
                print(f"   Best Bid: {data['best_bid']}")
                print(f"   Best Ask: {data['best_ask']}")

            elif data["type"] == "trade":
                print(f"šŸ’° Trade: {data['asset']}")
                print(f"   Price: {data['price']}")
                print(f"   Quantity: {data['quantity']}")

asyncio.run(connect_to_market())

JavaScript WebSocket

JavaScript
const ws = new WebSocket('ws://localhost:8000/ws/market/0x1234...');

ws.onopen = () => {
    console.log('āœ… Connected');

    // Subscribe to price updates
    ws.send(JSON.stringify({
        action: 'subscribe',
        channel: 'prices'
    }));
};

ws.onmessage = (event) => {
    const data = JSON.parse(event.data);

    switch(data.type) {
        case 'price_update':
            console.log(`šŸ’¹ ${data.asset}: $${data.price}`);
            break;
        case 'trade':
            console.log(`šŸ’° Trade: ${data.quantity} @ ${data.price}`);
            break;
    }
};

ws.onerror = (error) => console.error('WebSocket error:', error);
ws.onclose = () => console.log('Connection closed');

Available Channels

orderbook

Real-time order book updates (bids/asks)

trades

Live trade executions

prices

Asset price updates

market

Market status changes

šŸ“ˆ Price Streaming

Stream real-time cryptocurrency prices.

Python
# Stream prices using SDK
async for price in client.streaming.prices(["BTC", "ETH", "SOL"]):
    print(f"{price.symbol}: ${price.price:,.2f}")
    print(f"  24h Change: {price.change_24h:+.2f}%")
    print(f"  Volume: ${price.volume_24h:,.0f}")
    print()

Get Single Price

cURL
# Get current BTC price
curl -H "X-API-Key: your-key" \
     "http://localhost:8000/api/v1/prices/BTC"

Bulk Price Request

cURL
# Get multiple prices at once
curl -H "X-API-Key: your-key" \
     "http://localhost:8000/api/v1/prices?assets=BTC&assets=ETH&assets=SOL"

šŸ¤– Bot Registration

Register trading bots to earn rewards and track performance.

Python
# Register a new trading bot
bot = await client.incentives.register_bot(
    name="Alpha Market Maker",
    wallet_address="0x742d35Cc6634C0532925a3b844Bc9e7595f3E6",
    strategy_type="market_maker",
    description="High-frequency market making bot"
)

print(f"āœ… Bot registered!")
print(f"   Bot ID: {bot.id}")
print(f"   Tier: {bot.tier}")  # Starts at Bronze
print(f"   Status: {bot.status}")

Check Bot Tier Status

Python
# Get tier status and progression
tier = await client.incentives.tier_status(bot.id)

print(f"šŸ† Current Tier: {tier.current_tier}")
print(f"šŸ“Š Volume: ${tier.current_volume:,.2f}")
print(f"šŸŽÆ Next Tier: {tier.next_tier}")
print(f"šŸ“ˆ Progress: {tier.progress_percent:.1f}%")
print()
print(f"Benefits:")
print(f"  Fee Discount: {tier.fee_discount}%")
print(f"  Reward Multiplier: {tier.reward_multiplier}x")

Tier Benefits

šŸ„‰ Bronze

0% fee discount, 1x rewards

🄈 Silver

5% fee discount, 1.25x rewards

šŸ„‡ Gold

10% fee discount, 1.5x rewards

šŸ’Ž Diamond

20% fee discount, 2x rewards

šŸ”’ Staking

Stake tokens to earn yield with configurable lockup periods.

List Staking Pools

Python
# List available staking pools
pools = await client.incentives.list_staking_pools()

for pool in pools:
    print(f"šŸŠ {pool.name}")
    print(f"   Token: {pool.stake_token.symbol}")
    print(f"   Base APY: {pool.apy.base}%")
    print(f"   Max APY: {pool.apy.max}%")
    print(f"   Total Staked: {pool.pool_stats.total_staked:,.2f}")
    print()

Stake Tokens

Python
# Stake with 90-day lockup for bonus APY
stake = await client.incentives.stake(
    pool_id="pool_pred_main",
    wallet="0x742d35Cc6634C0532925a3b844Bc9e7595f3E6",
    amount=1000.0,
    lockup_days=90  # 90-day lock = +15% bonus APY
)

print(f"āœ… Staked successfully!")
print(f"   Stake ID: {stake.stake_id}")
print(f"   Amount: {stake.amount}")
print(f"   Effective APY: {stake.effective_apy}%")
print(f"   Voting Power: {stake.voting_power}")
print(f"   Lockup Ends: {stake.timing.lockup_ends_at}")

Claim Rewards

Python
# Check pending rewards
rewards = await client.incentives.calculate_staking_rewards(stake.stake_id)
print(f"šŸ’° Pending: {rewards.pending_rewards}")

# Claim rewards
claim = await client.incentives.claim_staking_rewards(
    stake_id=stake.stake_id,
    wallet="0x742d35Cc..."
)
print(f"āœ… Claimed: {claim.amount} {claim.reward_token.symbol}")

Lockup Tiers

Lockup Period Bonus APY Voting Power
Flexible (0 days) +0% 1.0x
30 days +5% 1.25x
90 days +15% 1.5x
180 days +25% 2.0x
365 days +40% 3.0x

šŸ… Leaderboards

View top traders and bots across different time periods.

Python
# Get weekly volume leaderboard
leaderboard = await client.incentives.leaderboard(
    period="weekly",
    metric="volume",
    limit=10
)

print(f"šŸ† {leaderboard.period.upper()} LEADERBOARD")
print(f"Metric: {leaderboard.metric}")
print()

for entry in leaderboard.entries:
    medal = "šŸ„‡" if entry.rank == 1 else "🄈" if entry.rank == 2 else "šŸ„‰" if entry.rank == 3 else "  "
    change = f"↑{entry.rank_change}" if entry.rank_change > 0 else f"↓{abs(entry.rank_change)}" if entry.rank_change < 0 else "–"

    print(f"{medal} #{entry.rank} {entry.bot_name}")
    print(f"   Volume: ${entry.volume:,.2f}")
    print(f"   PnL: ${entry.pnl:,.2f}")
    print(f"   Change: {change}")
    print()

Leaderboard Options

Periods

daily, weekly, monthly, all_time

Metrics

volume, trades, earnings, pnl

🧠 AI Analysis

Use AI-powered analysis to get asset recommendations.

Prompt-Based Analysis

Python
# Ask AI for asset recommendations
response = await client.ai.prompt_assets(
    prompt="What are the best DeFi tokens for yield farming?",
    user_id="user_123"
)

print("🧠 AI Asset Recommendations:")
print()

for asset in response.assets:
    confidence = "🟢" if asset.probability > 0.8 else "🟔" if asset.probability > 0.5 else "šŸ”“"
    print(f"{confidence} {asset.symbol} ({asset.probability:.0%})")
    print(f"   {asset.explanation}")
    print()

URL Content Analysis

Python
# Analyze how news affects specific assets
analysis = await client.ai.analyze_url(
    url="https://example.com/bitcoin-etf-news",
    assets=["BTC", "ETH", "SOL"]
)

print(f"šŸ“° {analysis.headline}")
print(f"Impact: {analysis.overall_market_impact}")
print()

for asset in analysis.asset_analyses:
    impact = "šŸ“ˆ" if asset.impact_direction == "positive" else "šŸ“‰" if asset.impact_direction == "negative" else "āž–"
    print(f"{impact} {asset.symbol}: {asset.relationship}")
    print(f"   Relevance: {asset.relevance_score:.0%}")
    print(f"   {asset.analysis}")
    print()
Powered by: Claude Sonnet 4 with advanced cryptocurrency market knowledge.

šŸ“‰ Technical Indicators

Calculate technical analysis indicators for any cryptocurrency.

MACD Indicator

Python
# Get MACD for Bitcoin
macd = await client.indicators.macd(
    symbol="BTC",
    days=90,
    fast_period=12,
    slow_period=26,
    signal_period=9
)

print(f"šŸ“Š MACD Analysis: {macd.symbol}")
print(f"Current Price: ${macd.metadata.current_price:,.2f}")
print()
print(f"MACD Line: {macd.current.macd:.2f}")
print(f"Signal Line: {macd.current.signal:.2f}")
print(f"Histogram: {macd.current.histogram:.2f}")
print(f"Trend: {macd.current.trend}")
print()
print(f"šŸ“ˆ Signal: {macd.interpretation.signal}")
print(f"   Strength: {macd.interpretation.strength}")
print(f"   {macd.interpretation.description}")

cURL Example

cURL
curl -H "X-API-Key: your-key" \
     "http://localhost:8000/api/v1/technical_indicators/macd/BTC?days=90"

šŸ¤– Trading Bot

Run an automated trading bot for market making.

Basic Usage

Bash
# Trade all active markets with $100 budget
python3 trading_bot.py --single-run --budget 100

# Trade a specific market
python3 trading_bot.py --contracts 0x1234... --budget 200

# Filter markets by name
python3 trading_bot.py --name-filter "crypto" --budget 150

# Run continuously
python3 trading_bot.py --budget 500 --interval 60

Bot Configuration

Python
# Custom bot configuration
from trading_bot import TradingBot, BotConfig

config = BotConfig(
    api_key="your-api-key",
    base_url="http://localhost:8000",
    strategy="market_maker",
    budget=1000.0,
    risk_tolerance=0.05,  # 5% max loss per trade
    spread_target=0.02,   # 2% spread
    rebalance_interval=300  # 5 minutes
)

bot = TradingBot(config)

# Run the bot
await bot.start()

# Monitor performance
stats = await bot.get_stats()
print(f"PnL: ${stats.total_pnl:,.2f}")
print(f"Trades: {stats.total_trades}")
print(f"Win Rate: {stats.win_rate:.1%}")
Risk Warning: Automated trading involves risk. Start with small amounts and monitor performance closely. Past performance does not guarantee future results.