-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
1165 lines (1002 loc) · 40.5 KB
/
Copy pathmain.cpp
File metadata and controls
1165 lines (1002 loc) · 40.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <limits>
#include <algorithm>
#include <utility> // for std::pair
#include <stdexcept> // Required for standard exception types
// --- NEW ADDITION ---
#include <curl/curl.h> // For making HTTP requests
#include "json.hpp" // For parsing JSON (make sure json.hpp is in your project)
#include <chrono> // For std::this_thread::sleep_for
#include <thread> // For std::this_thread
// --- END NEW ADDITION ---
using namespace std;
// --- NEW ADDITION ---
using json = nlohmann::json; // Alias for nlohmann::json
// --- END NEW ADDITION ---
class User;
class Exchange;
class AuthManager;
class LimitOrderManager;
// --- NEW ADDITION ---
// Callback function to write cURL response data into a string
static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp) {
((std::string*)userp)->append((char*)contents, size * nmemb);
return size * nmemb;
}
// --- END NEW ADDITION ---
class Crypto_currency {
private:
std::string name;
std::string symbol;
double price;
public:
Crypto_currency(const std::string& name, const std::string& symbol, double price);
const std::string& getName() const;
const std::string& getSymbol() const;
double getPrice() const;
void setPrice(double newPrice);
bool operator==(const Crypto_currency& other) const { return symbol == other.symbol; }
bool operator!=(const Crypto_currency& other) const { return !(*this == other); }
friend std::ostream& operator<<(std::ostream& os, const Crypto_currency& c);
};
Crypto_currency::Crypto_currency(const std::string& name, const std::string& symbol, double price)
: name(name), symbol(symbol), price(price) {}
const std::string& Crypto_currency::getName() const { return name; }
const std::string& Crypto_currency::getSymbol() const { return symbol; }
double Crypto_currency::getPrice() const { return price; }
void Crypto_currency::setPrice(double newPrice) { price = newPrice; }
inline std::ostream& operator<<(std::ostream& os, const Crypto_currency& c) {
os << c.getSymbol() << " (" << c.getName() << ") $" << std::fixed << std::setprecision(2) << c.getPrice();
return os;
}
class Wallet {
private:
double cashBalance;
std::map<std::string, double> holdings;
public:
Wallet() : cashBalance(0.0) {}
explicit Wallet(double initialCash) : cashBalance(initialCash) {}
double getCash() const;
void deposit(double amount);
bool withdraw(double amount);
double getQty(const std::string& symbol) const;
void addQty(const std::string& symbol, double units);
bool removeQty(const std::string& symbol, double units);
void print() const;
const std::map<std::string, double>& getHoldings() const;
Wallet& operator+=(double amount) { deposit(amount); return *this; }
Wallet& operator-=(double amount) { withdraw(amount); return *this; }
Wallet& operator+=(const std::pair<std::string,double>& asset) { addQty(asset.first, asset.second); return *this; }
Wallet& operator-=(const std::pair<std::string,double>& asset) { removeQty(asset.first, asset.second); return *this; }
bool operator==(const Wallet& other) const { return cashBalance == other.cashBalance && holdings == other.holdings; }
bool operator!=(const Wallet& other) const { return !(*this == other); }
friend std::ostream& operator<<(std::ostream& os, const Wallet& w);
};
double Wallet::getCash() const { return cashBalance; }
void Wallet::deposit(double amount) {
if (amount > 0) {
cashBalance += amount;
}
}
bool Wallet::withdraw(double amount) {
if (amount > 0 && amount <= cashBalance) {
cashBalance -= amount;
return true;
}
return false;
}
double Wallet::getQty(const std::string& symbol) const {
auto it = holdings.find(symbol);
return (it != holdings.end()) ? it->second : 0.0;
}
void Wallet::addQty(const std::string& symbol, double units) {
if (units > 0) {
holdings[symbol] += units;
}
}
bool Wallet::removeQty(const std::string& symbol, double units) {
if (units > 0 && getQty(symbol) >= units) {
holdings[symbol] -= units;
if (holdings[symbol] < 1e-9) {
holdings.erase(symbol);
}
return true;
}
return false;
}
void Wallet::print() const {
std::cout << "Cash: $" << std::fixed << std::setprecision(2) << cashBalance << "\n";
std::cout << "Holdings:\n";
if (holdings.empty()) {
std::cout << " No holdings yet.\n";
} else {
for (const auto& pair : holdings) {
std::cout << " " << pair.first << ": " << pair.second << " units\n";
}
}
}
const std::map<std::string, double>& Wallet::getHoldings() const { return holdings; }
inline std::ostream& operator<<(std::ostream& os, const Wallet& w) {
os << "Cash: $" << std::fixed << std::setprecision(2) << w.cashBalance << "\nHoldings:\n";
if (w.holdings.empty()) {
os << " No holdings yet.\n";
} else {
for (const auto& h : w.holdings) {
os << " " << h.first << ": " << h.second << " units\n";
}
}
return os;
}
class User {
private:
std::string name;
Wallet wallet;
public:
User(const std::string& name, double cash = 0.0);
const std::string& getName() const;
Wallet& getWallet();
const Wallet& getWallet() const;
void printSummary() const;
friend std::ostream& operator<<(std::ostream& os, const User& u);
};
User::User(const std::string& name, double cash) : name(name), wallet(cash) {}
const std::string& User::getName() const { return name; }
Wallet& User::getWallet() { return wallet; }
const Wallet& User::getWallet() const { return wallet; }
void User::printSummary() const {
std::cout << "\n--- User Portfolio ---\n";
std::cout << "Welcome, " << name << "!\n";
wallet.print();
std::cout << "----------------------\n";
}
inline std::ostream& operator<<(std::ostream& os, const User& u) {
os << "--- User Portfolio ---\n";
os << "User: " << u.name << "\n";
os << u.wallet;
os << "----------------------\n";
return os;
}
class Exchange {
private:
std::vector<Crypto_currency> listings;
public:
static int totalTrades;
void add_crypto_listing(const Crypto_currency& c);
Crypto_currency* find(const std::string& symbol);
double priceOf(const std::string& symbol);
bool isListingsEmpty() const;
void print() const;
const std::vector<Crypto_currency>& getListings() const;
};
int Exchange::totalTrades = 0;
void Exchange::add_crypto_listing(const Crypto_currency& c) { listings.push_back(c); }
Crypto_currency* Exchange::find(const std::string& symbol) {
for (auto& crypto : listings) {
if (crypto.getSymbol() == symbol) {
return &crypto;
}
}
return nullptr;
}
double Exchange::priceOf(const std::string& symbol) {
Crypto_currency* crypto = find(symbol);
return (crypto != nullptr) ? crypto->getPrice() : -1.0;
}
bool Exchange::isListingsEmpty() const { return listings.empty(); }
void Exchange::print() const {
std::cout << "\n--- Crypto Exchange Listings ---\n";
for (const auto& c : listings) {
std::cout << " " << std::setw(5) << c.getSymbol()
<< " " << std::setw(12) << c.getName()
<< " $" << std::fixed << std::setprecision(2) << c.getPrice() << "\n";
}
std::cout << "Total Trades on Exchange: " << totalTrades << "\n";
std::cout << "-------------------------------\n";
}
const std::vector<Crypto_currency>& Exchange::getListings() const { return listings; }
class Trade {
protected:
std::string symbol;
double units;
public:
Trade(const std::string& sym, double u);
virtual ~Trade() = default;
virtual bool execute(User& user, Exchange& ex) = 0;
};
Trade::Trade(const std::string& sym, double u) : symbol(sym), units(u) {}
class BuyTrade : public Trade {
public:
BuyTrade(const std::string& sym, double u);
bool execute(User& user, Exchange& ex) override;
};
BuyTrade::BuyTrade(const std::string& sym, double u) : Trade(sym, u) {}
bool BuyTrade::execute(User& user, Exchange& ex) {
double px = ex.priceOf(symbol);
if (px < 0) {
std::cout << "Symbol not found.\n";
return false;
}
double cost = px * units;
if (!user.getWallet().withdraw(cost)) {
std::cout << "Insufficient cash to complete purchase.\n";
return false;
}
user.getWallet().addQty(symbol, units);
Exchange::totalTrades++;
std::cout << "SUCCESS: Bought " << units << " " << symbol << " for $" << std::fixed << std::setprecision(2) << cost << "\n";
return true;
}
class SellTrade : public Trade {
public:
SellTrade(const std::string& sym, double u);
bool execute(User& user, Exchange& ex) override;
};
SellTrade::SellTrade(const std::string& sym, double u) : Trade(sym, u) {}
bool SellTrade::execute(User& user, Exchange& ex) {
double px = ex.priceOf(symbol);
if (px < 0) {
std::cout << "Symbol not found.\n";
return false;
}
if (!user.getWallet().removeQty(symbol, units)) {
std::cout << "Insufficient units to sell.\n";
return false;
}
double earnings = px * units;
user.getWallet().deposit(earnings);
Exchange::totalTrades++;
std::cout << "SUCCESS: Sold " << units << " " << symbol << " for $" << std::fixed << std::setprecision(2) << earnings << "\n";
return true;
}
class AuthManager {
private:
const std::string user_file = "users.txt";
unsigned long simpleHash(const std::string& str) const;
public:
User* login();
User* signUp();
void saveUserData(const User& user) const;
User* loadUserData(const std::string& username) const;
};
// Use a simple deterministic hash (djb2) that returns unsigned long
unsigned long AuthManager::simpleHash(const std::string& str) const {
unsigned long hash = 5381;
for (unsigned char c : str) {
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
}
return hash;
}
User* AuthManager::login() {
std::string username, password;
try {
std::ifstream file(user_file);
if (!file) {
std::cout << "No users have signed up yet.\n";
return nullptr;
}
std::cout << "--- User Login ---\n";
std::cout << "Enter username: ";
std::cin >> username;
std::cout << "Enter password: ";
std::cout << "if forgot password write 1:";
std::cin >> password;
if (password == "1") {
file.clear();
file.seekg(0);
std::string line;
while (std::getline(file, line)) {
std::stringstream ss(line);
std::string stored_user;
unsigned long stored_hash;
ss >> stored_user >> stored_hash;
if (username == stored_user) {
std::cout << "Stored password hash for user '" << username << "': " << stored_hash << "\n";
break;
}
}
return nullptr;
}
std::string line;
while (std::getline(file, line)) {
if (line.empty()) continue;
std::stringstream ss(line);
std::string stored_user;
unsigned long stored_hash;
ss >> stored_user >> stored_hash;
if (username == stored_user) {
if (simpleHash(password) == stored_hash) {
std::cout << "Login successful! Welcome, " << username << ".\n";
return loadUserData(username);
} else {
std::cout << "Invalid password.\n";
return nullptr;
}
}
}
} catch (const std::ifstream::failure& e) {
std::cerr << "Exception opening/reading user file: " << e.what() << '\n';
return nullptr;
}
std::cout << "User not found.\n";
return nullptr;
}
User* AuthManager::signUp() {
std::string username, password;
std::cout << "--- User Sign Up ---\n";
std::cout << "Choose a username: ";
std::cin >> username;
try {
std::ifstream infile(user_file);
if (infile) {
std::string line;
while (std::getline(infile, line)) {
if (line.empty()) continue;
std::stringstream ss(line);
std::string stored_user;
ss >> stored_user;
if (username == stored_user) {
std::cout << "Username already exists. Please try another.\n";
return nullptr;
}
}
}
infile.close();
std::cout << "Choose a password: \n Password should contain atleast size of 5 having character and digit\n";
std::cin >> password;
if (password.size() < 5) {
std::cout << "Not a valid password\n";
return nullptr;
}
std::ofstream outfile(user_file, std::ios::app);
if (!outfile) {
std::cerr << "Error: Could not open user file for writing.\n";
return nullptr;
}
outfile << username << " " << simpleHash(password) << std::endl;
std::cout << "Sign up successful! Welcome, " << username << ".\n";
User* newUser = new User(username, 10000.0);
saveUserData(*newUser);
return newUser;
} catch (const std::ios_base::failure& e) {
std::cerr << "Exception handling user file: " << e.what() << '\n';
return nullptr;
}
catch (const std::bad_alloc& e) {
std::cerr << "Memory allocation failed: " << e.what() << '\n';
return nullptr;
}
}
void AuthManager::saveUserData(const User& user) const {
std::string filename = user.getName() + "_wallet.csv";
try {
std::ofstream file(filename);
if (!file) {
std::cerr << "Error: Could not save user data for " << user.getName() << std::endl;
return;
}
file << user.getWallet().getCash() << std::endl;
for (const auto& holding : user.getWallet().getHoldings()) {
file << holding.first << "," << holding.second << std::endl;
}
} catch (const std::ofstream::failure& e) {
std::cerr << "Exception writing to user wallet file: " << e.what() << '\n';
}
}
User* AuthManager::loadUserData(const std::string& username) const {
std::string filename = username + "_wallet.csv";
try {
std::ifstream file(filename);
if (!file) {
User* newUser = new User(username, 10000.0);
saveUserData(*newUser);
return newUser;
}
double cash;
file >> cash;
User* user = new User(username, cash);
std::string line;
std::getline(file, line); // Consume rest of the first line
while (std::getline(file, line)) {
if (line.empty()) continue;
std::stringstream ss(line);
std::string symbol;
double units;
std::getline(ss, symbol, ',');
ss >> units;
if (!symbol.empty()) {
user->getWallet().addQty(symbol, units);
}
}
return user;
} catch (const std::ifstream::failure& e) {
std::cerr << "Exception reading user wallet file: " << e.what() << '\n';
return nullptr;
} catch (const std::bad_alloc& e) {
std::cerr << "Memory allocation failed: " << e.what() << '\n';
return nullptr;
}
}
class LimitOrder {
public:
int orderId;
std::string username;
std::string symbol;
double units;
double desiredPrice;
bool isBuyOrder;
LimitOrder(int id, std::string uname, std::string sym, double u, double price, bool isBuy);
void display() const;
friend std::ostream& operator<<(std::ostream& os, const LimitOrder& lo);
};
LimitOrder::LimitOrder(int id, std::string uname, std::string sym, double u, double price, bool isBuy)
: orderId(id), username(std::move(uname)), symbol(std::move(sym)), units(u), desiredPrice(price), isBuyOrder(isBuy) {}
void LimitOrder::display() const {
std::cout << "ID: " << std::setw(4) << orderId
<< " | " << (isBuyOrder ? "BUY " : "SELL")
<< " | " << std::setw(5) << symbol
<< " | Units: " << std::setw(8) << std::fixed << std::setprecision(4) << units
<< " | Target Price: $" << std::setw(10) << std::fixed << std::setprecision(2) << desiredPrice << std::endl;
}
inline std::ostream& operator<<(std::ostream& os, const LimitOrder& lo) {
os << "ID: " << std::setw(4) << lo.orderId
<< " | " << (lo.isBuyOrder ? "BUY " : "SELL")
<< " | " << std::setw(5) << lo.symbol
<< " | Units: " << std::setw(8) << std::fixed << std::setprecision(4) << lo.units
<< " | Target Price: $" << std::setw(10) << std::fixed << std::setprecision(2) << lo.desiredPrice;
return os;
}
class LimitOrderManager {
private:
std::vector<LimitOrder> orders;
const std::string filename = "limit_orders.txt";
const std::string id_filename = "order_id.txt";
static int nextOrderId;
void loadNextOrderId();
void saveNextOrderId() const;
void loadOrders();
void saveOrders() const;
public:
LimitOrderManager();
~LimitOrderManager();
void addOrder(const std::string& username, const std::string& symbol, double units, double price, bool isBuy);
void displayUserOrders(const std::string& username) const;
void checkAndExecuteUserOrders(User& user, Exchange& ex);
void checkAndExecuteAllOrders(Exchange& ex, AuthManager& auth);
};
int LimitOrderManager::nextOrderId = 1;
LimitOrderManager::LimitOrderManager() {
try {
loadNextOrderId();
loadOrders();
} catch (const std::exception& e) {
std::cerr << "Error during LimitOrderManager initialization: " << e.what() << '\n';
}
}
LimitOrderManager::~LimitOrderManager() {
try {
saveNextOrderId();
} catch (const std::exception& e) {
std::cerr << "Error during LimitOrderManager destruction: " << e.what() << '\n';
}
}
void LimitOrderManager::loadNextOrderId() {
try {
std::ifstream idFile(id_filename);
if (idFile) idFile >> nextOrderId;
if (nextOrderId == 0) nextOrderId = 1;
} catch (const std::ifstream::failure& e) {
std::cerr << "Exception loading next order ID: " << e.what() << '\n';
}
}
void LimitOrderManager::saveNextOrderId() const {
try {
std::ofstream idFile(id_filename);
if (idFile) idFile << nextOrderId;
} catch (const std::ofstream::failure& e) {
std::cerr << "Exception saving next order ID: " << e.what() << '\n';
}
}
void LimitOrderManager::loadOrders() {
orders.clear();
try {
std::ifstream file(filename);
if (!file) return;
int id, isBuyInt;
std::string username, symbol;
double units, price;
while (file >> id >> username >> symbol >> units >> price >> isBuyInt) {
orders.emplace_back(id, username, symbol, units, price, (isBuyInt == 1));
}
} catch (const std::ifstream::failure& e) {
std::cerr << "Exception loading limit orders: " << e.what() << '\n';
}
}
void LimitOrderManager::saveOrders() const {
try {
std::ofstream file(filename);
if (!file) return;
for (const auto& order : orders) {
file << order.orderId << " " << order.username << " " << order.symbol << " "
<< order.units << " " << order.desiredPrice << " " << (order.isBuyOrder ? 1 : 0) << std::endl;
}
} catch (const std::ofstream::failure& e) {
std::cerr << "Exception saving limit orders: " << e.what() << '\n';
}
}
void LimitOrderManager::addOrder(const std::string& username, const std::string& symbol, double units, double price, bool isBuy) {
try {
orders.emplace_back(nextOrderId++, username, symbol, units, price, isBuy);
saveOrders();
std::cout << "Limit order placed successfully.\n";
} catch (const std::bad_alloc& e) {
std::cerr << "Memory allocation failed for new order: " << e.what() << '\n';
}
}
void LimitOrderManager::displayUserOrders(const std::string& username) const {
std::cout << "\n--- Your Pending Limit Orders ---\n";
bool found = false;
for (const auto& order : orders) {
if (order.username == username) {
order.display();
found = true;
}
}
if (!found) std::cout << "You have no pending limit orders.\n";
}
void LimitOrderManager::checkAndExecuteUserOrders(User& user, Exchange& ex) {
bool ordersChanged = false;
try {
auto it = std::remove_if(orders.begin(), orders.end(), [&](LimitOrder& order) {
if (order.username != user.getName()) return false;
double currentPrice = ex.priceOf(order.symbol);
if (currentPrice < 0) return false;
bool shouldExecute = (order.isBuyOrder && currentPrice <= order.desiredPrice) ||
(!order.isBuyOrder && currentPrice >= order.desiredPrice);
if (shouldExecute) {
std::cout << "\n[!] EXECUTING YOUR LIMIT ORDER ID: " << order.orderId << std::endl;
bool success = order.isBuyOrder ? BuyTrade(order.symbol, order.units).execute(user, ex)
: SellTrade(order.symbol, order.units).execute(user, ex);
if (success) ordersChanged = true;
else std::cout << "[!] Limit Order ID " << order.orderId << " failed (insufficient funds/units).\n";
return success;
}
return false;
});
if (ordersChanged) {
orders.erase(it, orders.end());
saveOrders();
}
} catch (const std::exception& e) {
std::cerr << "An unexpected error occurred while checking user orders: " << e.what() << '\n';
}
}
void LimitOrderManager::checkAndExecuteAllOrders(Exchange& ex, AuthManager& auth) {
bool ordersChanged = false;
try {
auto it = std::remove_if(orders.begin(), orders.end(), [&](LimitOrder& order) {
double currentPrice = ex.priceOf(order.symbol);
if (currentPrice < 0) return false;
bool shouldExecute = (order.isBuyOrder && currentPrice <= order.desiredPrice) ||
(!order.isBuyOrder && currentPrice >= order.desiredPrice);
if (shouldExecute) {
User* owner = auth.loadUserData(order.username);
if (!owner) return false;
std::cout << "\n[!] EXECUTING GLOBAL LIMIT ORDER ID: " << order.orderId << " for user " << order.username << std::endl;
bool success = order.isBuyOrder ? BuyTrade(order.symbol, order.units).execute(*owner, ex)
: SellTrade(order.symbol, order.units).execute(*owner, ex);
if (success) {
auth.saveUserData(*owner);
ordersChanged = true;
} else {
std::cout << "[!] Global Limit Order ID " << order.orderId << " failed.\n";
}
delete owner;
return success;
}
return false;
});
if (ordersChanged) {
orders.erase(it, orders.end());
saveOrders();
}
} catch (const std::exception& e) {
std::cerr << "An unexpected error occurred while checking all orders: " << e.what() << '\n';
}
}
void clearInput() {
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
template <typename T>
T getNumericInput(const std::string& prompt) {
T value;
std::cout << prompt;
while (!(std::cin >> value)) {
std::cout << "Wrong input, enter a numeric value: ";
clearInput();
}
return value;
}
void saveCryptoData(const Exchange& ex) {
try {
std::ofstream file("crypto_data.csv");
if (!file) return;
for (const auto& crypto : ex.getListings()) {
file << crypto.getName() << "," << crypto.getSymbol() << "," << crypto.getPrice() << std::endl;
}
} catch (const std::ofstream::failure& e) {
std::cerr << "Exception writing to crypto data file: " << e.what() << '\n';
}
}
void loadCryptoData(Exchange& ex) {
try {
std::ifstream file("crypto_data.csv");
if (!file) return;
std::string line;
while (std::getline(file, line)) {
if (line.empty()) continue;
std::stringstream ss(line);
std::string name, symbol, price_str;
std::getline(ss, name, ',');
std::getline(ss, symbol, ',');
std::getline(ss, price_str);
if (!name.empty() && !symbol.empty() && !price_str.empty()) {
try {
ex.add_crypto_listing(Crypto_currency(name, symbol, std::stod(price_str)));
} catch (const std::invalid_argument& ia) {
std::cerr << "Invalid argument: " << ia.what() << " for price: " << price_str << '\n';
} catch (const std::out_of_range& oor) {
std::cerr << "Out of Range error: " << oor.what() << " for price: " << price_str << '\n';
}
}
}
} catch (const std::ifstream::failure& e) {
std::cerr << "Exception reading crypto data file: " << e.what() << '\n';
}
}
void seedExchange(Exchange& ex) {
ex.add_crypto_listing(Crypto_currency("Bitcoin", "BTC", 60000.0));
ex.add_crypto_listing(Crypto_currency("Ether", "ETH", 2500.0));
ex.add_crypto_listing(Crypto_currency("Solana", "SOL", 150.0));
}
// --- NEW ADDITION ---
// Function to update crypto prices from CoinGecko API
void updateCryptoPricesFromAPI(Exchange& ex) {
CURL *curl;
CURLcode res;
std::string readBuffer;
std::string apiUrl = "https://api.coingecko.com/api/v3/simple/price?ids=";
std::string idsParam;
// Map your exchange's symbols (BTC, ETH) to CoinGecko's IDs (bitcoin, ethereum)
// IMPORTANT: You MUST update this map if you add more cryptos
std::map<std::string, std::string> symbolToIdMap = {
{"BTC", "bitcoin"},
{"ETH", "ethereum"},
{"SOL", "solana"}
};
const auto& listings = ex.getListings();
if (listings.empty()) {
std::cout << "[API] No listings found in exchange to update prices for." << std::endl;
return;
}
// Build the 'ids' parameter for the API call (e.g., "bitcoin%2Cethereum%2Csolana")
for (size_t i = 0; i < listings.size(); ++i) {
auto it = symbolToIdMap.find(listings[i].getSymbol());
if (it != symbolToIdMap.end()) {
idsParam += it->second; // Use CoinGecko ID
if (i < listings.size() - 1) {
idsParam += "%2C"; // URL encoded comma
}
} else {
std::cout << "[API Warning] No CoinGecko ID found for symbol: " << listings[i].getSymbol() << std::endl;
}
}
// Remove trailing %2C if it exists
if (!idsParam.empty() && idsParam.length() >= 3 && idsParam.substr(idsParam.length() - 3) == "%2C") {
idsParam.erase(idsParam.length() - 3);
}
if (idsParam.empty()) {
std::cout << "[API] No valid CoinGecko IDs found for listed symbols." << std::endl;
return;
}
apiUrl += idsParam + "&vs_currencies=usd";
// std::cout << "[API] Fetching live prices... (" << apiUrl << ")" << std::endl; // Commented out to reduce noise
curl_global_init(CURL_GLOBAL_ALL);
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, apiUrl.c_str());
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcurl-agent/1.0"); // Some APIs require a user agent
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10L); // 10 seconds timeout
res = curl_easy_perform(curl);
if(res != CURLE_OK) {
std::cerr << "[API Error] curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;
} else {
long http_code = 0;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
if (http_code == 200) {
try {
json apiData = json::parse(readBuffer);
// Reverse map for lookup: coingecko_id -> symbol
std::map<std::string, std::string> idToSymbolMap;
for(const auto& pair : symbolToIdMap) {
idToSymbolMap[pair.second] = pair.first;
}
// Iterate through the received JSON
for (auto it = apiData.begin(); it != apiData.end(); ++it) {
std::string coingeckoId = it.key();
if (it.value().contains("usd")) {
double newPrice = it.value()["usd"].get<double>();
auto symbolIt = idToSymbolMap.find(coingeckoId);
if (symbolIt != idToSymbolMap.end()) {
Crypto_currency* crypto = ex.find(symbolIt->second);
if (crypto) {
// Only print if price changed noticeably
if (std::abs(crypto->getPrice() - newPrice) > 0.01) {
// std::cout << "[API Update] " << crypto->getSymbol() << " price set to $" << std::fixed << std::setprecision(2) << newPrice << std::endl;
}
crypto->setPrice(newPrice);
}
}
}
}
// std::cout << "[API] Live prices updated successfully." << std::endl; // Commented out to reduce noise
} catch (json::parse_error& e) {
std::cerr << "[API JSON Error] Failed to parse response: " << e.what() << std::endl;
std::cerr << "Response was: " << readBuffer << std::endl;
} catch (const std::exception& e) {
std::cerr << "[API Error] Error processing price data: " << e.what() << std::endl;
}
} else {
std::cerr << "[API HTTP Error] Received HTTP status code: " << http_code << std::endl;
}
}
curl_easy_cleanup(curl);
} else {
std::cerr << "[API Error] curl_easy_init() failed." << std::endl;
}
curl_global_cleanup();
}
// --- END NEW ADDITION ---
void adminMenu(Exchange& ex, AuthManager& auth, LimitOrderManager& limitManager) {
while (true) {
std::cout << "\n--- Admin Menu ---\n"
<< "1) Update Crypto Price (Manual %)\n"
<< "2) Fetch Live API Prices\n"
<< "0) Logout\n> ";
int choice = getNumericInput<int>("");
if (choice == 0) break;
switch (choice) {
case 1: {
std::string sym;
std::cout << "Update % for which symbol? ";
std::cin >> sym;
double pct = getNumericInput<double>("Percent change (+/-): ");
int inc = getNumericInput<int>("Increase? (1=yes, 0=no): ");
Crypto_currency* crypto = ex.find(sym);
if (crypto) {
double p = crypto->getPrice();
double delta = p * (pct / 100.0);
crypto->setPrice(inc == 1 ? p + delta : p - delta);
std::cout << "[OK] " << sym << " is now $" << crypto->getPrice() << "\n";
std::cout << "Checking all pending limit orders against new price...\n";
limitManager.checkAndExecuteAllOrders(ex, auth);
} else {
std::cout << "[ERR] Symbol not found\n";
}
break;
}
case 2: {
updateCryptoPricesFromAPI(ex);
std::cout << "Checking all pending limit orders against new API prices...\n";
limitManager.checkAndExecuteAllOrders(ex, auth);
break;
}
default: {
std::cout << "Unknown option.\n";
}
}
}
}
// --- NEW ADDITION ---
// Helper function to clear the terminal screen
void clearScreen() {
#ifdef _WIN32
system("cls"); // For Windows
#else
system("clear"); // For Linux/macOS
#endif
}
// --- END NEW ADDITION ---
// --- MODIFIED FUNCTION ---
// This function is replaced with the new "live dashboard" version
void userMenu(User& user, Exchange& ex, AuthManager& auth, LimitOrderManager& limitManager) {
while (true) {
try {
// This now acts as a "live dashboard" that refreshes
// every time the user returns to the menu.
clearScreen(); // 1. Clear the screen
std::cout << "[!] Fetching latest market prices...\n";
updateCryptoPricesFromAPI(ex); // 2. Get live prices
std::cout << "-------------------------------\n";
// 3. Check if any limit orders were triggered by new prices
limitManager.checkAndExecuteUserOrders(user, ex);
ex.print(); // 4. Display the updated market
user.printSummary(); // 5. Display the user's portfolio
std::cout << "\n=========== USER MENU ============\n"
<< "1) List Market (Refreshed)\n"
<< "2) View Portfolio (Refreshed)\n"
<< "3) Deposit Funds\n"
<< "4) Buy Crypto (Market Order)\n"
<< "5) Sell Crypto (Market Order)\n"
<< "6) Place Limit Order\n"
<< "7) View My Limit Orders\n"
// Option 8 is removed as it's now automatic
<< "0) Save & Logout\n> ";
int choice = getNumericInput<int>("");
if (choice == 0) {
auth.saveUserData(user);
std::cout << "Data saved. Logging out.\n";
break;
}
// --- We add a clearScreen() before each action ---
// --- so the output is clean. ---