Bot Integration Guide
Build automated betting bots with Cap Bet's API and SDK
Bot Integration Guide
Learn how to build automated betting bots that interact with Cap Bet's platform.
Overview
Cap Bet provides multiple ways to build automated bots:
- REST API: HTTP-based API for standard operations
- WebSocket API: Real-time market updates
- Smart Contract SDK: Direct on-chain interactions
- MCP Integration: AI-powered decision making
Bot Types
1. Market Maker Bot
Provides liquidity by creating and maintaining betting markets:
import { CapBetClient } from '@capbet/sdk';
class MarketMakerBot {
private client: CapBetClient;
async createMarket(title: string, lockTime: Date) {
return await this.client.markets.create({
title,
lockTime,
minBetAmount: 0.1,
maxBetAmount: 100,
});
}
async monitorMarkets() {
const markets = await this.client.markets.getAll({
status: 'active',
});
for (const market of markets) {
await this.balanceLiquidity(market);
}
}
}2. Arbitrage Bot
Identifies and exploits price discrepancies:
class ArbitrageBot {
async findOpportunities() {
const markets = await this.client.markets.getAll();
for (const market of markets) {
const odds = this.calculateOdds(market);
if (odds.yes < 0.5 && this.externalOdds(market) > 0.6) {
await this.placeBet(market.id, 'yes', 10);
}
}
}
}3. Analytics Bot
Monitors markets and provides insights:
class AnalyticsBot {
async trackMarkets() {
const ws = this.client.connectWebSocket();
ws.on('market:update', (market) => {
this.analyzeMarket(market);
this.sendAlert(market);
});
}
}WebSocket Integration
Subscribe to real-time updates:
import { CapBetWebSocket } from '@capbet/sdk';
const ws = new CapBetWebSocket({
url: 'wss://api.cap.bet/ws',
apiKey: process.env.API_KEY,
});
// Subscribe to market updates
ws.subscribe('markets', (data) => {
console.log('Market update:', data);
});
// Subscribe to position updates
ws.subscribe('positions', (data) => {
console.log('Position update:', data);
});
// Connect
await ws.connect();Event Types
Market Events
// Market created
{
type: 'market:created',
data: {
marketId: 'market_123',
title: 'Will SOL reach $200?',
creator: 'ABC123...',
}
}
// Position taken
{
type: 'market:position',
data: {
marketId: 'market_123',
user: 'XYZ789...',
side: 'yes',
amount: 10,
}
}
// Market resolved
{
type: 'market:resolved',
data: {
marketId: 'market_123',
result: true,
timestamp: '2024-10-19T12:00:00Z',
}
}Best Practices
1. Rate Limiting
Implement exponential backoff:
class RateLimiter {
private attempts = 0;
private maxAttempts = 5;
async executeWithBackoff(fn: () => Promise<any>) {
try {
return await fn();
} catch (error) {
if (this.attempts < this.maxAttempts) {
this.attempts++;
await this.sleep(Math.pow(2, this.attempts) * 1000);
return this.executeWithBackoff(fn);
}
throw error;
}
}
private sleep(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
}
}2. Error Handling
class BotClient {
async executeTrade(marketId: string, side: string, amount: number) {
try {
const result = await this.client.positions.create({
marketId,
side,
amount,
});
this.logger.info('Trade executed', result);
return result;
} catch (error) {
if (error.code === 'INSUFFICIENT_FUNDS') {
this.logger.error('Insufficient funds');
await this.notifyOwner('Insufficient funds');
}
throw error;
}
}
}3. Position Management
Track open positions:
class PositionManager {
private positions = new Map();
async updatePositions() {
const positions = await this.client.positions.getAll();
for (const position of positions) {
this.positions.set(position.id, position);
if (this.shouldClose(position)) {
await this.closePosition(position);
}
}
}
}Security Considerations
- API Keys: Store securely in environment variables
- Private Keys: Use hardware wallets or secure key management
- Monitoring: Implement alerts for unusual activity
- Rate Limits: Respect API rate limits
- Error Handling: Gracefully handle failures
Example: Complete Bot
import { CapBetClient, CapBetWebSocket } from '@capbet/sdk';
class TradingBot {
private client: CapBetClient;
private ws: CapBetWebSocket;
private positions = new Map();
constructor() {
this.client = new CapBetClient({
apiKey: process.env.API_KEY,
});
}
async start() {
// Initialize WebSocket
this.ws = new CapBetWebSocket({ url: 'wss://api.cap.bet/ws' });
// Subscribe to events
this.ws.subscribe('markets', this.handleMarketUpdate.bind(this));
// Connect
await this.ws.connect();
// Start monitoring
setInterval(() => this.updatePositions(), 60000);
}
private async handleMarketUpdate(market: any) {
if (this.shouldTrade(market)) {
await this.executeTrade(market);
}
}
private shouldTrade(market: any): boolean {
// Implement your trading logic
return true;
}
private async executeTrade(market: any) {
try {
const position = await this.client.positions.create({
marketId: market.id,
side: 'yes',
amount: 10,
});
this.positions.set(position.id, position);
} catch (error) {
console.error('Trade failed:', error);
}
}
}
// Start bot
const bot = new TradingBot();
bot.start();