├── CMakeLists.txt ├── src ├── stock.cpp ├── orderBook.cpp ├── order.cpp └── trader.cpp ├── include ├── stock.h ├── orderBook.h ├── trader.h └── order.h ├── main.cpp └── README.md /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.12) 2 | 3 | project(StockTradingSystem) 4 | 5 | # Add source files 6 | add_executable(my_app main.cpp src/order.cpp src/orderBook.cpp src/stock.cpp src/trader.cpp) 7 | 8 | # Set C++ standard 9 | set(CMAKE_CXX_STANDARD 11) 10 | 11 | # Specify additional libraries or dependencies 12 | target_link_libraries(my_app PRIVATE pthread) 13 | 14 | # Install target (optional) 15 | # install(TARGETS my_app DESTINATION bin) 16 | -------------------------------------------------------------------------------- /src/stock.cpp: -------------------------------------------------------------------------------- 1 | #include "../include/stock.h" 2 | 3 | using namespace StockTradingSystem; 4 | 5 | Stock::Stock() = default; 6 | 7 | Stock::Stock(double p, const std::string& n) 8 | : price{p} 9 | , name{n} 10 | { 11 | } 12 | 13 | void Stock::setPrice(double p) 14 | { 15 | price = p; 16 | } 17 | 18 | void Stock::setName(const std::string& n) 19 | { 20 | name = n; 21 | } 22 | 23 | double Stock::getPrice() const 24 | { 25 | return price; 26 | } 27 | 28 | std::string Stock::getName() const 29 | { 30 | return name; 31 | } -------------------------------------------------------------------------------- /include/stock.h: -------------------------------------------------------------------------------- 1 | #ifndef STOCK_TRADING_SYSTEM_STOCK_H 2 | #define STOCK_TRADING_SYSTEM_STOCK_H 3 | 4 | #include 5 | 6 | namespace StockTradingSystem 7 | { 8 | 9 | class Stock 10 | { 11 | public: 12 | Stock(); 13 | Stock(double, const std::string&); 14 | void setPrice(double); 15 | void setName(const std::string&); 16 | double getPrice() const; 17 | std::string getName() const; 18 | private: 19 | double price; 20 | std::string name; 21 | }; 22 | 23 | } // StockTradingSystem 24 | 25 | #endif // STOCK_TRADING_SYSTEM_STOCK_H -------------------------------------------------------------------------------- /include/orderBook.h: -------------------------------------------------------------------------------- 1 | #ifndef STOCK_TRADING_SYSTEM_ORDERBOOK_H 2 | #define STOCK_TRADING_SYSTEM_ORDERBOOK_H 3 | 4 | #include "order.h" 5 | 6 | #include 7 | #include 8 | 9 | namespace StockTradingSystem 10 | { 11 | 12 | class OrderBook 13 | { 14 | public: 15 | OrderBook(); 16 | void addOrder(std::shared_ptr); 17 | void matchOrders(); 18 | void printOrderBook() const; 19 | void setStrategy(OrderMatchingStrategy*); 20 | private: 21 | std::vector> book; 22 | OrderMatchingStrategy* strategy; 23 | }; 24 | 25 | } // StockTradingSystem 26 | 27 | #endif // STOCK_TRADING_SYSTEM_ORDERBOOK_H -------------------------------------------------------------------------------- /include/trader.h: -------------------------------------------------------------------------------- 1 | #ifndef STOCK_TRADING_SYSTEM_TRADER_H 2 | #define STOCK_TRADING_SYSTEM_TRADER_H 3 | 4 | #include "stock.h" 5 | #include "order.h" 6 | #include "orderBook.h" 7 | 8 | #include 9 | 10 | namespace StockTradingSystem 11 | { 12 | 13 | class TraderException : public std::exception 14 | { 15 | public: 16 | TraderException(const std::string&); 17 | virtual const char* what() const noexcept override; 18 | private: 19 | std::string message; 20 | }; 21 | 22 | 23 | class Trader 24 | { 25 | public: 26 | Trader(); 27 | Trader(const std::string&); 28 | Trader(const std::string&, const std::vector&, OrderFactory*, OrderBook*); 29 | void buy(const Stock&, int); 30 | void sell(const Stock&, int); 31 | void trade(double, double, int, int); 32 | int getID() const; 33 | const std::vector>& getOrders() const; 34 | void addStock(const Stock&); 35 | std::vector getStocks() const; 36 | ~Trader(); 37 | private: 38 | static int id_counter; 39 | int id; 40 | std::string name; 41 | std::vector stocks; 42 | OrderFactory* orderFactory; 43 | OrderBook* orderBook; 44 | std::vector> orders; 45 | }; 46 | 47 | } // StockTradingSystem 48 | 49 | #endif // STOCK_TRADING_SYSTEM_TRADER_H 50 | -------------------------------------------------------------------------------- /main.cpp: -------------------------------------------------------------------------------- 1 | #include "include/orderBook.h" 2 | #include "include/trader.h" 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | using namespace StockTradingSystem; 10 | 11 | // Define a trader function to simulate traders placing orders 12 | void traderFunction(Trader& trader, OrderBook& orderBook) { 13 | Stock someStock(145, "a"); 14 | Stock anotherStock(154, "b"); 15 | trader.addStock(someStock); 16 | trader.addStock(anotherStock); 17 | int quantity = 25; 18 | 19 | // Place buy and sell orders 20 | std::shared_ptr buyOrder = std::make_shared(trader.getID(), someStock.getPrice(), quantity); 21 | buyOrder->setOrderType(OrderType::BUY); 22 | std::shared_ptr sellOrder = std::make_shared(trader.getID(), anotherStock.getPrice(), quantity); 23 | sellOrder->setOrderType(OrderType::SELL); 24 | 25 | trader.trade(150, 160, 12, 13); 26 | 27 | // Add orders to the order book 28 | orderBook.addOrder(buyOrder); 29 | orderBook.addOrder(sellOrder); 30 | } 31 | 32 | int main() { 33 | // Create an order book 34 | OrderBook orderBook; 35 | 36 | // Create and start multiple trader threads 37 | std::vector traderThreads; 38 | int numTraders = 3; 39 | for (int i = 0; i < numTraders; ++i) { 40 | Trader trader("Trader " + std::to_string(i + 1)); 41 | traderThreads.emplace_back(traderFunction, std::ref(trader), std::ref(orderBook)); 42 | } 43 | 44 | // Join trader threads 45 | for (auto& thread : traderThreads) { 46 | thread.join(); 47 | } 48 | 49 | // Print the order book after all trading is done 50 | orderBook.printOrderBook(); 51 | 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /src/orderBook.cpp: -------------------------------------------------------------------------------- 1 | #include "../include/orderBook.h" 2 | 3 | #include 4 | 5 | using namespace StockTradingSystem; 6 | 7 | OrderBook::OrderBook() : strategy(nullptr) 8 | { 9 | } 10 | 11 | void OrderBook::addOrder(std::shared_ptr order) 12 | { 13 | book.push_back(order); 14 | } 15 | 16 | void OrderBook::matchOrders() { 17 | std::vector> buyOrders; 18 | std::vector> sellOrders; 19 | 20 | // Create vectors of shared pointers to orders 21 | for (const auto& order : book) { 22 | if (order->getPrice() > 0) { 23 | buyOrders.push_back(std::static_pointer_cast(order)); 24 | } else { 25 | sellOrders.push_back(std::static_pointer_cast(order)); 26 | } 27 | } 28 | 29 | // Call the matching strategy with the separated buy and sell order vectors 30 | strategy->matchOrders(buyOrders, sellOrders); 31 | 32 | // Update the order book with remaining orders 33 | book.clear(); 34 | book.insert(book.end(), buyOrders.begin(), buyOrders.end()); 35 | book.insert(book.end(), sellOrders.begin(), sellOrders.end()); 36 | } 37 | 38 | void OrderBook::printOrderBook() const 39 | { 40 | std::cout << "Order Book content...\n"; 41 | std::cout << "ID\tPrice\tQuantity\tOrder Type\n"; 42 | for (const auto& order : book) 43 | { 44 | std::string orderTypeName = (order->getOrdertype() == OrderType::BUY) ? "Buy" : "Sell"; 45 | std::cout << order->getTraider_id() << "\t" << order->getPrice() << "\t" << 46 | order->getQuantity() << "\t\t" << orderTypeName << "\n"; 47 | } 48 | std::cout << "\n"; 49 | } 50 | 51 | 52 | void OrderBook::setStrategy(OrderMatchingStrategy* s) 53 | { 54 | strategy = s; 55 | } -------------------------------------------------------------------------------- /include/order.h: -------------------------------------------------------------------------------- 1 | #ifndef STOCK_TRADING_SYSTEM_ORDER_H 2 | #define STOCK_TRADING_SYSTEM_ORDER_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | namespace StockTradingSystem 10 | { 11 | 12 | enum OrderType { BUY, SELL }; 13 | 14 | class Order 15 | { 16 | public: 17 | Order(int, double, int); 18 | virtual ~Order(); 19 | virtual std::string getOrderType() const = 0; 20 | int getTraider_id() const; 21 | double getPrice() const; 22 | int getQuantity() const; 23 | std::time_t getTimestamp() const; 24 | void reduceQuantity(int); 25 | OrderType getOrdertype() const; 26 | void setOrderType(OrderType); 27 | private: 28 | int traider_id; 29 | double price; 30 | int quantity; 31 | std::time_t timestamp; 32 | OrderType ordertype; 33 | }; 34 | 35 | class MarketOrder : public Order 36 | { 37 | public: 38 | MarketOrder(int trader_id, double price, int quantity) : Order(trader_id, price, quantity) {} 39 | std::string getOrderType() const override; 40 | }; 41 | 42 | class LimitOrder : public Order 43 | { 44 | public: 45 | LimitOrder(int trader_id, double price, int quantity) : Order(trader_id, price, quantity) {} 46 | std::string getOrderType() const override; 47 | }; 48 | 49 | class OrderFactory { 50 | public: 51 | virtual std::unique_ptr createOrder(int, double, int) = 0; 52 | virtual ~OrderFactory(); 53 | }; 54 | 55 | class MarketOrderFactory : public OrderFactory { 56 | public: 57 | std::unique_ptr createOrder(int, double, int) override; 58 | }; 59 | 60 | class LimitOrderFactory : public OrderFactory { 61 | public: 62 | std::unique_ptr createOrder(int, double, int) override; 63 | }; 64 | 65 | class OrderMatchingStrategy { 66 | public: 67 | virtual void matchOrders(std::vector>&, std::vector>&) = 0; 68 | virtual ~OrderMatchingStrategy(); 69 | }; 70 | 71 | class PriceTimeOrderMatchingStrategy : public OrderMatchingStrategy { 72 | public: 73 | void matchOrders(std::vector>&, std::vector>&) override; 74 | }; 75 | 76 | } // StockTradingSystem 77 | 78 | #endif // STOCK_TRADING_SYSTEM_ORDER_H 79 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # StockTradingSystem 2 | 3 | ## Overview 4 | The Stock Trading System is a C++ application that simulates a stock trading environment. It allows multiple traders to buy and sell stocks and maintains an order book for processing these orders. This README provides an overview of the project, its design, and instructions for running the application. 5 | 6 | ## Project Structure 7 | 8 | The project is organized into several key components: 9 | 10 | - **include**: Contains header files for classes and interfaces. 11 | - **src**: Contains the source code for the application. 12 | - **main.cpp**: The entry point of the program. 13 | 14 | ### Classes 15 | The following key classes are part of the project: 16 | 17 | - **Trader**: Represents a trader who can buy and sell stocks. 18 | - **Stock**: Represents a stock with a price and name. 19 | - **Order**: Represents an order placed by a trader (base class). 20 | - **MarketOrder**: Represents a market order that buys or sells at the current market price. 21 | - **LimitOrder**: Represents a limit order with a specified price. 22 | - **OrderFactory**: Creates different types of orders (Market or Limit). 23 | - **OrderMatchingStrategy**: Defines strategies for matching buy and sell orders. 24 | - **PriceTimeOrderMatchingStrategy**: A specific matching strategy based on order prices and timestamps. 25 | - **OrderBook**: Maintains an order book and matches buy/sell orders. 26 | - **OrderMatchingStrategy**: The base class for order matching strategies. 27 | 28 | ## Design Patterns 29 | 30 | The project uses the following design patterns: 31 | 32 | - **Factory Method Pattern**: The `OrderFactory` class uses a factory method to create different types of orders (Market or Limit). 33 | - **Strategy Pattern**: The `OrderMatchingStrategy` hierarchy allows for various order matching strategies to be implemented. The `PriceTimeOrderMatchingStrategy` is an example of such a strategy. 34 | 35 | ## Running the Application 36 | 37 | To run the Stock Trading System application, follow these steps: 38 | 39 | 1. Clone repository. 40 | 41 | ```bash 42 | git clone https://github.com/NalbandyanElmira/StockTradingSystem 43 | ``` 44 | 45 | ```bash 46 | cd StockTradingSystem/build 47 | ``` 48 | 49 | ```bash 50 | make 51 | ``` 52 | 53 | 2. Execute the compiled binary. 54 | ```bash 55 | ./my_app 56 | ``` 57 | 58 | 3. The application will simulate trading with multiple traders, and the order book will be displayed at the end of the simulation. 59 | -------------------------------------------------------------------------------- /src/order.cpp: -------------------------------------------------------------------------------- 1 | #include "../include/order.h" 2 | 3 | #include 4 | #include 5 | 6 | using namespace StockTradingSystem; 7 | 8 | Order::Order(int id, double p, int q) 9 | : traider_id{id} 10 | , price{p} 11 | , quantity{q} 12 | { 13 | } 14 | 15 | Order::~Order() 16 | { 17 | } 18 | 19 | int Order::getTraider_id() const 20 | { 21 | return traider_id; 22 | } 23 | 24 | double Order::getPrice() const 25 | { 26 | return price; 27 | } 28 | 29 | int Order::getQuantity() const 30 | { 31 | return quantity; 32 | } 33 | 34 | std::time_t Order::getTimestamp() const 35 | { 36 | return timestamp; 37 | } 38 | 39 | void Order::reduceQuantity(int amount) 40 | { 41 | if (amount > 0 && amount <= quantity) 42 | { 43 | quantity -= amount; 44 | } 45 | else 46 | { 47 | throw std::out_of_range{"Amount out of range."}; 48 | } 49 | } 50 | 51 | OrderType Order::getOrdertype() const { 52 | return ordertype; 53 | } 54 | 55 | void Order::setOrderType(OrderType type) { 56 | ordertype = type; 57 | } 58 | 59 | std::string MarketOrder::getOrderType() const 60 | { 61 | return "Market Order"; 62 | } 63 | 64 | std::string LimitOrder::getOrderType() const 65 | { 66 | return "Limit Order"; 67 | } 68 | 69 | OrderFactory::~OrderFactory() 70 | { 71 | } 72 | 73 | std::unique_ptr MarketOrderFactory::createOrder(int trader_id, double price, int quantity) { 74 | return std::make_unique(trader_id, price, quantity); 75 | } 76 | 77 | std::unique_ptr LimitOrderFactory::createOrder(int trader_id, double price, int quantity) { 78 | return std::make_unique(trader_id, price, quantity); 79 | } 80 | 81 | OrderMatchingStrategy::~OrderMatchingStrategy() 82 | { 83 | } 84 | 85 | void PriceTimeOrderMatchingStrategy::matchOrders(std::vector>& buyOrders, std::vector>& sellOrders) { 86 | std::vector> matchedOrders; 87 | 88 | for (auto sellOrder = sellOrders.begin(); sellOrder != sellOrders.end(); ++sellOrder) { 89 | for (auto it = buyOrders.begin(); it != buyOrders.end();) { 90 | if ((*sellOrder)->getPrice() <= (*it)->getPrice()) { 91 | matchedOrders.push_back(*it); 92 | it = buyOrders.erase(it); // Remove the matched buy order 93 | } else { 94 | ++it; 95 | } 96 | } 97 | } 98 | 99 | // Update the buyOrders vector with remaining unmatched orders 100 | buyOrders.insert(buyOrders.end(), matchedOrders.begin(), matchedOrders.end()); 101 | } 102 | -------------------------------------------------------------------------------- /src/trader.cpp: -------------------------------------------------------------------------------- 1 | #include "../include/trader.h" 2 | 3 | #include 4 | 5 | using namespace StockTradingSystem; 6 | 7 | TraderException::TraderException(const std::string& mess) 8 | : message(mess) 9 | { 10 | } 11 | 12 | const char* TraderException::what() const noexcept 13 | { 14 | return message.c_str(); 15 | } 16 | 17 | int Trader::id_counter = 0; 18 | 19 | Trader::Trader() 20 | : name{""} 21 | , id{id_counter++} 22 | , orderFactory{nullptr} 23 | , orderBook{nullptr} 24 | { 25 | } 26 | 27 | Trader::Trader(const std::string& n) 28 | : name{n} 29 | , orderBook{nullptr} 30 | , orderFactory{nullptr} 31 | , id{id_counter++} 32 | { 33 | } 34 | 35 | Trader::Trader(const std::string& n, const std::vector& s, OrderFactory* o, OrderBook* b) 36 | : id{id_counter++} 37 | , name{n} 38 | , stocks{s} 39 | , orderFactory{o} 40 | , orderBook{b} 41 | { 42 | } 43 | 44 | void Trader::buy(const StockTradingSystem::Stock& stock, int quantity) 45 | { 46 | try 47 | { 48 | if (orderFactory != nullptr && orderBook != nullptr) { 49 | std::shared_ptr ord = orderFactory->createOrder(id, stock.getPrice(), quantity); 50 | orders.push_back(ord); 51 | if (ord != nullptr) { 52 | orderBook->addOrder(ord); 53 | } 54 | } 55 | } 56 | catch (const TraderException& e) { 57 | // Handle trader-specific exceptions 58 | std::cerr << "Trader Exception: " << e.what() << std::endl; 59 | } catch (const std::exception& e) { 60 | // Handle other exceptions (if any) 61 | std::cerr << "Exception: " << e.what() << std::endl; 62 | } 63 | } 64 | 65 | void Trader::sell(const StockTradingSystem::Stock& stock, int quantity) 66 | { 67 | try 68 | { 69 | if (orderFactory != nullptr && orderBook != nullptr) { 70 | std::shared_ptr ord = orderFactory->createOrder(id, -stock.getPrice(), quantity); 71 | orders.push_back(ord); 72 | if (ord != nullptr) { 73 | orderBook->addOrder(ord); 74 | } 75 | } 76 | } 77 | catch (const TraderException& e) { 78 | // Handle trader-specific exceptions 79 | std::cerr << "Trader Exception: " << e.what() << std::endl; 80 | } catch (const std::exception& e) { 81 | // Handle other exceptions (if any) 82 | std::cerr << "Exception: " << e.what() << std::endl; 83 | } 84 | } 85 | 86 | void Trader::trade(double buyThreshold, double sellThreshold, int buyQuantity, int sellQuantity) 87 | { 88 | // Buy when the stock price is lower than a threshold and sell when it's higher 89 | 90 | for (const Stock& stock : stocks) { 91 | if (stock.getPrice() < buyThreshold) { 92 | // Buy the stock with a fixed quantity (e.g., 100 shares) 93 | buy(stock, buyQuantity); 94 | } else if (stock.getPrice() > sellThreshold) { 95 | // Sell the stock with a fixed quantity (e.g., 50 shares) 96 | sell(stock, sellQuantity); 97 | } 98 | } 99 | } 100 | 101 | int Trader::getID() const 102 | { 103 | return id; 104 | } 105 | 106 | const std::vector>& Trader::getOrders() const { 107 | return orders; 108 | } 109 | 110 | void Trader::addStock(const Stock& st) 111 | { 112 | stocks.push_back(st); 113 | } 114 | 115 | std::vector Trader::getStocks() const 116 | { 117 | return stocks; 118 | } 119 | 120 | Trader::~Trader() 121 | { 122 | delete orderFactory; 123 | delete orderBook; 124 | } 125 | --------------------------------------------------------------------------------