Live2025

Stock Market Gaming Portal

A real-time stock market gamification platform — users bet on stock races (which stock gains the most), compete on live leaderboards, earn points and badges, all powered by live market data synced via WebSocket workers, with bot detection and automated race management.

NestJSTypeScriptPostgreSQLRedisBullMQSocket.IOReactNginxDockerAWS

Category

SaaS Products

Year

2025

Status

Live

The Problem

Stock market education and engagement is dry. People read about investing, watch YouTube videos, but never develop real intuition for how stocks move relative to each other. Paper trading platforms exist, but they are slow and solitary — there is no competition, no urgency, no reason to come back every day.

The idea was simple: turn stock price movement into a live, competitive game. Pick stocks you think will outperform, watch them race against each other in real-time with horse-race-style animations, and win points if you called it right. Make it social, make it live, make it addictive — without requiring users to risk real money in actual markets.

The challenge was entirely backend — live market data ingestion, real-time race mechanics, concurrent bet handling, fair leaderboard calculation, bot detection, and keeping hundreds of simultaneous WebSocket connections in sync during a live race.

What I Built

A backend-heavy real-time gaming platform where users bet on stock races, watch live animated races driven by actual market data, and compete on leaderboards for points and badges.

Stock Races — The Core Game:

  • A race is a competition between 3–8 stocks over a defined time window (5 minutes, 15 minutes, 1 hour, or full trading day)
  • Before the race starts, users place bets — predicting which stock will finish first (highest percentage gain) and by how much each stock will increase or decrease
  • When the race begins, real-time stock price changes are streamed to all connected users via WebSocket
  • The UI renders a horse-race-style animation — each stock is a “horse” on a track, and its position moves forward or backward based on live percentage gain relative to its opening price
  • Stocks overtake each other in real-time as prices fluctuate — the visual effect is genuinely exciting during volatile market moments
  • When the race ends, final positions are locked based on actual closing percentage gains. Points are awarded based on prediction accuracy
  • Multiple races can run simultaneously — morning sprints (5-min), afternoon marathons (full day), themed races (tech stocks only, energy sector, top gainers from yesterday)

Betting & Points System:

  • Users bet with virtual points (not real money) — earned through correct predictions, daily login bonuses, and achievement badges
  • Bet types:
    • Winner pick — which stock finishes first. Higher odds for underdog picks (stock with lower recent momentum)
    • Gain/loss prediction — predict the percentage change for a specific stock within a range bracket (e.g., +2% to +4%). More precise predictions earn more points
    • Podium prediction — predict the top 3 finishing order. Exact order match pays the most, partial matches pay less
  • Points calculation runs at race completion — a deterministic scoring algorithm factors in prediction accuracy, number of participants (larger races pay more), and bet timing (earlier bets pay slightly more since they carry more risk)
  • Anti-gaming rules — users cannot change bets after a race starts, maximum bet size per race to prevent point hoarding, and cooldown between rapid-fire bets

Live Leaderboard:

  • Global leaderboard ranked by total points — updated in real-time as races complete
  • Weekly and monthly leaderboards with reset cycles — keeps competition fresh and gives new users a chance to climb
  • Per-race leaderboard showing all participants and their predictions once the race ends
  • Streak tracking — consecutive correct winner picks earn bonus multipliers
  • Leaderboard updates pushed to all connected clients via Socket.IO — no polling, no stale data

User Badge & Achievement System:

  • Badges earned for milestones: first race, 10 correct predictions, 5-race win streak, top 10 weekly finish, 100 races participated, sector specialist (correctly predicted 20 races in the same sector)
  • Badge rarity tiers — common, rare, epic, legendary — with increasingly difficult unlock criteria
  • Profile showcase — users display their top badges on their public profile
  • Badge unlock notifications pushed in real-time via WebSocket

Live Stock Data Portal:

  • Real-time stock prices displayed on the portal — users can browse stocks, see live price tickers, and view intraday charts before placing bets
  • Historical data — daily, weekly, and monthly charts for every stock symbol. Candlestick and line chart views
  • Stock metadata — company name, sector, market cap, 52-week high/low, average volume, recent news sentiment
  • Search and filter — find stocks by symbol, name, sector, or performance metrics
  • Watchlist — users can save favorite stocks and get notified when they appear in upcoming races

Bot Detection:

  • Algorithmic detection of bot accounts and automated betting patterns
  • Signals: inhuman bet timing (bets placed within milliseconds of race opening), perfect prediction accuracy over suspicious sample sizes, identical bet patterns across multiple accounts, API request fingerprinting
  • Flagged accounts are shadow-restricted — they can still play but their bets don’t affect leaderboards or earn real points, and they are queued for manual review
  • Rate limiting on bet placement — both per-user and per-IP
  • Device fingerprinting and session analysis to detect multi-accounting

Admin Dashboard:

  • Race management — create races (select stocks, set duration, set start time), monitor active races, view completed race results
  • User management — view accounts, point balances, bet history, flag/ban suspicious accounts
  • Leaderboard controls — reset cycles, manual point adjustments for edge cases
  • System health — active WebSocket connections, worker queue depths, market data sync lag, race completion rates
  • Revenue metrics — if the platform introduces premium features or ads

Backend Architecture (The Heavy Lifting)

This is a backend-heavy application with five distinct server-side components:

1. NestJS Application Server (Core Business Logic):

  • The central API server handling all business logic — user registration, authentication, race creation, bet placement, points calculation, leaderboard queries, badge management
  • RESTful API endpoints for the frontend, with request validation, rate limiting, and JWT authentication
  • Race lifecycle management — state machine governing race stages (scheduled → open for bets → in progress → calculating → completed)
  • Points calculation engine — runs at race completion, processes all bets against actual stock performance, applies scoring rules, updates user balances and leaderboards atomically
  • Badge evaluation — after every race completion, checks all participants against badge unlock criteria and triggers notifications for new unlocks

2. Market Data Sync Worker (WebSocket Consumer):

  • A dedicated async worker process that maintains a persistent WebSocket connection to the market data provider
  • Receives live stock price updates in real-time during market hours
  • Normalizes incoming data (different providers have different payload formats) and writes to Redis for immediate consumption by the race engine
  • Also persists price snapshots to PostgreSQL at configurable intervals (every 1 second during active races, every 15 seconds otherwise) for historical data
  • Handles connection drops gracefully — automatic reconnection with exponential backoff, gap detection, and backfill from the provider’s REST API when the WebSocket was down
  • Runs independently of the main application server — if the NestJS server restarts, market data sync continues uninterrupted

3. Symbol & Metadata Sync Worker:

  • Another async worker that periodically syncs stock symbols, company information, sector classifications, market cap data, and other metadata from the market data provider
  • Runs on a schedule — full sync daily before market open, incremental updates hourly
  • Handles symbol changes (ticker renames, delistings, IPOs) and updates the local database accordingly
  • Populates the search index so users can find stocks by name, symbol, or sector
  • Maintains 52-week high/low, average volume, and other derived metrics used for race creation and stock display

4. Socket.IO Server (Live Connections):

  • Dedicated WebSocket server handling all real-time client connections
  • During an active race, streams live stock position updates to all connected race participants — position recalculated every second based on latest price data from Redis
  • Pushes leaderboard updates, badge unlock notifications, race start/end events, and bet confirmation acknowledgments
  • Redis adapter for Socket.IO — enables horizontal scaling across multiple Socket.IO server instances. All instances share connection state and room membership via Redis pub/sub
  • Room-based architecture — each active race is a Socket.IO room. Users join a room when they enter a race view, and receive only updates relevant to that race
  • Connection management — heartbeat monitoring, automatic reconnection handling, and graceful degradation (if WebSocket fails, fall back to long polling)

5. BullMQ Job Queues & Cron Workers (Redis-backed):

  • Race lifecycle jobs — scheduled jobs that transition races through their lifecycle: open betting window, start race, end race, trigger points calculation
  • Bot race generation (cron) — a scheduled process that creates simulated races with bot participants for testing, demonstration, and to ensure there are always active races even during low-traffic hours. Bot bets follow realistic distribution patterns
  • Race cleanup (cron) — catches races that got stuck in an intermediate state (e.g., a race that was “in progress” but never completed due to a server crash). Detects stale races and either completes them with available data or cancels them with bet refunds
  • Points calculation queue — race completion triggers an async job that calculates points for all participants. Runs in a worker to avoid blocking the API server during large races with hundreds of bets
  • Badge evaluation queue — after points are calculated, another job evaluates badge criteria for all affected users
  • Data archival — periodic jobs that move old race data and completed bet records to archive tables to keep the primary tables performant

Technical Challenges

  • Real-time race synchronization — Hundreds of users watching the same race must see identical stock positions at the same moment. The market data worker writes price updates to Redis, the NestJS race engine calculates percentage gains, and the Socket.IO server broadcasts positions — all within a 1-second cycle. Redis pub/sub ensures all Socket.IO instances (if horizontally scaled) broadcast the same data. Clock skew between servers is handled by using Redis server time as the single source of truth.

  • Atomic points calculation — When a race ends, hundreds of bets must be scored against final stock prices, user balances updated, leaderboards recalculated, and badges evaluated — all atomically. If any step fails, the entire calculation must roll back. Built this as a PostgreSQL transaction with row-level locks on user balance rows, with the entire operation running in a BullMQ worker with retry logic. Idempotency keys prevent double-crediting if the job is retried.

  • Market data reliability — Live market data providers drop connections, send malformed data, or have outages. The sync worker maintains a local buffer of recent prices in Redis. If the WebSocket disconnects, the race engine continues using cached data (flagged as potentially stale). When the connection recovers, a backfill process detects gaps and fills them from the provider’s REST API. Races that ran during a data gap are flagged for review.

  • Bot detection without false positives — Aggressive bot detection catches bots but also flags legitimate power users who bet frequently. Built a multi-signal scoring system rather than hard rules. No single signal triggers a ban — instead, signals accumulate a suspicion score, and only accounts exceeding a threshold over a time window get restricted. Manual review queue ensures no legitimate user is permanently penalized.

  • Socket.IO scaling with Redis adapter — A single Socket.IO instance handles roughly 5,000 concurrent connections. Beyond that, horizontal scaling is needed. The Redis adapter syncs room membership and broadcasts across instances, but adds latency. Tuned the Redis pub/sub channel structure to minimize cross-instance chatter — each race room publishes to its own channel, so instances only process messages for races they have active clients for.

  • Race state machine correctness — A race transitions through multiple states, and external events (market close, data outage, server restart) can interrupt any transition. Built the state machine with explicit transition guards in PostgreSQL — each state change is a conditional UPDATE that checks the current state before applying. Cron cleanup jobs detect races stuck in intermediate states and either advance or cancel them based on available data and elapsed time.

Architecture

  • NestJS API Server — Core business logic. REST API for frontend. Race management, bet processing, points engine, badge system, user management. JWT auth, rate limiting, request validation.
  • Market Data Worker — Async process maintaining WebSocket connection to market data provider. Writes live prices to Redis, persists snapshots to PostgreSQL. Auto-reconnection and gap backfill.
  • Symbol Sync Worker — Async process syncing stock metadata, symbols, and derived metrics on a schedule. Keeps the local database current with listings, delistings, and corporate actions.
  • Socket.IO Server — Dedicated real-time server. Streams race positions, leaderboard updates, and notifications to connected clients. Redis adapter for horizontal scaling. Room-based architecture per race.
  • BullMQ Workers — Redis-backed job queues for race lifecycle transitions, points calculation, badge evaluation, bot race generation, race cleanup, and data archival. Cron schedules for recurring jobs.
  • Database — PostgreSQL for users, races, bets, points ledger, badges, stock metadata, price history, and audit logs. Indexes on race lookups, leaderboard queries, and bet scoring.
  • Cache & Pub/Sub — Redis for live stock prices (hot data), Socket.IO adapter (cross-instance sync), BullMQ job queues, session tokens, and leaderboard caching.
  • Frontend — React application with Socket.IO client. Horse-race animation renderer, live stock tickers, leaderboard views, bet placement interface, profile and badge showcase.
  • Infrastructure — Nginx reverse proxy with WebSocket upgrade support. Docker containers for each component. PostgreSQL on RDS. Redis on ElastiCache. Deployed on AWS.

Results & Impact

  • Live stock races with real market data — the horse-race animation driven by actual price movements creates genuine excitement and engagement that paper trading cannot match
  • Backend-first architecture — five distinct server-side components (API server, two data sync workers, WebSocket server, job queue workers) running independently, each handling its specific concern
  • Real-time at scale — Socket.IO with Redis adapter handles thousands of concurrent connections streaming race updates every second during active races
  • Fair and reliable scoring — atomic points calculation with PostgreSQL transactions ensures no user is over- or under-credited, even during server failures
  • Bot-resilient — multi-signal detection keeps the leaderboard fair without penalizing legitimate power users
  • Self-healing race management — cron-based cleanup catches stuck races, and bot-generated races ensure there is always activity on the platform
  • Sole architect and developer — designed and built the entire system: NestJS API, market data sync workers, Socket.IO real-time server, BullMQ job queues, React frontend with race animations, and all infrastructure

Stack Deep Dive

  • NestJS (TypeScript) as the core API framework — modules for races, bets, users, points, badges, and admin, with guards, interceptors, and pipes for auth/validation
  • Socket.IO with Redis adapter for real-time race streaming and leaderboard pushes across horizontally scaled instances
  • Redis for live price data (sub-millisecond reads for race position calculation), BullMQ job queues, Socket.IO pub/sub, and leaderboard caching
  • BullMQ for scheduled and event-driven job processing — race lifecycle, points calculation, badge evaluation, bot race generation, and cleanup crons
  • PostgreSQL for all persistent data — races, bets, users, points ledger, badges, stock metadata, price history, with row-level locking for atomic balance updates
  • React frontend with Socket.IO client — horse-race animation, live tickers, interactive bet placement, and real-time leaderboard
  • Nginx with WebSocket upgrade support as reverse proxy and SSL terminator
  • Docker for containerized deployment of all five backend components plus frontend
  • AWS (EC2, RDS, ElastiCache, CloudWatch) for managed infrastructure

Interested in working together?

Get in Touch