Skip to content

Commit be13e9d

Browse files
main logic updated
1 parent a85aad4 commit be13e9d

File tree

2 files changed

+69
-2
lines changed

2 files changed

+69
-2
lines changed

.github/workflows/pipeline.yml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,11 @@ jobs:
1717
sudo apt-get install -y cppcheck
1818
cppcheck --error-exitcode=1 --enable=all --suppress=missingIncludeSystem .
1919
20+
- name: Compile and Run Unit Tests
21+
run: |
22+
g++ -o engine_test main.cpp
23+
./engine_test --test
24+
2025
- name: Build Container Image
2126
run: docker build -t trading-engine:${{ github.sha }} .
2227

main.cpp

Lines changed: 64 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,71 @@
11
#include <iostream>
2+
#include <queue>
3+
#include <vector>
4+
#include <cassert>
25
#include <thread>
36
#include <chrono>
7+
#include <string>
48

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";
769
while(true) {
870
std::this_thread::sleep_for(std::chrono::seconds(10));
971
}

0 commit comments

Comments
 (0)