[ 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
pip install event-trader
npm install @event-trader/sdk
2. Initialize the Client
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}")
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}`);
});
# List all active markets
curl -H "X-API-Key: your-api-key-here" \
"http://localhost:8000/api/v1/markets?status=active"
user-secret-key
š Authentication
All API requests require authentication using an API key.
Generate an API Key
# 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
Using Your API Key
# 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()
ā ļø Error Handling
Handle API errors gracefully in your applications.
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
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.
# 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
# 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.
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}")
š Get Market Results
Retrieve current standings and winner for a market.
# 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
š° Place a Bet
Bet on which asset will win in a prediction market.
# 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}")
š Order Book
View the order book with bids and asks for any asset.
# 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
š Limit Orders
Place and manage limit orders on the order book.
Place a Limit Order
# 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
# 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
# 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
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
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.
# 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
# Get current BTC price
curl -H "X-API-Key: your-key" \
"http://localhost:8000/api/v1/prices/BTC"
Bulk Price Request
# 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.
# 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
# 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
# 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
# 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
# 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.
# 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
# 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
# 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()
š Technical Indicators
Calculate technical analysis indicators for any cryptocurrency.
MACD Indicator
# 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 -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
# 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
# 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%}")