Knowledge Guide
HomeOO & Low-Level DesignOO Design Problems

Design an Online Stock Brokerage System

Let's design an Online Stock Brokerage System.

An Online Stock Brokerage System facilitates its users the trade (i.e. buying and selling) of stocks online. It allows clients to keep track of and execute their transactions, and shows performance charts of the different stocks in their portfolios. It also provides security for their transactions and alerts them to pre-defined levels of changes in stocks, without the use of any middlemen.

The online stock brokerage system automates traditional stock trading using computers and the internet, making the transaction faster and cheaper. This system also gives speedier access to stock reports, current market trends, and real-time stock prices.

Image
Image

System Requirements

We will focus on the following set of requirements while designing the online stock brokerage system:

  1. Any user of our system should be able to buy and sell stocks.

  2. Any user can have multiple watchlists containing multiple stock quotes.

  3. Users should be able to place stock trade orders of the following types: 1) market, 2) limit, 3) stop loss and, 4) stop limit.

  4. Users can have multiple 'lots' of a stock. This means that if a user has bought a stock multiple times, the system should be able to differentiate between different lots of the same stock.

  5. The system should be able to generate reports for quarterly updates and yearly tax statements.

  6. Users should be able to deposit and withdraw money either via check, wire, or electronic bank transfer.

  7. The system should be able to send notifications whenever trade orders are executed.

Usecase diagram

We have three main Actors in our system:

Here are the top use cases of the Stock Brokerage System:

Image
Image

Class diagram

Here are the main classes of our Online Stock Brokerage System:

Image
Image
Image
Image

Activity diagrams

Place a buy order: Any system user can perform this activity. Here are the steps to place a buy order:

Image
Image

Place a sell order: Any system user can perform this activity. Here are the steps to place a buy order:

Image
Image

Code

Here is the code for the top use cases.

Enums and Constants: Here are the required enums and constants:

java
public enum ReturnStatus {
    SUCCESS, FAIL, INSUFFICIENT_FUNDS, INSUFFICIENT_QUANTITY, NO_STOCK_POSITION
}

public enum OrderStatus {
    OPEN, FILLED, PARTIALLY_FILLED, CANCELLED
}

public enum TimeEnforcementType {
    GOOD_TILL_CANCELLED, FILL_OR_KILL, IMMEDIATE_OR_CANCEL, ON_THE_OPEN, ON_THE_CLOSE
}

public enum AccountStatus {
    ACTIVE, CLOSED, CANCELED, BLACKLISTED, None
}

public class Location {
    private String streetAddress;
    private String city;
    private String state;
    private String zipCode;
    private String country;
}

public static class Constants {
    public static final int MONEY_TRANSFER_LIMIT = 100_000;
}

StockExchange: To encapsulate all the interactions with the stock exchange:

java
public class StockExchange {

    private static StockExchange stockExchangeInstance = null;

    // private constructor to restrict for singleton
    private StockExchange() {
    }

    // static method to get the singleton instance of StockExchange
    public static StockExchange getInstance() {
        if (stockExchangeInstance == null) {
            stockExchangeInstance = new StockExchange();
        }
        return stockExchangeInstance;
    }

    public static boolean placeOrder(Order order) {
        boolean returnStatus = getInstance().submitOrder(Order);
        return returnStatus;
    }
}

Order: To encapsulate all buy or sell orders:

java
public abstract class Order {
    private String orderNumber;
    public boolean isBuyOrder;
    private OrderStatus status;
    private TimeEnforcementType timeEnforcement;
    private Date creationTime;

    private HashMap<Integer, OrderPart> parts;

    public void setStatus(OrderStatus status) {
        this.status = status;
    }

    public bool saveInDB() {
        // save in the database
    }

    public void addOrderParts(OrderParts parts) {
        for (OrderPart part : parts) {
            this.parts.put(part.id, part);
        }
    }
}

public class LimitOrder extends Order {
    private double priceLimit;
}

Member: Members will be buying and selling stocks:

java
// For simplicity, we are not defining getter and setter functions. The reader can
// assume that all class attributes are private and accessed through their respective
// public getter methods and modified only through their public methods function.

public abstract class Account {
    private String id;
    private String password;
    private String name;
    private AccountStatus status;
    private Location address;
    private String email;
    private String phone;

    public boolean resetPassword();
}

public class Member extends Account {
    private double availableFundsForTrading;
    private Date dateOfMembership;

    private HashMap<string, StockPosition> stockPositions;

    private HashMap<Integer, Order> activeOrders;

    public ErrorCode placeSellLimitOrder(
      string stockId,
      float quantity,
      int limitPrice,
      TimeEnforcementType enforcementType )
    {
      // check if member has this stock position
      if(!stockPositions.containsKey(stockId)){
        return NO_STOCK_POSITION;
      }
  
      StockPosition stockPosition = stockPositions.get(stockId);
      // check if the member has enough quantity available to sell
      if(stockPosition.getQuantity() < quantity){
        return INSUFFICIENT_QUANTITY;
      }
  
      LimitOrder order =
        new LimitOrder(stockId, quantity, limitPrice, enforcementType);
      order.isBuyOrder = false;
      order.saveInDB();
      boolean success = StockExchange::placeOrder(order);
      if(!success){
        order.setStatus(OrderStatus::FAILED);
        order.saveInDB();
      } else {
        activeOrders.add(orderId, order);
      }
      return success;
    }

    public ErrorCode placeBuyLimitOrder(
      string stockId,
      float quantity,
      int limitPrice,
      TimeEnforcementType enforcementType)
    {
      // check if the member has enough funds to buy this stock
      if(availableFundsForTrading < quantity * limitPrice ){
        return INSUFFICIENT_FUNDS;
      }
  
      LimitOrder order =
        new LimitOrder(stockId, quantity, limitPrice, enforcementType);
      order.isBuyOrder = true;
      order.saveInDB();
      boolean success = StockExchange::placeOrder(order);
      if(!success){
        order.setStatus(OrderStatus::FAILED);
        order.saveInDB();
      } else {
        activeOrders.add(orderId, order);
      }
      return success;
    }

    // this function will be invoked whenever there is an update from
    // stock exchange against an order
    public void callbackStockExchange(int orderId, List<OrderPart> orderParts, OrderStatus status) {
        Order order = activeOrders.get(orderId);
        order.addOrderParts(orderParts);
        order.setStatus(status);
        order.updateInDB();

        if (status == OrderStatus::FILLED || status == OrderStatus::CANCELLEd) {
            activeOrders.remove(orderId);
        }
    }
}
🤖 Don't fully get this? Learn it with Claude

Stuck on Design an Online Stock Brokerage System? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🎨 Explain it visually

Build the mental picture, not memorization.

I just read a lesson on **Design an Online Stock Brokerage System** (OO & Low-Level Design) and want to truly understand it. Explain Design an Online Stock Brokerage System from first principles using ONE vivid real-world analogy and a visual mental model — draw it as ASCII art or a clear step-by-step diagram — with a concrete example using real numbers. Then ask me one question to check I got the mental picture, and wait for my reply. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🤔 Walk me through it (interactive)

Socratic — adapts to where you're stuck.

Teach me **Design an Online Stock Brokerage System** interactively. Ask me ONE guiding question at a time, wait for my answer, and adapt to my confusion — build the idea with me step by step instead of explaining it all at once. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧪 Quiz me & fix my gaps

Active recall exposes what you missed.

Quiz me on **Design an Online Stock Brokerage System** with 5 questions, easy to tricky, ONE at a time. Tell me if each answer is right; at the end, explain clearly what I got wrong and why. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧠 Make it stick

Intuition + hook + flashcards for long-term memory.

Help me remember **Design an Online Stock Brokerage System** for the long term: give the one-sentence intuition, a memorable hook/mnemonic, a tiny worked example, and 3 active-recall flashcards (Q -> A). If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes