EventTrader
AI-Native Trading
PAPER
Menu
Dark Mode
Plain English Mode

[ 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 cymetica-eventtrader
Bash
# JavaScript/TypeScript SDK — npm release in progress; Python SDK is live today:
pip install cymetica-eventtrader

2. Initialize the Client

Python
import asyncio
import os

from event_trader import EventTrader  # pip install cymetica-eventtrader

async def main():
    async with EventTrader(
        api_key=os.environ["EVENT_TRADER_API_KEY"],
        base_url="https://cymetica.com",
    ) as client:
        # Fetch all active markets
        markets = await client.markets.list(status="active")
        for market in markets:
            print(f"{market.name}: {market.contract_address}")

asyncio.run(main())
JavaScript
import { EventTrader } from 'cymetica-eventtrader';

// Initialize with your API key
const client = new EventTrader({
    baseUrl: 'https://cymetica.com/api',
    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" \
     "https://cymetica.com/api/v1/markets?status=active"
Tip: Get a free API key from the API Docs page or your Account settings.

🔐 Authentication

Market data (markets, prices, orderbooks) is public — no key needed. Account-specific and trading requests require an API key.

Generate an API Key

cURL
# Generate a new API key
curl -X POST "https://cymetica.com/api/v1/api-keys" \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer YOUR_JWT_TOKEN" \
     -d '{"name": "My Trading Bot", "permissions": {"read": true, "trade": true, "withdraw": false}}'

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(
        "https://cymetica.com/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
import asyncio
import os

from event_trader import (
    APIError,
    EventTrader,
    NotFoundError,
    RateLimitError,
    ValidationError,
)

async def main():
    async with EventTrader(api_key=os.environ["EVENT_TRADER_API_KEY"]) as client:
        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.field_errors}")
        except APIError as e:
            print(f"API error {e.status_code}: {e.message}")

asyncio.run(main())

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 Trade

Trade on which asset will win in a prediction market.

Python
# Trade on Bitcoin with a market order — identity comes from your
# API key; there is no user_id parameter anywhere in the SDK.
order = await client.trading.place_order(
    market_id="0x1234...",
    asset="BTC",
    side="buy",
    price=0,  # ignored for market orders
    quantity=100.0,
    order_type="market",
)

print(f"✅ Trade placed!")
print(f"   Order ID: {order.id}")
print(f"   Asset: {order.asset}")
print(f"   Quantity: {order.quantity}")
print(f"   Odds: {trade.current_odds:.2f}")
Important: Trades 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 — identity comes from your API key
order = await client.trading.place_order(
    market_id="0x1234...",
    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 for the authenticated account
orders = await client.trading.open_orders(
    market_id="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 = "wss://cymetica.com/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('wss://cymetica.com/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
# Poll many prices in one call...
prices = await client.prices.get_many(["BTC", "ETH", "SOL"])
for symbol, price in prices.items():
    print(f"{symbol}: ${price.price:,.2f}")

# ...or stream a market's live order book over WebSocket
stream = client.streaming.orderbook("0x1234...", "BTC")
async for update in stream:
    print(f"best bid {update.best_bid} / best ask {update.best_ask}")

Get Single Price

cURL
# Get current BTC price
curl -H "X-API-Key: your-key" \
     "https://cymetica.com/api/v1/prices/BTC"

Bulk Price Request

cURL
# Get multiple prices at once
curl -H "X-API-Key: your-key" \
     "https://cymetica.com/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 to extract relevant assets from a prompt (REST — not yet in the SDK)
import httpx
import os

resp = httpx.post(
    "https://cymetica.com/api/v1/ai_trading_agent/prompt-assets",
    headers={"X-API-Key": os.environ["EVENT_TRADER_API_KEY"]},
    json={"prompt": "cryptocurrencies related to DeFi and smart contracts"},
    timeout=30,
)
resp.raise_for_status()

print("🧠 AI Asset Recommendations:")
for symbol in resp.json()["symbols"]:
    print(f" - {symbol}")

URL Content Analysis

Python
# Analyze how news affects specific assets (REST — not yet in the SDK)
import httpx
import os

resp = httpx.post(
    "https://cymetica.com/api/v1/ai_trading_agent/analyze-url-assets",
    headers={"X-API-Key": os.environ["EVENT_TRADER_API_KEY"]},
    json={
        "url": "https://example.com/bitcoin-etf-news",
        "assets": ["BTC", "ETH", "SOL"],
    },
    timeout=60,
)
resp.raise_for_status()
analysis = resp.json()
print(analysis)
Powered by: Proprietary AI with advanced cryptocurrency market knowledge.

📉 Technical Indicators

Calculate technical analysis indicators for any cryptocurrency.

MACD Indicator

Python
# Get technical indicators (MACD) for Bitcoin
ta = await client.prices.indicators("BTC", indicators=["macd"], interval="1h")

print(f"📊 Technical Analysis: {ta.asset}")
print(ta)
print(f"   {macd.interpretation.description}")

cURL Example

cURL
curl -H "X-API-Key: your-key" \
     "https://cymetica.com/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="https://cymetica.com",
    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.