Skip to content
YAP545Public

About

High-performance order matching and processing system in Spring Boot 3 featuring a deterministic Price-Time Priority engine, live WebSockets, and OpenAPI docs.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

OrderFlow — High-Performance Order Matching & Processing System

Project Overview

OrderFlow is a Spring Boot 3 application designed for real-time order processing, order book management, and order matching using a deterministic Price-Time Priority matching engine. It features RESTful APIs for order/employee management, live STOMP WebSockets for broadcasting executed trades, openAPI (Swagger UI) documentation, and integrated data persistence.


Features

  • Order Book Engine: In-memory, thread-safe price-time priority matching engine.
  • Trade Generation & Broadcaster: Automatically detects matches, generates trades, updates remaining quantities, and publishes trades to connected WebSocket subscribers (/topic/trades).
  • RESTful Management APIs: Full CRUD capabilities for Orders and Employees with pagination, sorting, and filtering options.
  • Robust Input Validation: Strict bean validation using @Valid, @NotBlank, @NotNull, @Positive, and regex pattern matching for order sides (BUY/SELL).
  • Unified Error Handling: Comprehensive @RestControllerAdvice returning structured ErrorResponse objects with details for 404 Not Found, 400 Bad Request, and 500 Internal Server Error.
  • Environment-Driven Configuration: Externalized configuration for database connection strings and credentials to ensure security.
  • Interactive Swagger Documentation: Built-in Swagger UI for exploring and testing API endpoints.

Architecture

OrderFlow follows a clean 3-tier enterprise Spring Boot architecture with decoupling between REST Controllers, Business Logic Services, the Matching Engine, and Data Access Repositories.

                  +-----------------------+
                  |   REST Clients / UI   |
                  +-----------+-----------+
                              |
                     HTTP / WebSocket
                              |
       +----------------------v----------------------+
       |                 Controllers                 |
       |  OrderController | OrderBookController ...  |
       +----------------------+----------------------+
                              |
       +----------------------v----------------------+
       |                  Services                   |
       |      OrderService  |  TradeService          |
       +-----------+-------------------+-------------+
                   |                   |
      +------------v----------+   +----v-------------------+
      | Engine (OrderBook)    |   | Repositories (Spring   |
      | PriorityQueue (BUY)   |   | Data JPA)              |
      | PriorityQueue (SELL)  |   +------------------------+
      +------------+----------+
                   |
      +------------v----------+
      | TradePublisher        |
      | (STOMP WebSockets)    |
      +-----------------------+

Order Matching Algorithm & Price-Time Priority

OrderFlow uses an in-memory priority queue structure to maintain order books for BUY and SELL orders:

  1. Price Priority:
    • BUY Orders: Higher prices take precedence (sorted descending by price).
    • SELL Orders: Lower prices take precedence (sorted ascending by price).
  2. Time Priority:
    • For orders with identical prices, the order with the earlier millisecond timestamp is matched first.
  3. Execution Rules:
    • When a BUY order arrives with limit price $P_{buy}$, it matches against resting SELL orders where $P_{sell} \le P_{buy}$.
    • When a SELL order arrives with limit price $P_{sell}$, it matches against resting BUY orders where $P_{buy} \ge P_{sell}$.
    • Trade execution occurs at the resting order's limit price.
    • Partial fills reduce remaining quantities for both orders. If an order is fully filled (quantity = 0), it is removed from the book. Any remaining unfilled quantity stays on the order book.

Technology Stack

  • Java Version: 17 / 25
  • Framework: Spring Boot 3.5.4
  • Web & Messaging: Spring WebMVC, Spring WebSocket (STOMP / SockJS)
  • Persistence: Spring Data JPA, Hibernate ORM
  • Databases:
    • Production / Local Dev: MySQL
    • Testing: H2 (In-Memory)
  • API Documentation: Springdoc OpenAPI (Swagger UI 2.8.9)
  • Build Tool: Apache Maven

Project Structure

c:/Users/yasha/Downloads/OrderFlow-main/OrderFlow-main
├── pom.xml
├── README.md
├── src
│   ├── main
│   │   ├── java
│   │   │   └── com
│   │   │       └── orderflow
│   │   │           ├── OrderflowApplication.java
│   │   │           ├── config
│   │   │           │   └── WebSocketConfig.java
│   │   │           ├── controller
│   │   │           │   ├── EmployeeController.java
│   │   │           │   ├── HomeController.java
│   │   │           │   ├── OrderBookController.java
│   │   │           │   ├── OrderController.java
│   │   │           │   └── TradeController.java
│   │   │           ├── dto
│   │   │           │   └── ErrorResponse.java
│   │   │           ├── engine
│   │   │           │   └── OrderBook.java
│   │   │           ├── entity
│   │   │           │   ├── Employee.java
│   │   │           │   └── Order.java
│   │   │           ├── exception
│   │   │           │   ├── GlobalExceptionHandler.java
│   │   │           │   └── ResourceNotFoundException.java
│   │   │           ├── model
│   │   │           │   ├── OrderBookResponse.java
│   │   │           │   └── Trade.java
│   │   │           ├── repository
│   │   │           │   ├── EmployeeRepository.java
│   │   │           │   └── OrderRepository.java
│   │   │           ├── service
│   │   │           │   ├── EmployeeService.java
│   │   │           │   ├── OrderService.java
│   │   │           │   └── TradeService.java
│   │   │           └── websocket
│   │   │               └── TradePublisher.java
│   │   └── resources
│   │       ├── application.properties
│   │       └── static
│   │           └── test.html
│   └── test
│       ├── java
│       │   └── com
│       │       └── orderflow
│       │           ├── OrderflowApplicationTests.java
│       │           ├── controller
│       │           │   ├── EmployeeControllerTest.java
│       │           │   └── OrderControllerTest.java
│       │           ├── engine
│       │           │   └── OrderBookTest.java
│       │           └── service
│       │               ├── EmployeeServiceTest.java
│       │               └── OrderServiceTest.java
│       └── resources
│           └── application-test.properties

Database Design

orders Table

Column Type Constraints Description
id BIGINT PRIMARY KEY, AUTO_INCREMENT Unique order identifier
symbol VARCHAR(255) NOT NULL Asset symbol (e.g. TCS, INFY, AAPL)
side VARCHAR(255) NOT NULL Order direction (BUY or SELL)
price DOUBLE NOT NULL Limit price per unit
quantity INT NOT NULL Order quantity
timestamp BIGINT NOT NULL Millisecond timestamp when order was placed

employees Table

Column Type Constraints Description
id INT PRIMARY KEY, AUTO_INCREMENT Employee unique ID
name VARCHAR(255) NOT NULL Employee full name
email VARCHAR(255) NOT NULL Employee email address

REST APIs

Orders Endpoints (/orders)

  • POST /orders — Submit a new order (Triggers matching engine).
  • GET /orders — List all orders.
  • GET /orders/{id} — Get order by ID.
  • GET /orders/symbol/{symbol} — Filter orders by symbol.
  • GET /orders/page?page=0&size=10 — Get paginated list of orders.
  • GET /orders/sort?field=price — Get orders sorted by field.
  • GET /orders/orderbook — Get current order book snapshot.
  • PUT /orders/{id} — Update order details.
  • DELETE /orders/{id} — Delete order by ID.

OrderBook Endpoint (/orderbook)

  • GET /orderbook — Get active buy and sell orders sorted by price-time priority.

Trades Endpoint (/trades)

  • GET /trades — Retrieve list of executed trades.

Employees Endpoints (/employees)

  • POST /employees — Create new employee.
  • GET /employees — List all employees.
  • GET /employees/{id} — Get employee by ID.
  • PUT /employees/{id} — Update employee.
  • DELETE /employees/{id} — Delete employee.

WebSocket & Real-Time Communication

  • Endpoint: /ws (SockJS fallback enabled)
  • STOMP Broker Topic: /topic/trades
  • Client Live Preview: An interactive live trade streaming HTML client is available at http://localhost:9093/test.html.

Configuration & Environment Variables

Production settings in application.properties accept environment variables with sensible defaults:

Variable Default Value Description
PORT 9093 Application HTTP server port
SPRING_DATASOURCE_URL jdbc:mysql://localhost:3306/orderflowdb?createDatabaseIfNotExist=true&useSSL=false MySQL JDBC URL
SPRING_DATASOURCE_USERNAME root Database username
SPRING_DATASOURCE_PASSWORD root Database password
SPRING_JPA_HIBERNATE_DDL_AUTO update DDL generation mode

Prerequisites & Installation

  1. JDK 17 or higher installed.
  2. Apache Maven 3.8+ installed.
  3. MySQL Server (optional for local running, test suite uses embedded H2).

Running Automated Tests

mvn clean test

Packaging & Running Application

mvn clean package
java -jar target/orderflow-0.0.1-SNAPSHOT.jar

Swagger / OpenAPI

Once the application is running, inspect and interact with the REST APIs via: http://localhost:9093/swagger-ui.html or http://localhost:9093/v3/api-docs


Future Enhancements

  • Multi-asset order book mapping (Map<String, OrderBook>).
  • Database persistence for executed Trade history.
  • Authentication & Authorization via Spring Security & JWT.

About

High-performance order matching and processing system in Spring Boot 3 featuring a deterministic Price-Time Priority engine, live WebSockets, and OpenAPI docs.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages