Skip to content

akhilkumar-dot/Trading-Engine

Repository files navigation

🏦 Trading Engine

A production-grade, event-driven stock trading platform built with a Java Spring Boot microservices architecture. The system handles real-time order placement, order matching, trade execution, market-data streaming, and user portfolio management β€” all coordinated through Apache Kafka and backed by PostgreSQL.


πŸ“‘ Table of Contents


πŸ— Architecture Overview

                        β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                        β”‚        API Gateway          β”‚
                        β”‚  (Port 8080 Β· JWT Filter)   β”‚
                        β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                     β”‚ routes requests
           β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
           β–Ό                         β–Ό                          β–Ό
   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”        β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
   β”‚ User Service β”‚        β”‚  Order Service   β”‚      β”‚ Market Data Service β”‚
   β”‚  (Port 8081) β”‚        β”‚  (Port 8082)     β”‚      β”‚    (Port 8085)      β”‚
   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜        β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜      β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                    β”‚ Kafka: orders-topic
                                    β–Ό
                         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                         β”‚   Matching Engine    β”‚
                         β”‚    (Port 8083)       β”‚
                         β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                    β”‚ Kafka: trades-topic
                                    β–Ό
                         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                         β”‚    Trade Service     β”‚
                         β”‚    (Port 8084)       β”‚
                         β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
   β”‚          Eureka Discovery Server (Port 8761)           β”‚
   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

   Infrastructure: Apache Kafka Β· PostgreSQL (Supabase) Β· Redis

πŸ›  Microservices

Service Port Responsibility
Eureka Server 8761 Service discovery & registry
API Gateway 8080 Single entry point, JWT validation, routing
User Service 8081 Registration, login, JWT issuance, portfolio
Order Service 8082 Order placement, validation, Kafka publishing
Matching Engine 8083 Order book, buy/sell matching, trade generation
Trade Service 8084 Trade event consumption, history persistence
Market Data Service 8085 Real-time price feeds, WebSocket streaming

βš™οΈ Technology Stack

Category Technology
Language Java 17
Framework Spring Boot 3.x
Service Discovery Spring Cloud Netflix Eureka
API Gateway Spring Cloud Gateway MVC
Messaging Apache Kafka (Confluent 7.5)
Database PostgreSQL 15 (Supabase)
Caching Redis 7.2
Security Spring Security + JWT (JJWT)
ORM Spring Data JPA / Hibernate
Build Tool Maven (Maven Wrapper included)
Containerisation Docker + Docker Compose

πŸš€ Getting Started

Prerequisites

Tool Version
Java JDK 17+
Maven 3.9+ (or use included mvnw)
Docker & Docker Compose Latest
Git Any

Infrastructure Setup

Start Kafka, Zookeeper, PostgreSQL and Redis via Docker Compose:

docker-compose up -d

This spins up:

  • Zookeeper on port 2181
  • Kafka on port 9092
  • PostgreSQL on port 5432 (db: tradingdb, user: postgres)
  • Redis on port 6379

Configuration

Every service ships with an application.properties.example template located at:

<service>/src/main/resources/application.properties.example

Copy and populate the template for each service:

# Example for user-service
cp user-service/src/main/resources/application.properties.example \
   user-service/src/main/resources/application.properties

Then edit the file and replace the placeholder values:

Placeholder Description
<DB_HOST> PostgreSQL hostname (e.g. localhost or Supabase host)
<DB_NAME> Database name (e.g. postgres)
<DB_USER> Database username
<DB_PASSWORD> Database password
<YOUR_JWT_SECRET_MIN_32_CHARS> A random 32+ character secret key

⚠️ Never commit application.properties β€” it is excluded by .gitignore.

Running the Services

Start services in order (each in its own terminal):

# 1. Eureka Discovery Server (must start first)
cd eureka-server && ./mvnw clean spring-boot:run

# 2. API Gateway
cd api-gateway && ./mvnw clean spring-boot:run

# 3. User Service
cd user-service && ./mvnw clean spring-boot:run

# 4. Order Service
cd order-service && ./mvnw clean spring-boot:run

# 5. Matching Engine
cd matching-engine && ./mvnw clean spring-boot:run

# 6. Trade Service
cd trade-service && ./mvnw clean spring-boot:run

# 7. Market Data Service
cd market-data-service && ./mvnw clean spring-boot:run

Verify everything is up:


πŸ“‘ API Reference

All requests go through the API Gateway at http://localhost:8080.

Auth β€” User Service (/api/users)

Method Endpoint Auth Description
POST /api/users/register ❌ Public Register a new user
POST /api/users/login ❌ Public Login & receive JWT token
GET /api/users/portfolio βœ… Bearer View user portfolio

Register

POST /api/users/register
{
  "username": "akhil",
  "email": "akhil@example.com",
  "password": "secret123"
}

Login

POST /api/users/login
{
  "email": "akhil@example.com",
  "password": "secret123"
}
// Response: { "token": "eyJhbGci..." }

Orders β€” Order Service (/api/orders)

Method Endpoint Auth Description
POST /api/orders βœ… Bearer Place a new order
GET /api/orders/{userId} βœ… Bearer Get orders for a user

Place Order

POST /api/orders
Authorization: Bearer <token>
{
  "userId": 1,
  "symbol": "AAPL",
  "quantity": 10,
  "price": 185.50,
  "orderType": "LIMIT",
  "orderSide": "BUY"
}

Order types: LIMIT, MARKET
Order sides: BUY, SELL


Trades β€” Trade Service (/api/trades)

Method Endpoint Auth Description
GET /api/trades/{userId} βœ… Bearer Get trade history for a user

Market Data β€” Market Data Service (/api/market)

Method Endpoint Auth Description
GET /api/market/{symbol} ❌ Public Get latest price for a symbol
WS /ws/market ❌ Public WebSocket real-time price feed

πŸ“¨ Kafka Event Flow

Order Service
    β”‚
    β”‚  orders-topic  (OrderEventDTO)
    β–Ό
Matching Engine
    β”‚  β€” Matches BUY/SELL orders from the in-memory order book
    β”‚
    β”‚  trades-topic  (TradeEventDTO)
    β–Ό
Trade Service
    β”‚  β€” Persists executed trades to PostgreSQL
    β”‚  β€” Updates user portfolios

Key Kafka Topics

Topic Producer Consumer Payload
orders-topic Order Service Matching Engine OrderEventDTO
trades-topic Matching Engine Trade Service TradeEventDTO

πŸ” Security

  • JWT Authentication is enforced at the API Gateway level via JwtAuthFilter.
  • Tokens are issued by the User Service on successful login.
  • The JWT secret must be identical in user-service and api-gateway configs.
  • Public endpoints (no token required):
    • POST /api/users/register
    • POST /api/users/login
    • GET /api/market/**
    • WebSocket /ws

πŸ“ Project Structure

trading-engine/
β”œβ”€β”€ docker-compose.yml              # Infrastructure (Kafka, PG, Redis)
β”œβ”€β”€ .gitignore                      # Protects secrets & build artifacts
β”‚
β”œβ”€β”€ eureka-server/                  # Service registry
β”œβ”€β”€ api-gateway/                    # JWT auth + routing
β”‚   └── src/main/
β”‚       β”œβ”€β”€ java/.../filter/JwtAuthFilter.java
β”‚       └── resources/application.properties.example
β”‚
β”œβ”€β”€ user-service/                   # Auth, registration, portfolio
β”‚   └── src/main/
β”‚       β”œβ”€β”€ java/.../model/User.java
β”‚       └── resources/application.properties.example
β”‚
β”œβ”€β”€ order-service/                  # Order placement & Kafka publishing
β”‚   └── src/main/
β”‚       β”œβ”€β”€ java/.../dto/OrderRequestDTO.java
β”‚       └── resources/application.properties.example
β”‚
β”œβ”€β”€ matching-engine/                # Order book & trade matching
β”‚   └── src/main/
β”‚       └── resources/application.properties.example
β”‚
β”œβ”€β”€ trade-service/                  # Trade event consumer & history
β”‚   └── src/main/
β”‚       └── resources/application.properties.example
β”‚
└── market-data-service/            # Price feeds & WebSocket
    └── src/main/
        └── resources/application.properties.example

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/my-feature
  3. Copy and configure all application.properties.example files β€” do not commit real credentials
  4. Commit your changes: git commit -m "feat: add my feature"
  5. Push and open a Pull Request

πŸ“„ License

This project is open-source and available under the MIT License.


Built with β˜• Java Β· πŸƒ Spring Boot Β· ⚑ Apache Kafka

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors