---
slug: "arbibot"
source_type: "readme"
source_url: "https://cdn.jsdelivr.net/gh/axwelbrand-byte/arbibot@master/README.md"
repo: "https://github.com/axwelbrand-byte/arbibot"
source_file: "README.md"
branch: "master"
---
# ArbiBot - Sports & Esports Arbitrage Bot for Kalshi & Polymarket

An automated arbitrage bot focused on **sports and esports markets** that identifies and executes profit opportunities between Kalshi and Polymarket.

## 🎮⚽ Sports & Esports Focus

This bot **exclusively monitors sports and esports markets** for the following:

**Esports:**
- **CS2** (Counter-Strike 2)
- **League of Legends**
- **Valorant**
- **Dota 2**
- **Call of Duty** (CoD, Warzone)

**Traditional Sports:**
- **NBA** (Basketball)
- **Soccer** (Football, Premier League, UEFA, Champions League)
- **NFL** (American Football)
- **Tennis** (ATP, WTA, Grand Slams)
- **MMA** (UFC, Bellator)

## Overview

ArbiBot continuously monitors sports and esports markets on both Kalshi and Polymarket to identify arbitrage opportunities. The bot:

- Fetches active sports/esports markets from both platforms (live and upcoming matches/games)
- Filters for high-liquidity markets (minimum $100 volume)
- Matches similar markets across platforms using intelligent name matching
- Detects arbitrage opportunities using proven strategies
- Executes trades automatically (when enabled)
- Monitors active positions and cancels stale orders
- Tracks profit and loss
- **Portfolio Allocation**: 70% for near-term markets (<24hrs), 30% for future markets

## Features

- **🎮⚽ Sports & Esports Focus**: Monitors esports (CS2, LoL, Valorant, Dota 2, CoD) and traditional sports (NBA, Soccer, NFL, Tennis, MMA)
- **💧 Liquidity Filtering**: Only trades on markets with $100+ volume for real execution capability
- **📊 Portfolio Allocation Strategy**:
  - 70% allocated to near-term markets (live or resolving within 24 hours)
  - 30% allocated to future markets (higher profit threshold required)
  - Prevents liquidity from getting locked up long-term
- **Cross-Platform Arbitrage**: Only looks for opportunities between Kalshi and Polymarket (not within a single platform)
- **Valid Arbitrage Strategy**:
  - Buy opposing outcomes (YES + NO) across platforms
  - Total cost < $1.00 guarantees profit (one outcome must pay $1.00)
  - No existing positions required
- **Paper Trading Mode**: Test strategies with simulated money before risking real capital
- **Telegram Notifications**: Real-time alerts for opportunities and hourly performance summaries
- **Intelligent Market Matching**: Recognizes team/player names and match formats across platforms
- **Risk Management**: Configurable profit thresholds and position size limits
- **Order Management**: Automatically cancels stale orders to prevent losses
- **Profit Tracking**: Real-time tracking of executed trades and profits

## Installation

1. Clone the repository:
```bash
git clone <repository-url>
cd ArbiBot
```

2. Install dependencies:
```bash
npm install
```

3. Configure environment variables:
```bash
cp .env.example .env
```

Edit `.env` with your API credentials and preferences.

## Quick Start (Paper Trading)

The safest way to test ArbiBot is with paper trading mode:

1. Install dependencies:
```bash
npm install
```

2. Copy the example configuration:
```bash
cp .env.example .env
```

3. Set up Telegram notifications (optional but recommended):
   - See [TELEGRAM_SETUP.md](https://github.com/axwelbrand-byte/arbibot/blob/HEAD/TELEGRAM_SETUP.md) for detailed instructions
   - Or skip this step to run without notifications

4. Edit `.env` and set:
```env
PAPER_TRADING_MODE=true
STARTING_BALANCE=1000
ENABLE_TELEGRAM_NOTIFICATIONS=true  # if you set up Telegram
TELEGRAM_BOT_TOKEN=your_bot_token    # from @BotFather
TELEGRAM_CHAT_ID=your_chat_id        # your Telegram user ID
```

5. Run the bot:
```bash
npm run dev
```

6. Monitor results in console and Telegram!

## Configuration

Create a `.env` file with the following variables:

```env
# Kalshi API Configuration
KALSHI_API_KEY=your_kalshi_api_key_here
KALSHI_PRIVATE_KEY=your_kalshi_private_key_here
KALSHI_API_URL=https://api.elections.kalshi.com/trade-api/v2

# Polymarket API Configuration
POLYMARKET_API_KEY=your_polymarket_api_key_here
POLYMARKET_PRIVATE_KEY=your_polymarket_private_key_here
POLYMARKET_API_URL=https://clob.polymarket.com

# Bot Configuration
MIN_PROFIT_THRESHOLD=0.02        # Minimum 2% profit required
MAX_POSITION_SIZE=100            # Maximum $100 per trade
CHECK_INTERVAL_MS=5000           # Check every 5 seconds
ENABLE_TRADING=false             # Set to true to execute real trades
PAPER_TRADING_MODE=true          # Use simulated money for testing
STARTING_BALANCE=1000            # Starting balance for paper trading

# Telegram Configuration
TELEGRAM_BOT_TOKEN=your_telegram_bot_token_here
TELEGRAM_CHAT_ID=your_chat_id_here
ENABLE_TELEGRAM_NOTIFICATIONS=true
HOURLY_SUMMARY_ENABLED=true

# Logging
LOG_LEVEL=info                   # Log level: debug, info, warn, error
```

### Configuration Options

**Bot Settings:**
- `MIN_PROFIT_THRESHOLD`: Minimum profit percentage required to execute a trade (e.g., 0.02 = 2%)
- `MAX_POSITION_SIZE`: Maximum amount to invest in a single arbitrage opportunity
- `CHECK_INTERVAL_MS`: How often to scan for opportunities (in milliseconds)
- `ENABLE_TRADING`: Set to `false` for dry-run mode, `true` to execute real trades
- `LOG_LEVEL`: Verbosity of logging (debug, info, warn, error)

**Paper Trading Settings:**
- `PAPER_TRADING_MODE`: Set to `true` to use simulated money (recommended for testing)
- `STARTING_BALANCE`: Starting balance for paper trading (e.g., 1000 = $1,000)

**Telegram Settings:**
- `TELEGRAM_BOT_TOKEN`: Your Telegram bot token from @BotFather
- `TELEGRAM_CHAT_ID`: Your Telegram user ID (see [TELEGRAM_SETUP.md](https://github.com/axwelbrand-byte/arbibot/blob/HEAD/TELEGRAM_SETUP.md))
- `ENABLE_TELEGRAM_NOTIFICATIONS`: Set to `true` to receive notifications
- `HOURLY_SUMMARY_ENABLED`: Set to `true` to receive hourly performance summaries

## Getting API Keys

### Kalshi

1. Sign up at [kalshi.com](https://kalshi.com)
2. Navigate to Profile Settings
3. Click "Create New API Key"
4. Save your API key and private key

### Polymarket

1. Sign up at [polymarket.com](https://polymarket.com)
2. Access the API documentation to generate credentials
3. Save your API key and private key

## Usage

### Development Mode

Run the bot with hot-reloading:

```bash
npm run dev
```

### Production Mode

Build and run the bot:

```bash
npm run build
npm start
```

### Watch Mode

Compile TypeScript in watch mode:

```bash
npm run watch
```

## How It Works

### 1. Market Fetching

The bot fetches active markets from both Kalshi and Polymarket APIs.

### 2. Market Matching

Markets are matched across platforms using:
- String similarity (Levenshtein distance)
- Key phrase matching
- Normalization of market names

### 3. Arbitrage Detection

The bot checks for **valid arbitrage opportunities** using opposing outcomes:

1. **Buy YES on Platform A + Buy NO on Platform B**
   - If total cost < $1.00, guaranteed profit (one outcome pays $1.00)
   - Example: Buy Team Liquid YES @ $0.45 + Buy Team Liquid NO @ $0.48 = $0.93 cost → $0.07 profit

2. **Buy NO on Platform A + Buy YES on Platform B**
   - Same strategy, reversed order
   - No existing positions required

**Note**: The bot does NOT use buy/sell strategies (e.g., "Buy YES then Sell YES") because you cannot sell shares you don't own. Only buying opposing outcomes guarantees profit without requiring pre-existing positions.

### 4. Order Execution

**Paper Trading Mode:**
- Simulates trades with virtual money
- Tracks simulated profit/loss
- 95% success rate with realistic slippage (90-100% of expected profit)
- Trades "fill" after 10-30 seconds
- Sends notifications for each trade

**Live Trading Mode:**
When an opportunity is found and trading is enabled:
1. Places buy order on the first platform
2. Places sell order on the second platform
3. If either order fails, cancels the successful order
4. Tracks the arbitrage position

### 5. Notifications & Monitoring

**Telegram Notifications (if enabled):**
- Startup notification
- Real-time arbitrage opportunity alerts
- Trade execution notifications
- Trade result notifications (success/failure)
- Hourly performance summaries
- Error notifications

**Order Monitoring (live trading):**
The bot continuously monitors active orders and:
- Updates order statuses
- Cancels stale orders (> 1 minute old)
- Prevents losses from incomplete arbitrages

## Project Structure

```
ArbiBot/
├── src/
│   ├── clients/
│   │   ├── kalshi.ts             # Kalshi API client
│   │   └── polymarket.ts         # Polymarket API client
│   ├── services/
│   │   ├── marketMatcher.ts      # Market matching logic
│   │   ├── arbitrageDetector.ts  # Arbitrage detection
│   │   ├── orderManager.ts       # Order placement and management
│   │   ├── paperTrading.ts       # Paper trading simulation
│   │   └── telegramNotifier.ts   # Telegram notifications
│   ├── types/
│   │   └── index.ts              # TypeScript type definitions
│   ├── utils/
│   │   ├── config.ts          # Configuration loader
│   │   └── logger.ts          # Logging utility
│   ├── bot.ts                 # Main bot orchestrator
│   └── index.ts               # Entry point
├── .env.example               # Example environment variables
├── .gitignore
├── package.json
├── tsconfig.json
├── TELEGRAM_SETUP.md          # Telegram bot setup guide
└── README.md
```

## Safety Features

1. **Paper Trading Mode**: Test with simulated money before risking real capital
2. **Real-time Notifications**: Get instant alerts via Telegram for every opportunity
3. **Profit Threshold**: Only execute trades above minimum profit
4. **Position Limits**: Cap maximum investment per trade
5. **Stale Order Cancellation**: Automatically cancel orders that don't fill quickly
6. **Error Handling**: Robust error handling and logging
7. **Graceful Shutdown**: Proper cleanup on SIGINT/SIGTERM

## Logging

Logs are written to:
- Console (with colors)
- `combined.log` (all logs)
- `error.log` (errors only)

## Risk Disclaimer

**USE AT YOUR OWN RISK**

This bot involves real financial transactions. There are risks including:
- API failures or delays
- Market volatility
- Partial fills
- Slippage
- Platform-specific risks

Always:
- Start with small position sizes
- Use dry-run mode first
- Monitor the bot closely
- Never invest more than you can afford to lose

## Troubleshooting

### No markets found

- Check your API keys are correct
- Verify API endpoints are accessible
- Check rate limits on the platforms

### No matching markets

- The platforms may not have overlapping markets
- Adjust the similarity threshold in `marketMatcher.ts`

### Orders not executing

- Verify `ENABLE_TRADING=true` in `.env`
- Check you have sufficient balance on both platforms
- Review logs for API errors

## Future Improvements

- WebSocket support for real-time price updates
- More sophisticated market matching algorithms
- Multi-leg arbitrage strategies
- Portfolio optimization
- Backtesting framework
- Web dashboard for monitoring

## License

MIT

## Contributing

Contributions are welcome! Please open an issue or pull request.

## API Documentation

- [Kalshi API Docs](https://docs.kalshi.com/welcome)
- [Polymarket API Docs](https://docs.polymarket.com)

## Sources

- [Introduction - API Documentation - Kalshi](https://docs.kalshi.com/welcome)
- [Kalshi API | Kalshi Help Center](https://help.kalshi.com/kalshi-api)
- [Kalshi API: The Complete Developer's Guide | Zuplo Learning Center](https://zuplo.com/learning-center/kalshi-api)
