The Stock Trading System is a comprehensive, full-stack simulation of a real-world investment environment. It provides a robust platform where investors can trade stocks, track their portfolios, and manage cash balances in real time. The project is heavily focused on backend database engineering, emphasizing strict concurrency control, data integrity, and complex relational modeling.
- Frontend / Application Layer: Next.js, React 19
- Styling: Tailwind CSS
- Database Engine: MySQL
- Languages: TypeScript, SQL
The system utilizes a relational database mapped across 11 normalized tables, structured through Advanced Entity-Relationship concepts:
- Strong Entities: Tables such as
USERSandSTOCKSpossess their own primary keys and exist independently. - Weak & Dependent Entities: Financial entities like
ACCOUNTS,WALLETS, andPORTFOLIOSexist in total participation with their parentINVESTORS.ON DELETE CASCADEis utilized to inherently drop associated financial records if a parent user is deleted, whileON DELETE RESTRICTprotects critical items likeSTOCKSandORDERSfrom being orphaned. - ISA Inheritance Hierarchy: Role management is centralized in a root
USERStable, branching into disjoint specialized entities:INVESTORS,ADMINS, andAUDITORS. - Associative Entities: Many-to-many relationships are resolved using bridging tables, such as
PORTFOLIO_HOLDINGS, which map varied stocks to investor portfolios.
- USERS / INVESTORS / ADMINS / AUDITORS: Hierarchical role representation.
- STOCKS & STOCK_PRICE_HISTORY: Maintains current market data and a definitive audit trail of all historical price drifts.
- ACCOUNTS / WALLETS / PORTFOLIOS: Dependent financial containers.
- PORTFOLIO_HOLDINGS: Maps the exact quantity and asset distribution per user.
- ORDERS & TRANSACTIONS: Records every trade attempt, its status (Pending, Success, Failed, Cancelled), and the resulting monetary transaction.
The application relies heavily on database computation to optimize server performance. Over 20 advanced SQL routines are utilized to provide key metrics:
- Dynamic Views: An
Investor_Net_Worthview dynamically aggregates an investor's raw cash balance alongside the real-time market value of their holdings by joiningPORTFOLIOS,PORTFOLIO_HOLDINGS, andSTOCKS. - Data Integrity Constraints: Constraints like
CHECK (balance >= 0)guarantee mathematical accuracy at the database level. - Analytical Queries: Features include grouping market caps, detecting the highest historical price deviations, identifying inactive stocks via
LEFT JOIN, and categorizing transaction sizes dynamically.
To enforce business rules independently of the application logic, the database utilizes 5 distinct triggers:
create_wallet_after_account_insert: Automates the creation of a zero-balance wallet as soon as a new investor account is provisioned.create_portfolio_after_account_insert: Provisions an empty portfolio upon account creation.order_insert(BEFORE): Intercepts new orders to mathematically validate quantities and dynamic prices, enforcing that thetotal_valuecolumn accurately reflectsquantity * order_price.order_update(BEFORE): Provides the same mathematical validation for modified trades.track_stock_price_changes: ExecutesAFTER UPDATE ON STOCKS, passively logging the drift betweenOLD.current_priceandNEW.current_priceinto the history table.
Given the heavy concurrency typical in stock trading systems, naive sequential queries lead to double-spending and race conditions. This is resolved via explicit database transaction handling:
- Serializable Trades: A simulated "Buy Order" initiates a
START TRANSACTION. - Read Locks: It applies a
LOCK IN SHARE MODEwhen verifying stock prices to prevent the price from alternating mid-trade. - Exclusive Write Locks: It applies a
FOR UPDATElock onto the investor's wallet balance, safely reserving funds. - Deadlock Resolution: The Next.js application explicitly catches
ER_LOCK_DEADLOCKMySQL errors during extreme volume, gracefully executing aROLLBACKand invoking an automated programmatic retry mechanism up to 3 times before finalizing aCOMMIT.
Follow these steps to run the project locally.
-
Clone the repository (if not already cloned):
git clone <repository_url> cd Stock-Trading-System/stock-trading-system
-
Install dependencies:
npm install
-
Configure Environment Variables: Create a
.env.localor.envfile in thestock-trading-systemdirectory and add your MySQL database credentials:DB_HOST=your_mysql_host DB_USER=your_mysql_user DB_PASSWORD=your_mysql_password DB_NAME=your_database_name
-
Initialize Database: Use the provided SQL scripts in the
scripts and queriesfolder to provision the tables, triggers, and seed the database with mock test data. -
Run the Development Server:
npm run dev
Open
http://localhost:3000with your browser to see the result.