Trade your insights, shape the future.
A high-performance, real-time prediction trading platform built with modern microservices architecture. Users can buy and sell "YES" or "NO" contracts on future events, with prices dynamically adjusting based on market demand through an automated order matching engine.
PredictTrade solves the problem of opaque and slow prediction markets by providing a transparent, high-performance, and real-time trading experience. Built for traders, market enthusiasts, and developers interested in high-frequency trading systems and modern web architecture.
- Real-time Order Matching: Microsecond-level order processing and matching
- Microservices Architecture: Scalable, distributed system design
- Live Market Data: WebSocket-powered real-time price updates and order book streaming
- High Performance: Redis-based message queuing and pub/sub for low-latency communication
- Type-Safe Monorepo: Shared TypeScript types and packages across all services
- Intuitive Trading Interface: Modern Next.js application with real-time charts and order forms
- Live Market Data: Real-time price charts, order books, and trade history
- Secure Authentication: NextAuth.js with email verification
- Responsive Design: Built with Tailwind CSS and Shadcn UI components
- Real-time Updates: WebSocket connections for instant market data
- RESTful API Gateway: Express.js server handling authentication and order validation
- Trading Engine: Core order matching system with price discovery algorithms
- WebSocket Service: Real-time data distribution to thousands of concurrent users
- Message Queuing: Redis-based asynchronous order processing
- Database Layer: PostgreSQL with TimescaleDB for time-series data
- Microservices Design: Separate services for trading, WebSocket, and API handling
- Horizontal Scalability: Redis pub/sub enables multi-instance deployments
- Fault Tolerance: Graceful shutdown procedures and health monitoring
- Type Safety: Shared TypeScript types across the entire system
Client Layer
- Next.js frontend with real-time UI components
- WebSocket connections for live data streaming
- Form validation with React Hook Form and Zod
API Gateway
- Express.js server handling HTTP requests
- User authentication and session management
- Order validation and event management
- Queues trading orders to Redis for async processing
Trading Engine
- Core order matching algorithms
- In-memory order books for each market
- Real-time price discovery and trade execution
- Balance and contract management
WebSocket Service
- Manages thousands of concurrent connections
- Real-time market data distribution
- Subscription management for different data streams
- Health monitoring and graceful shutdowns
Message Broker (Redis)
- Order processing queues
- Pub/sub channels for real-time data
- Inter-service communication
- Caching and session storage
Database Layer
- PostgreSQL for persistent data storage
- TimescaleDB extension for time-series price data
- Prisma ORM for type-safe database access
- Next.js - React framework with SSR and API routes
- TypeScript - Type-safe JavaScript development
- Tailwind CSS - Utility-first styling framework
- Shadcn UI - Reusable component library
- Framer Motion - Animation library for smooth interactions
- Recharts - Data visualization for price charts
- NextAuth.js - Authentication and session management
- Node.js & Express.js - Server runtime and web framework
- TypeScript - End-to-end type safety
- WebSockets (ws) - Real-time bidirectional communication
- Redis - Message broker and caching layer
- PostgreSQL + TimescaleDB - Database with time-series optimization
- Prisma ORM - Type-safe database client
- Turborepo - Monorepo build system with caching
- Docker & Docker Compose - Containerization and orchestration
- ESLint & Prettier - Code quality and formatting
- Winston - Structured logging
- Zod - Runtime type validation
.
βββ apps/
β βββ client/ # Next.js frontend application
β βββ server/ # Express.js API gateway
βββ services/
β βββ engine/ # Trading engine service
β βββ wss/ # WebSocket service
βββ packages/
β βββ db/ # Prisma ORM and database services
β βββ ui/ # Shared React components
β βββ types/ # Shared TypeScript types
β βββ logger/ # Winston logging utility
β βββ order-queue/ # Redis client and queue management
β βββ zod-schema/ # Data validation schemas
β βββ eslint-config/ # Shared ESLint configurations
β βββ typescript-config/ # Shared TypeScript configurations
βββ docker-compose.yml # Database and Redis containers
- Node.js (v18 or higher)
- npm (v10 or higher)
- Docker and Docker Compose
-
Clone the repository
git clone <your-repo-url> cd predict-trade
-
Install dependencies
npm install
-
Start Docker services
docker-compose up -d
-
Setup environment variables
Create
.envfiles in the following directories:packages/db/.envDATABASE_URL="postgresql://dev:dev@localhost:5432/repo?schema=public"
apps/client/.envNEXTAUTH_SECRET="your-nextauth-secret" NEXTAUTH_URL="http://localhost:3001" NEXT_PUBLIC_BACKEND_URL="http://localhost:3000" NEXT_PUBLIC_WSS_URL="ws://localhost:8080" SMTP_HOST="your-smtp-host" SMTP_PORT="587" SMTP_SECURE="true" SMTP_USER="your-smtp-user" SMTP_PASSWORD="your-smtp-password" FROM_EMAIL="your-from-email"
apps/server/.envDATABASE_URL="your-postgre-url" REDIS_URL="redis://localhost:6379" SYNTHETIC_MARKET_MAKER_USER_ID="your-market-maker-id"
services/wss/.envPORT=8080 REDIS_URL="redis://localhost:6379"
-
Setup database
npm run build --workspace=@repo/db npx prisma migrate dev --name init --schema packages/db/prisma/schema.prisma
-
Build and start all services
npm run build npm run dev
- Frontend: http://localhost:3001
- API Gateway: http://localhost:3000
- WebSocket Service: ws://localhost:8080
- User places order β Client validates and sends to API Gateway
- API Gateway β Validates order and pushes to Redis ORDER_QUEUE
- Trading Engine β Processes order from queue, matches against order book
- Order execution β Updates balances, creates trade records
- Real-time updates β Engine publishes market data to Redis pub/sub
- WebSocket Service β Receives updates and broadcasts to connected clients
- Client receives β Real-time price and order book updates
- Market Data: Price updates, order book depth, recent trades
- User Data: Balance updates, order status, trade confirmations
- System Data: Connection health, market summaries
- User: Authentication, profile, balance, and role information
- Event: Prediction markets with title, description, and status
- UserContract: User holdings of YES/NO contracts per event
- Trade: Individual trade transactions with buyer/seller details
- PriceHistory: Time-series price data for charting
- TimescaleDB Integration: Optimized time-series queries for price history
- Type Safety: Prisma-generated types for all database operations
- Efficient Indexing: Optimized queries for real-time data access
# Install dependencies
npm install
# Build all packages and apps
npm run build
# Start all services in development
npm run dev
# Lint all code
npm run lint
# Type checking
npm run type-check
# Database operations
npx prisma studio # Database GUI
npx prisma migrate dev # Run migrations
npx prisma generate # Generate client# Run specific service
npm run dev --workspace=apps/client
npm run dev --workspace=services/engine
npm run dev --workspace=services/wss
# Build specific package
npm run build --workspace=@repo/db
npm run build --workspace=@trade/types- Environment Variables: Secure storage of API keys and database URLs
- Database Scaling: PostgreSQL read replicas and connection pooling
- Redis Clustering: Multi-node Redis setup for high availability
- Load Balancing: Multiple WebSocket service instances
- Monitoring: Application performance and error tracking
# Build production images
docker-compose -f docker-compose.prod.yml build
# Deploy services
docker-compose -f docker-compose.prod.yml up -d- Order Processing: ~1000 orders/second per engine instance
- WebSocket Connections: 10,000+ concurrent connections per WSS instance
- Database Queries: <10ms average response time for market data
- Real-time Latency: <50ms from order placement to client update
- Horizontal Scaling: Multiple engine and WSS instances
- Database Optimization: Indexed queries and connection pooling
- Caching Strategy: Redis for frequently accessed data
- Async Processing: Non-blocking order queue processing
- Authentication: Secure session management with NextAuth.js
- Input Validation: Zod schemas for all API endpoints
- SQL Injection Prevention: Prisma ORM with parameterized queries
- Rate Limiting: Redis-based request throttling
- Error Handling: Sanitized error responses
We welcome contributions!
This project is licensed under the MIT License. See the LICENSE file for details.
Built with modern web technologies and best practices in system design. Special thanks to the open-source community for the incredible tools and libraries that made this project possible.