AlgoArena - AI Trading Battle Arena

Inspiration

The inspiration for AlgoArena came from a simple question: Can AI really beat the market? We've all heard stories about Wall Street quants using algorithms to make millions, but what if anyone could create their own AI trading bot and test it against real market data?

We wanted to democratize algorithmic trading by creating a platform where:

  • Students can learn about market dynamics without risking real money
  • Developers can experiment with AI-powered trading strategies
  • Anyone can compete against institutional-grade algorithms in real-time

The gamification aspect was crucial—we wanted to make quantitative finance fun and accessible, not intimidating. By turning trading into a competitive arena where your custom AI bot battles against others, we hoped to spark curiosity about both finance and AI.

What it does

AlgoArena is a real-time AI trading simulation platform that lets you:

  1. Create Custom AI Trading Bots: Write your own trading strategy in plain English (e.g., "I'm a momentum trader—buy stocks going up, sell stocks going down")

  2. Battle Against AI Opponents: Your bot competes against institutional traders (quants, hedge funds) and retail traders in live market simulations

  3. Use Real Market Data: Powered by Yahoo Finance API, the platform fetches actual historical data for:

    • US Tech stocks (AAPL, MSFT, GOOGL, etc.)
    • S&P 500 companies
    • Indian markets (NIFTY 50)
    • Cryptocurrencies
  4. Watch Live Simulations: Real-time WebSocket streaming shows:

    • Live price charts with actual stock values
    • Agent activity feed (who's buying/selling what)
    • Dynamic leaderboard with P&L tracking
    • Market index showing collective market movement
  5. Analyze Performance: After each simulation, get detailed analytics:

    • Final ranking and profit/loss
    • Portfolio breakdown
    • AI-generated post-market analysis
    • Strategy recommendations

The platform calculates the Market Index as the average price of all stocks:

$$\text{Market Index} = \frac{1}{n}\sum_{i=1}^{n} P_i$$

where $P_i$ is the current price of stock $i$, giving you a real sense of overall market movement (not normalized to 100).

How we built it

Architecture Overview

We built AlgoArena with a modern full-stack architecture:

Backend (Python + FastAPI):

  • FastAPI for async WebSocket server
  • Google Gemini API for AI trading agents (using gemini-2.0-flash model)
  • yfinance for fetching live market data
  • Custom order book matching engine with price-time priority
  • Multi-agent orchestration system managing 10+ concurrent AI traders

Frontend (React + TypeScript):

  • React 18 with TypeScript for type safety
  • Vite for lightning-fast development
  • TailwindCSS + Shadcn/UI for beautiful, accessible components
  • Recharts for real-time data visualization
  • Framer Motion for smooth animations
  • WebSocket client for real-time updates

Key Technical Decisions

  1. WebSocket over REST: We chose WebSockets for real-time streaming because REST polling would be inefficient for tick-by-tick market updates. Every price change, trade, and agent action is pushed instantly to all connected clients.

  2. LLM-Powered Agents: Instead of hardcoding trading logic, we use Google Gemini to power AI agents. Each agent has a unique personality and strategy, making decisions based on:

    • Current market prices
    • Historical price data
    • Portfolio positions
    • Market news events
  3. Real Market Data: We integrated Yahoo Finance API to fetch actual historical data, giving users realistic price movements and volatility. The data includes:

    • OHLCV (Open, High, Low, Close, Volume)
    • Flexible time periods (1 month to 10+ years)
    • Multiple markets (US, India, Crypto)
  4. State Management: We built a custom Redux-like store for managing complex market state:

    • Real-time price updates
    • Agent activities
    • Portfolio values
    • Top movers (gainers/losers)

The Build Process

Week 1: Core Simulation Engine

  • Built the order book matching engine
  • Created the multi-agent orchestration system
  • Implemented basic LLM integration

Week 2: Live Data Integration

  • Integrated yfinance API
  • Built market data provider with caching
  • Added support for multiple markets

Week 3: Frontend Development

  • Designed and built React components
  • Implemented WebSocket client
  • Created real-time charts and visualizations

Week 4: Polish & Features

  • Added AI trading consultant (chatbot)
  • Built post-market analysis
  • Implemented saved agents feature
  • Fixed currency display for different markets

Challenges we ran into

1. Real-time State Synchronization

Problem: With 10+ AI agents making trades simultaneously, keeping the frontend in sync with the backend was challenging. Race conditions caused duplicate agent activities and stale price data.

Solution: We implemented a deduplication system using unique IDs and timestamps. Each agent activity is checked against existing activities before being added to the state:

const isDuplicate = state.agentActivities.some(
  existing =>
    existing.id === event.payload.id ||
    (existing.summary === event.payload.summary &&
      Math.abs(existing.timestamp - event.payload.timestamp) < 1000)
);

2. Market Index Normalization

Problem: Initially, we normalized the market index to start at 100 (like real indices), but users were confused—they wanted to see actual stock prices, not normalized values.

Solution: We changed the market index calculation to show the actual average price of all stocks:

def calculate_market_index(initial_prices: dict, current_prices: dict) -> float:
    """Calculate the average price of all stocks in the market."""
    total = sum(current_prices.values())
    count = len(current_prices)
    return total / count if count > 0 else 0.0

Now if you're trading US tech stocks averaging $300, the index shows $300, not 100.

3. Currency Symbol Confusion

Problem: The platform was showing rupee symbols (₹) for US stocks and dollar symbols ($) for Indian stocks—completely backwards!

Solution: We implemented dynamic currency detection based on the selected market:

def get_currency_for_market(yf_market):
    if yf_market == 'india_nifty50':
        return '₹'
    elif yf_market == 'crypto':
        return '$'
    else:
        return '$'  # US markets

The currency is broadcast via WebSocket and stored in the frontend state, ensuring all components display the correct symbol.

4. LLM Response Parsing

Problem: Gemini sometimes returned malformed JSON or included extra text, breaking our agent decision system.

Solution: We implemented robust JSON extraction with regex and fallback parsing:

# Try to extract JSON from response
json_match = re.search(r'\{.*\}', response_text, re.DOTALL)
if json_match:
    return json.loads(json_match.group())

5. WebSocket Connection Management

Problem: Users experienced disconnections, and the frontend didn't handle reconnection gracefully.

Solution: We implemented exponential backoff reconnection with a maximum delay:

const delay = Math.min(1000 * Math.pow(2, reconnectAttempts), 30000);
reconnectTimeout = setTimeout(connect, delay);

Accomplishments that we're proud of

1. Real-Time Performance at Scale

We built a system that handles:

  • 10+ concurrent AI agents making decisions
  • Real-time price updates for 10-20 stocks
  • WebSocket streaming to multiple clients
  • All with sub-second latency

2. Beautiful, Intuitive UI

We created a trading dashboard that's both powerful and accessible:

  • Real-time charts with smooth animations
  • Live agent activity feed
  • Dynamic leaderboard
  • Responsive design that works on all devices

3. AI-Powered Trading Agents

Our LLM integration allows users to create trading bots using natural language:

  • "I'm a momentum trader—buy stocks going up"
  • "I'm a contrarian—buy dips, sell rallies"
  • "I only buy stocks below their historical average"

The AI understands these strategies and executes them in real-time.

4. Live Market Data Integration

We successfully integrated Yahoo Finance API to fetch:

  • Real historical data for 1000+ stocks
  • Multiple markets (US, India, Crypto)
  • Flexible time periods (1 month to 10+ years)
  • OHLCV data for accurate charting

5. Complete Feature Set

In just 4 weeks, we built:

  • ✅ Multi-agent simulation engine
  • ✅ Real-time WebSocket streaming
  • ✅ Live market data integration
  • ✅ AI trading consultant (chatbot)
  • ✅ Post-market analysis
  • ✅ Saved agents feature
  • ✅ Multiple market support
  • ✅ Beautiful, responsive UI

6. Learning & Growth

This project pushed us to learn:

  • WebSocket programming for real-time communication
  • LLM integration for AI-powered decision making
  • Financial APIs and market data handling
  • State management for complex real-time applications
  • TypeScript for type-safe frontend development

What's Next?

We're excited to continue developing AlgoArena with features like:

  • Backtesting engine for historical strategy evaluation
  • Social features for sharing strategies and competing with friends
  • Advanced analytics with Sharpe ratio, alpha, and beta calculations
  • Paper trading with real-time market data
  • Strategy marketplace where users can share and sell their best bots

AlgoArena proves that AI + Finance + Gamification = Fun Learning. We hope it inspires more people to explore algorithmic trading and AI!

Built With

Share this project:

Updates