Skip to content

About

Simple API for market order execution simulator used to evaluate testing tools

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Order Execution Engine API

A Demo Order Execution Engine API with JWT Authentication. This is a simplified stock trading simulator where users can execute buy/sell orders with virtual money.

Features

  • JWT Authentication - Secure user registration and login
  • Multi-user Support - Each user manages their own accounts
  • Authorization - Users can only access their own accounts, orders, positions, and trades
  • Create and manage trading accounts
  • Buy and sell stocks at current market prices
  • Track positions and portfolio value
  • View trade history and performance
  • Real-time P&L calculations
  • RESTful API with automatic OpenAPI documentation

Tech Stack

  • Language: Python 3.11+
  • Framework: FastAPI
  • Database: PostgreSQL 15
  • ORM: SQLAlchemy 2.x with Alembic migrations
  • Validation: Pydantic v2
  • Deployment: Docker & Docker Compose

Quick Start

Prerequisites

  • Docker and Docker Compose installed
  • Git (to clone the repository)

Setup and Run

  1. Clone the repository (or navigate to the project directory)

  2. Start the services:

    docker-compose up --build

    This will:

    • Start PostgreSQL database
    • Run database migrations
    • Start the FastAPI application
    • API will be available at http://localhost:8000
  3. Seed the database (optional, for test data):

    docker-compose exec api python -m app.seed
  4. Access the API documentation:

    • Swagger UI: http://localhost:8000/docs
    • ReDoc: http://localhost:8000/redoc
    • Health Check: http://localhost:8000/health

API Documentation

Interactive Documentation

  • Swagger UI: http://localhost:8000/docs
  • ReDoc: http://localhost:8000/redoc

API Specifications

  • OpenAPI YAML: openapi.yaml - Complete OpenAPI 3.1 spec in YAML format
  • OpenAPI JSON: openapi.json - Complete OpenAPI 3.1 spec in JSON format
  • Postman Collection: postman_collection.json - Ready-to-import Postman collection with examples

Authentication

The API uses JWT (JSON Web Token) authentication. Most endpoints require authentication.

Getting Started with Authentication

  1. Register a new user:

    curl -X POST "http://localhost:8000/api/v1/auth/register" \
      -H "Content-Type: application/json" \
      -d '{
        "email": "user@example.com",
        "username": "myuser",
        "password": "mypassword",
        "full_name": "My Name"
      }'
  2. Login to get an access token:

    curl -X POST "http://localhost:8000/api/v1/auth/login" \
      -H "Content-Type: application/json" \
      -d '{
        "username": "myuser",
        "password": "mypassword"
      }'
  3. Save the access token from the response:

    {
      "access_token": "eyJhbGc...",
      "token_type": "bearer"
    }
  4. Use the token in subsequent requests:

    curl -X GET "http://localhost:8000/api/v1/accounts" \
      -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

Authentication Endpoints

  • POST /auth/register - Register a new user
  • POST /auth/login - Login with JSON body
  • GET /auth/me - Get current user info (requires auth)

Protected vs Public Endpoints

Public (No authentication required):

  • All /stocks endpoints - Stock prices are public information
  • All /auth endpoints (except /auth/me) - Registration and login

Protected (Authentication required):

  • All /accounts endpoints - Users can only access their own accounts
  • All /orders endpoints - Users can only create/view orders for their accounts
  • All /positions endpoints - Users can only view their own positions
  • All /trades endpoints - Users can only view their own trades

API Endpoints

Base URL: http://localhost:8000/api/v1

Authentication

  • POST /auth/register - Register new user
  • POST /auth/login - Login with JSON body
  • GET /auth/me - Get current user info

Accounts (Protected)

  • GET /accounts - List all your accounts

  • POST /accounts - Create a new trading account

  • GET /accounts/{account_id} - Get account details

  • POST /accounts/{account_id}/deposit - Deposit cash

  • POST /accounts/{account_id}/withdraw - Withdraw cash

  • GET /accounts/{account_id}/performance - Get account performance summary

Orders

  • POST /orders - Create and execute an order
  • GET /orders - List all orders (with filters)
  • GET /orders/{order_id} - Get specific order details

Positions

  • GET /positions - List all positions
  • GET /positions/{account_id} - Get positions for specific account

Trades

  • GET /trades - List all trades (with filters)
  • GET /trades/{account_id} - Get trades for specific account

Stocks

  • GET /stocks - List all available stocks
  • GET /stocks/{symbol} - Get current price for symbol
  • PUT /stocks/{symbol} - Update stock price (for testing)

Usage Examples

1. Create an Account

curl -X POST "http://localhost:8000/api/v1/accounts" \
  -H "Content-Type: application/json" \
  -d '{
    "account_number": "ACC001",
    "holder_name": "John Doe",
    "initial_cash": 10000.00
  }'

2. Buy Stocks

curl -X POST "http://localhost:8000/api/v1/orders" \
  -H "Content-Type: application/json" \
  -d '{
    "account_id": 1,
    "symbol": "AAPL",
    "order_type": "BUY",
    "quantity": 10
  }'

3. Check Positions

curl -X GET "http://localhost:8000/api/v1/positions/1"

4. Sell Stocks

curl -X POST "http://localhost:8000/api/v1/orders" \
  -H "Content-Type: application/json" \
  -d '{
    "account_id": 1,
    "symbol": "AAPL",
    "order_type": "SELL",
    "quantity": 5
  }'

5. View Account Performance

curl -X GET "http://localhost:8000/api/v1/accounts/1/performance"

6. Update Stock Price

curl -X PUT "http://localhost:8000/api/v1/stocks/AAPL" \
  -H "Content-Type: application/json" \
  -d '{
    "current_price": 155.50
  }'

Business Rules

Buy Orders

  1. Account must exist and be ACTIVE
  2. Symbol must exist in stock_prices
  3. Account must have sufficient cash balance
  4. Order executes immediately at current market price

Sell Orders

  1. Account must exist and be ACTIVE
  2. Account must have a position in the symbol
  3. Position must have sufficient quantity
  4. Order executes immediately at current market price

Positions

  • Positions are created when buying stocks
  • Average cost is calculated when buying more of the same stock
  • Positions are deleted when quantity reaches 0
  • Unrealized P&L is calculated as: (current_price - average_cost) * quantity

Account Value

  • Total Value = Cash Balance + Sum of Position Values
  • Recalculated after every order execution
  • Updated when stock prices change

Testing with Postman

Complete Postman collections are included with all API endpoints and example requests.

Available Collections

  1. postman_collection_with_auth.json (RECOMMENDED) - Full collection with JWT authentication
  2. postman_collection.json - Legacy collection (pre-authentication)

Import to Postman

  1. Import Collection:

    • Open Postman
    • Click "Import" button
    • Select postman_collection_with_auth.json (recommended)
    • Click "Import"
  2. Import Environment:

    • Click "Import" button
    • Select postman_environment.json
    • Click "Import"
    • Select "OMS Demo API - Local (With Auth)" from the environment dropdown

Collection Features

  • JWT Authentication - Login requests automatically save tokens
  • Bearer Token Auth - Automatically applied to protected endpoints
  • 70+ Requests organized by resource type
  • Auto-saved Variables: access_token, account_id automatically saved
  • Complete Workflow: Step-by-step authentication and trading workflow
  • Error Cases: Examples of validation failures and authorization errors
  • Query Parameters: Filtering and pagination examples

Folder Structure

  1. Authentication - Register, login, get current user
  2. Stocks (Public) - List, get price, update price (no auth required)
  3. Accounts (Protected) - Create, list, get, deposit, withdraw, performance
  4. Orders (Protected) - Create buy/sell orders, list with filters
  5. Positions (Protected) - View positions and portfolio
  6. Trades (Protected) - Trade history and audit log
  7. Complete Workflow (With Auth) - 7-step end-to-end authenticated trading scenario

Quick Start with Postman

  1. Import postman_collection.json
  2. Run the "Complete Workflow" folder in order:
    • Register a new user
    • Login to get JWT token (automatically saved)
    • Create trading account
    • Buy/sell stocks with auto-authentication
    • View performance and P&L
  3. All protected endpoints automatically use the saved token

Database Schema

Tables

  1. accounts - Trading accounts with cash balance
  2. positions - Stock holdings per account
  3. orders - Buy/sell orders with status
  4. trades - Immutable execution records
  5. stock_prices - Current market prices

Initial Stock Data

The database comes pre-seeded with these stocks:

  • AAPL: $150.00
  • GOOGL: $140.00
  • MSFT: $380.00
  • TSLA: $200.00
  • AMZN: $170.00

Development

Run Without Docker

  1. Install dependencies:

    pip install -r requirements.txt
  2. Set up PostgreSQL and create database

  3. Configure environment:

    cp .env.example .env
    # Edit .env with your database URL
  4. Run migrations:

    alembic upgrade head
  5. Seed database:

    python -m app.seed
  6. Start server:

    uvicorn app.main:app --reload

Run Tests

# Run migrations
docker-compose exec api alembic upgrade head

# Seed test data
docker-compose exec api python -m app.seed

# View logs
docker-compose logs -f api

Project Structure

oms-demo-api/
├── app/
│   ├── models/          # SQLAlchemy models
│   ├── schemas/         # Pydantic schemas
│   ├── services/        # Business logic
│   ├── routers/         # API endpoints
│   ├── utils/           # Helper functions
│   ├── config.py        # Configuration
│   ├── database.py      # Database setup
│   ├── main.py          # FastAPI app
│   └── seed.py          # Seed script
├── alembic/             # Database migrations
├── docker-compose.yml   # Docker setup
├── Dockerfile           # Container image
├── requirements.txt     # Python dependencies
└── README.md           # This file

Troubleshooting

Database Connection Issues

If you see database connection errors:

# Check if database is running
docker-compose ps

# View database logs
docker-compose logs db

# Restart services
docker-compose down
docker-compose up --build

Reset Database

# Stop services
docker-compose down -v

# Start fresh
docker-compose up --build

View API Logs

docker-compose logs -f api

API Response Examples

Successful Order (BUY)

{
  "id": 1,
  "account_id": 1,
  "symbol": "AAPL",
  "order_type": "BUY",
  "quantity": 10,
  "price": 150.00,
  "status": "FILLED",
  "rejection_reason": null,
  "total_amount": 1500.00,
  "created_at": "2025-01-11T10:30:00Z",
  "filled_at": "2025-01-11T10:30:00Z"
}

Rejected Order (Insufficient Funds)

{
  "id": 2,
  "account_id": 1,
  "symbol": "AAPL",
  "order_type": "BUY",
  "quantity": 1000,
  "price": 150.00,
  "status": "REJECTED",
  "rejection_reason": "Insufficient funds. Required: 150000.00, Available: 10000.00",
  "total_amount": 150000.00,
  "created_at": "2025-01-11T10:31:00Z",
  "filled_at": null
}

License

This is a demo project for testing purposes.

Support

For issues or questions, please check the API documentation at /docs or review the implementation in the source code.

About

Simple API for market order execution simulator used to evaluate testing tools

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages