|
1 | 1 | #include <iostream> |
| 2 | +#include <queue> |
| 3 | +#include <vector> |
| 4 | +#include <cassert> |
2 | 5 | #include <thread> |
3 | 6 | #include <chrono> |
| 7 | +#include <string> |
4 | 8 |
|
5 | | -int main() { |
6 | | - std::cout << "Mock Trading Engine Initialized." << std::endl; |
| 9 | +struct Order { |
| 10 | + int id; |
| 11 | + double price; |
| 12 | + int quantity; |
| 13 | + bool is_buy; |
| 14 | +}; |
| 15 | + |
| 16 | +struct CompareBuy { |
| 17 | + bool operator()(const Order& a, const Order& b) { return a.price < b.price; } |
| 18 | +}; |
| 19 | + |
| 20 | +struct CompareSell { |
| 21 | + bool operator()(const Order& a, const Order& b) { return a.price > b.price; } |
| 22 | +}; |
| 23 | + |
| 24 | +class OrderBook { |
| 25 | + std::priority_queue<Order, std::vector<Order>, CompareBuy> buys; |
| 26 | + std::priority_queue<Order, std::vector<Order>, CompareSell> sells; |
| 27 | + int trades_executed = 0; |
| 28 | + |
| 29 | +public: |
| 30 | + void addOrder(const Order& order) { |
| 31 | + if (order.is_buy) buys.push(order); |
| 32 | + else sells.push(order); |
| 33 | + match(); |
| 34 | + } |
| 35 | + |
| 36 | + void match() { |
| 37 | + while (!buys.empty() && !sells.empty() && buys.top().price >= sells.top().price) { |
| 38 | + Order b = buys.top(); buys.pop(); |
| 39 | + Order s = sells.top(); sells.pop(); |
| 40 | + int traded = std::min(b.quantity, s.quantity); |
| 41 | + |
| 42 | + b.quantity -= traded; |
| 43 | + s.quantity -= traded; |
| 44 | + trades_executed++; |
| 45 | + |
| 46 | + if (b.quantity > 0) buys.push(b); |
| 47 | + if (s.quantity > 0) sells.push(s); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + int getTrades() const { return trades_executed; } |
| 52 | +}; |
| 53 | + |
| 54 | +void runTests() { |
| 55 | + OrderBook book; |
| 56 | + book.addOrder({1, 100.5, 10, true}); |
| 57 | + book.addOrder({2, 100.0, 5, false}); |
| 58 | + assert(book.getTrades() == 1); |
| 59 | + std::cout << "Unit Tests Passed.\n"; |
| 60 | +} |
| 61 | + |
| 62 | +int main(int argc, char* argv[]) { |
| 63 | + if (argc > 1 && std::string(argv[1]) == "--test") { |
| 64 | + runTests(); |
| 65 | + return 0; |
| 66 | + } |
| 67 | + |
| 68 | + std::cout << "Trading Engine Active. Waiting for orders...\n"; |
7 | 69 | while(true) { |
8 | 70 | std::this_thread::sleep_for(std::chrono::seconds(10)); |
9 | 71 | } |
|
0 commit comments