📊 Project Overview
System Architecture
This is a cryptocurrency exchange trading simulator built in C++ by Muhammad Saad Amin. It simulates a real-time order matching system where users can place bids and asks for various cryptocurrency pairs.
📈 Order Matching
Implements a sophisticated bid-ask matching algorithm that pairs buyers with sellers based on price priority
💰 Wallet Management
Tracks user cryptocurrency balances and validates transactions before execution
📁 CSV Processing
Reads historical market data from CSV files to populate the order book
⏰ Time Simulation
Advances through timestamps to simulate real market progression
Application Flow
Core Components
- OrderBookEntry: Represents a single order (bid/ask) with price, amount, timestamp, and product
- OrderBook: Manages all orders, handles matching logic, and tracks market state
- Wallet: Manages user's cryptocurrency balances and validates orders
- CSVReader: Parses CSV files to load historical market data
- MerkelMain: User interface and main application controller
📚 OrderBook System
OrderBookEntry.h - Data Structure
📝 Explanation
The OrderBookType enum defines four states:
- bid: A buy order (user wants to purchase cryptocurrency)
- ask: A sell order (user wants to sell cryptocurrency)
- sale: A completed transaction between a bid and ask
- unknown: Error state for invalid order types
OrderBookEntry Class
🔍 Key Features
- Static Comparators: Used with std::sort to organize orders by timestamp or price
- compareByPriceAsc: Sorts asks from lowest to highest (sellers willing to accept less go first)
- compareByPriceDesc: Sorts bids from highest to lowest (buyers willing to pay more go first)
- Product Format: Uses "BASE/QUOTE" notation (e.g., BTC/USDT means buying BTC with USDT)
OrderBook Class - Core Matching Engine
⚙️ Matching Algorithm Logic
The algorithm implements price-time priority:
- Sort asks (sells) from lowest price to highest
- Sort bids (buys) from highest price to lowest
- Try to match the best buyer with the best seller
- If bid price ≥ ask price, a trade can occur!
💡 Trading Logic Examples
Example 1 - Perfect Match:
- Ask: Sell 5 BTC at $40,000
- Bid: Buy 5 BTC at $41,000
- Result: Sale of 5 BTC at $40,000 (seller's price)
Example 2 - Partial Fill (Bid Larger):
- Ask: Sell 3 BTC at $40,000
- Bid: Buy 10 BTC at $41,000
- Result: Sale of 3 BTC at $40,000, bid remains for 7 BTC
Example 3 - Partial Fill (Ask Larger):
- Ask: Sell 10 BTC at $40,000
- Bid: Buy 3 BTC at $41,000
- Result: Sale of 3 BTC at $40,000, ask remains for 7 BTC
📁 CSV Reader - Data Import System
Main Reading Function
📖 How It Works
- Opens the CSV file using ifstream
- Reads each line of the file
- Tokenizes (splits) the line into fields using commas
- Converts the tokens into an OrderBookEntry object
- Error handling: If any line is malformed, it's skipped with an error message
- Returns all successfully parsed entries
Tokenization Function
✂️ Tokenization Process
This function splits a CSV line like:
2020/03/17 17:01:24,BTC/USDT,ask,9500.50,0.5
Into separate tokens:
- tokens[0] = "2020/03/17 17:01:24" (timestamp)
- tokens[1] = "BTC/USDT" (product)
- tokens[2] = "ask" (order type)
- tokens[3] = "9500.50" (price)
- tokens[4] = "0.5" (amount)
String to OrderBookEntry Conversion
🔄 Conversion Process
- Validation: Ensures exactly 5 tokens exist
- Type Conversion: Uses std::stod to convert price/amount strings to doubles
- Error Handling: Catches conversion failures (e.g., "abc" → double)
- Object Creation: Constructs OrderBookEntry with parsed data
💼 Wallet - Balance Management System
Currency Storage
🗂️ Data Structure
The wallet uses a std::map to store balances:
- Key-value pairs allow quick lookup: O(log n)
- Example: {"BTC": 1.5, "USDT": 50000.0, "ETH": 10.0}
- Automatically handles new currencies when inserted
Insert Currency Function
➕ Adding Funds
This function safely adds cryptocurrency to the wallet:
- Validation: Rejects negative amounts
- New Currency: If currency doesn't exist, starts at 0
- Existing Currency: Adds to current balance
- Example: insertCurrency("BTC", 0.5) adds 0.5 BTC
Remove Currency Function
➖ Removing Funds
This function safely removes cryptocurrency with multiple checks:
- Negative Check: Prevents removing negative amounts
- Existence Check: Verifies currency exists in wallet
- Balance Check: Ensures sufficient funds before deduction
- Returns: true if successful, false if failed
Order Fulfillment Validation
✅ Order Validation Logic
For ASK (Sell) Orders:
- Product: "BTC/USDT", Amount: 0.5
- Need: 0.5 BTC (base currency)
- Check: Do we have 0.5 BTC in wallet?
For BID (Buy) Orders:
- Product: "BTC/USDT", Price: $40,000, Amount: 0.5
- Need: 0.5 × $40,000 = $20,000 USDT (quote currency)
- Check: Do we have $20,000 USDT in wallet?
Wallet Display Function
📊 Wallet Display
Creates a formatted string showing all balances:
BTC : 1.500000
ETH : 10.000000
USDT : 50000.000000
🎮 Main & MerkelMain - User Interface
Application Entry Point
🚀 Program Start
Simple and clean:
- Creates a MerkelMain instance
- Calls init() to start the interactive simulation
- Everything else is handled by MerkelMain
Main Loop - init() Function
🔄 Infinite Loop
The application runs continuously:
- Initialize time to earliest timestamp in data
- Display menu options to user
- Get user's choice (1-6)
- Process the choice
- Repeat forever (until program closed)
Menu Display
📋 Menu Options
- Option 1: Help - Explains the game objective
- Option 2: Market Stats - Shows current prices and order counts
- Option 3: Place Ask - Sell cryptocurrency
- Option 4: Place Bid - Buy cryptocurrency
- Option 5: View Wallet - Check balances
- Option 6: Advance Time - Move to next timestamp
Market Statistics Display
📈 Market Analysis
For each trading pair (BTC/USDT, ETH/USDT, etc.):
- Shows how many sell orders exist
- Displays highest and lowest asking prices
- Helps user make informed trading decisions
- Example output:
Product: BTC/USDT
Asks seen: 25
Max ask: 41500.00
Min ask: 39800.00
Placing an Ask (Sell Order)
💰 Selling Process
User Input Format: ETH/BTC,200,0.5
- Product: ETH/BTC
- Price: 200 (BTC per ETH)
- Amount: 0.5 ETH
Validation Steps:
- Parse input into 3 tokens
- Create OrderBookEntry object
- Check wallet has 0.5 ETH
- If yes, add order to book
- If no, reject with error message
Time Advancement & Order Matching
⏰ Time Progression
When user chooses option 6:
- For each trading pair (BTC/USDT, ETH/USDT, etc.)
- Run the matching algorithm
- Execute all possible trades
- Display completed sales
- Move to next timestamp
- If at end of data, wrap back to beginning
This simulates the passage of time in the market!
Member Variables
🏗️ Application State
- wallet: Tracks user's balances (initially empty)
- currentTime: Current position in market timeline
- orderBook: All market orders loaded from CSV file
These three components work together to create the complete trading simulation!
🎯 Complete System Flow
- Initialization: Load CSV data → Populate OrderBook → Set starting time
- User Loop: Display menu → Get input → Process action
- Trading: Validate wallet → Place order → Wait for matching
- Matching: Advance time → Match bids/asks → Execute trades → Update wallets
- Repeat: Continue simulation indefinitely