-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrypto.cpp
More file actions
488 lines (412 loc) · 17.6 KB
/
Copy pathcrypto.cpp
File metadata and controls
488 lines (412 loc) · 17.6 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
/**
* @file crypto.cpp
* @brief Implementation of the Crypto widget for managing user cryptocurrency tracking.
*
* Handles adding, deleting, and displaying crypto assets with live price integration,
* chart rendering, and investment statistics.
*
* @author Shourya Nundy
*/
#include "crypto.h"
#include "database.h"
#include <QScrollArea>
#include <QMessageBox>
#include <QSqlQuery>
#include <QSqlError>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QUrl>
#include <QDateTime>
#include <QChart>
#include <QChartView>
#include <QLineSeries>
#include <QDateTimeAxis>
#include <QValueAxis>
#include <QHeaderView>
using namespace Qt;
/**
* @brief Constructor for the Crypto widget.
*/
Crypto::Crypto(QWidget *parent) : QWidget(parent)
{
// Scroll area and main container setup
QScrollArea *scrollArea = new QScrollArea(this);
scrollArea->setWidgetResizable(true);
QWidget *container = new QWidget();
scrollArea->setWidget(container);
mainLayout = new QVBoxLayout(container);
mainLayout->setSpacing(15);
// Header title
QLabel *title = new QLabel("Crypto Tracking", this);
title->setStyleSheet("font-size: 24px; font-weight: bold;");
mainLayout->addWidget(title);
// Stats section for investment overview
QHBoxLayout *statsLayout = new QHBoxLayout();
totalInvestmentLabel = new QLabel("Total Investment: $0.00", this);
profitLossLabel = new QLabel("Profit/Loss: $0.00", this);
refreshStatsButton = new QPushButton("⟳", this);
refreshStatsButton->setFixedSize(28, 28);
refreshStatsButton->setToolTip("Refresh Totals");
refreshStatsButton->setCursor(Qt::PointingHandCursor);
statsLayout->addWidget(totalInvestmentLabel);
statsLayout->addWidget(profitLossLabel);
statsLayout->addWidget(refreshStatsButton);
connect(refreshStatsButton, &QPushButton::clicked, this, &Crypto::updateStats);
statsLayout->addStretch();
mainLayout->addLayout(statsLayout);
QHBoxLayout *timeframeLayout = new QHBoxLayout();
timeframeBox = new QComboBox(this);
timeframeBox->setMinimumWidth(80);
timeframeBox->addItems({"Hour", "Day", "Week"});
connect(timeframeBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &Crypto::updateTimeframe);
timeframeLayout->addWidget(new QLabel("Timeframe:"));
timeframeLayout->addWidget(timeframeBox);
timeframeLayout->addStretch();
mainLayout->addLayout(timeframeLayout);
chartView = new QChartView(this);
chartView->setMinimumHeight(250);
chartView->setRenderHint(QPainter::Antialiasing);
mainLayout->addWidget(chartView);
QHBoxLayout *formLayout = new QHBoxLayout();
cryptoNameInput = new QLineEdit(this);
cryptoNameInput->setPlaceholderText("Crypto Symbol (e.g., BTC)");
purchasePriceInput = new QLineEdit(this);
purchasePriceInput->setPlaceholderText("Purchase Price ($)");
quantityInput = new QLineEdit(this);
quantityInput->setPlaceholderText("Quantity");
dateInput = new QDateEdit(QDate::currentDate(), this);
dateInput->setCalendarPopup(true);
refreshPriceButton = new QPushButton("⟳ Refresh Price", this);
connect(refreshPriceButton, &QPushButton::clicked, this, [this]() {
fetchCryptoPrice(cryptoNameInput->text().toUpper());
});
livePriceLabel = new QLabel("Live Price: --", this);
connect(cryptoNameInput, &QLineEdit::editingFinished, this, [this]() {
fetchCryptoPrice(cryptoNameInput->text().toUpper());
});
formLayout->addWidget(cryptoNameInput);
formLayout->addWidget(purchasePriceInput);
formLayout->addWidget(quantityInput);
formLayout->addWidget(dateInput);
formLayout->addWidget(refreshPriceButton);
formLayout->addWidget(livePriceLabel);
addButton = new QPushButton("➕ Add Crypto", this);
addButton->setStyleSheet("background-color: #27ae60; color: white; padding: 10px; border-radius: 5px;");
connect(addButton, &QPushButton::clicked, this, &Crypto::addCrypto);
formLayout->addWidget(addButton);
mainLayout->addLayout(formLayout);
cryptoTable = new QTableWidget(this);
cryptoTable->setColumnCount(6);
cryptoTable->setHorizontalHeaderLabels({"#", "Date", "Crypto", "Purchase Price", "Quantity", "DB_ID"});
cryptoTable->setColumnHidden(5, true); // hide DB_ID column
cryptoTable->horizontalHeader()->setStretchLastSection(true);
cryptoTable->verticalHeader()->hide();
cryptoTable->setSelectionBehavior(QAbstractItemView::SelectRows);
connect(cryptoTable, &QTableWidget::cellClicked, this, &Crypto::showCryptoPerformance);
deleteButton = new QPushButton("🗑 Delete Selected", this);
deleteButton->setStyleSheet("background-color: #e74c3c; color: white; padding: 10px; border-radius: 5px;");
connect(deleteButton, &QPushButton::clicked, this, &Crypto::deleteCrypto);
QVBoxLayout *tableLayout = new QVBoxLayout();
cryptoTable->setMinimumHeight(300);
cryptoTable->setMaximumHeight(500);
tableLayout->addWidget(cryptoTable);
QHBoxLayout *buttonLayout = new QHBoxLayout();
buttonLayout->addWidget(deleteButton);
buttonLayout->addStretch();
tableLayout->addLayout(buttonLayout);
mainLayout->addLayout(tableLayout);
QVBoxLayout *outerLayout = new QVBoxLayout(this);
outerLayout->addWidget(scrollArea);
loadCryptoData();
updateTimeframe();
}
/**
* @brief Adds a new crypto entry to the database and table.
*/
void Crypto::addCrypto()
{
if (cryptoNameInput->text().isEmpty() || quantityInput->text().isEmpty()) {
QMessageBox::warning(this, "Error", "Please fill all fields");
return;
}
QString cryptoSymbol = cryptoNameInput->text().toUpper();
bool quantityOk;
double quantity = quantityInput->text().toDouble(&quantityOk);
if (!quantityOk) {
QMessageBox::warning(this, "Error", "Invalid quantity.");
return;
}
QSqlQuery query(DatabaseManager::getDatabase());
query.prepare("INSERT INTO cryptocurrencies (user_id, date, crypto_name, purchase_price, quantity) "
"VALUES (:user_id, :date, :crypto_name, :purchase_price, :quantity)");
query.bindValue(":user_id", DatabaseManager::currentUserId);
query.bindValue(":date", dateInput->date().toString("yyyy-MM-dd"));
query.bindValue(":crypto_name", cryptoSymbol);
query.bindValue(":purchase_price", purchasePriceInput->text().toDouble());
query.bindValue(":quantity", quantity);
if (!query.exec()) {
QMessageBox::warning(this, "Error", "Failed to add crypto: " + query.lastError().text());
return;
}
loadCryptoData();
emit dataChanged();
cryptoNameInput->clear();
purchasePriceInput->clear();
quantityInput->clear();
dateInput->setDate(QDate::currentDate());
livePriceLabel->setText("Live Price: --");
updateStats();
}
/**
* @brief Deletes the currently selected cryptocurrency record from the database.
*
* Removes the selected row from the UI and deletes the corresponding entry from the database,
* using the hidden database ID. Triggers a refresh of the table and updates investment stats.
*/
void Crypto::deleteCrypto()
{
int selectedRow = cryptoTable->currentRow();
if (selectedRow >= 0) {
QString id = cryptoTable->item(selectedRow, 5)->text(); // actual DB ID
QSqlQuery query(DatabaseManager::getDatabase());
query.prepare("DELETE FROM cryptocurrencies WHERE id = :id AND user_id = :user_id");
query.bindValue(":id", id);
query.bindValue(":user_id", DatabaseManager::currentUserId);
if (!query.exec()) {
QMessageBox::warning(this, "Error", "Failed to delete crypto: " + query.lastError().text());
return;
}
loadCryptoData();
emit dataChanged();
updateStats();
}
}
/**
* @brief Loads all crypto investment entries for the current user and populates the table.
*
* Fetches data from the database and displays it in the `cryptoTable` widget.
* Hides the database ID column while keeping it accessible for operations like delete.
*/
void Crypto::loadCryptoData()
{
cryptoTable->setRowCount(0);
QSqlQuery query(DatabaseManager::getDatabase());
query.prepare("SELECT id, date, crypto_name, purchase_price, quantity FROM cryptocurrencies WHERE user_id = :user_id");
query.bindValue(":user_id", DatabaseManager::currentUserId);
if (!query.exec()) {
QMessageBox::warning(this, "Error", "Failed to load data.");
return;
}
while (query.next()) {
int row = cryptoTable->rowCount();
cryptoTable->insertRow(row);
cryptoTable->setItem(row, 0, new QTableWidgetItem(QString::number(row + 1)));
cryptoTable->setItem(row, 1, new QTableWidgetItem(query.value(1).toString()));
cryptoTable->setItem(row, 2, new QTableWidgetItem(query.value(2).toString()));
cryptoTable->setItem(row, 3, new QTableWidgetItem(QString::number(query.value(3).toDouble(), 'f', 2)));
cryptoTable->setItem(row, 4, new QTableWidgetItem(QString::number(query.value(4).toDouble(), 'f', 10)));
cryptoTable->setItem(row, 5, new QTableWidgetItem(query.value(0).toString())); // DB ID
}
updateStats();
}
/**
* @brief Fetches the current USD price for the specified cryptocurrency symbol.
*
* Sends an HTTP request to a public API (CoinGecko or similar) and displays the
* live price in the UI. If the symbol is invalid or fails, it displays an error.
*
* @param cryptoSymbol The uppercase symbol of the cryptocurrency (e.g., BTC, ETH).
*/
void Crypto::fetchCryptoPrice(const QString &cryptoSymbol)
{
QString urlString = "https://min-api.cryptocompare.com/data/price?fsym=" + cryptoSymbol + "&tsyms=USD";
QUrl url(urlString);
QNetworkRequest request(url);
QNetworkAccessManager *manager = new QNetworkAccessManager(this);
QNetworkReply *reply = manager->get(request);
connect(reply, &QNetworkReply::finished, this, [this, reply]() {
if (reply->error() == QNetworkReply::NoError) {
QJsonObject json = QJsonDocument::fromJson(reply->readAll()).object();
if (json.contains("USD")) {
double price = json["USD"].toDouble();
purchasePriceInput->setText(QString::number(price, 'f', 2));
livePriceLabel->setText("Live Price: $" + QString::number(price, 'f', 2));
}
}
reply->deleteLater();
});
}
/**
* @brief Displays the historical chart for the selected cryptocurrency.
*
* Updates the current symbol and triggers a chart refresh for that crypto
* using the selected timeframe (Hour, Day, Week).
*
* @param row The selected row index in the crypto table
* @param column The column index (unused)
*/
void Crypto::showCryptoPerformance(int row, int)
{
QString cryptoSymbol = cryptoTable->item(row, 2)->text();
currentSymbol = cryptoSymbol;
updateTimeframe();
}
/**
* @brief Fetches historical price data for the currentSymbol and updates the chart.
*
* Uses the selected timeframe (Hour, Day, Week) to construct an API request
* and visualize historical data with tooltips using QChart.
*/
void Crypto::updateTimeframe()
{
QString tf = timeframeBox->currentText();
QString endpoint = "histohour";
int limit = 24;
if (tf == "Day") {
endpoint = "histoday";
limit = 30;
} else if (tf == "Week") {
endpoint = "histoday";
limit = 90;
}
//Construct API request
QString urlString = QString("https://min-api.cryptocompare.com/data/v2/%1?fsym=%2&tsym=USD&limit=%3")
.arg(endpoint, currentSymbol, QString::number(limit));
QUrl url(urlString);
QNetworkRequest request(url);
QNetworkAccessManager *manager = new QNetworkAccessManager(this);
QNetworkReply *reply = manager->get(request);
connect(reply, &QNetworkReply::finished, this, [this, reply]() {
if (reply->error() != QNetworkReply::NoError) {
reply->deleteLater();
return;
}
//parse response
QJsonArray dataArray = QJsonDocument::fromJson(reply->readAll())["Data"].toObject()["Data"].toArray();
QLineSeries *series = new QLineSeries();
series->setName("Price");
QPen pen(QColor("#00c6ff")); // Start color (light blue)
pen.setWidth(3); // Thicker line
series->setPen(pen);
for (const auto &val : dataArray) {
auto obj = val.toObject();
QDateTime time = QDateTime::fromSecsSinceEpoch(obj["time"].toInt());
series->append(time.toMSecsSinceEpoch(), obj["close"].toDouble());
}
QGraphicsSimpleTextItem *tooltipItem = new QGraphicsSimpleTextItem();
chartView->scene()->addItem(tooltipItem);
tooltipItem->setZValue(11);
tooltipItem->hide();
connect(series, &QLineSeries::hovered, this, [=](const QPointF &point, bool state) {
if (state) {
QDateTime timestamp = QDateTime::fromMSecsSinceEpoch(qint64(point.x()));
QString timeStr = (timeframeBox->currentText() == "Hour")
? timestamp.toString("hh:mm")
: timestamp.toString("dd MMM");
tooltipItem->setText(QString("%1\n$%2")
.arg(timeStr)
.arg(QString::number(point.y(), 'f', 2)));
tooltipItem->setFont(QFont("Segoe UI", 10, QFont::Bold));
tooltipItem->setBrush(QColor("#222"));
tooltipItem->setPos(chartView->chart()->mapToPosition(point));
tooltipItem->show();
} else {
tooltipItem->hide();
}
});
QChart *chart = new QChart();
chart->addSeries(series);
chart->setTitle(currentSymbol + " - " + timeframeBox->currentText() + " Performance");
chart->legend()->hide();
chart->setAnimationOptions(QChart::AllAnimations);
// Background
chart->setBackgroundBrush(QColor("#ffffff"));
chart->setBackgroundPen(QPen(Qt::NoPen));
// Drop shadow (optional)
chart->setDropShadowEnabled(true);
QDateTimeAxis *axisX = new QDateTimeAxis;
axisX->setGridLineColor(QColor("#c0eaff"));
axisX->setFormat((timeframeBox->currentText() == "Hour") ? "hh:mm" : "MMM d");
axisX->setTitleText("Time");
chart->addAxis(axisX, Qt::AlignBottom);
series->attachAxis(axisX);
QValueAxis *axisY = new QValueAxis;
axisY->setGridLineColor(QColor("#c0eaff"));
axisY->setTitleText("Price (USD)");
chart->addAxis(axisY, Qt::AlignLeft);
series->attachAxis(axisY);
chartView->setChart(chart);
reply->deleteLater();
});
}
/**
* @brief Updates the total investment and profit/loss statistics for all crypto entries.
*
* Iterates through each crypto row, fetches the current price via an API,
* and calculates total invested amount and overall profit/loss.
* Displays this summary in the stats section.
*/
void Crypto::updateStats()
{
// Struct to accumulate totals across async API responses
struct Totals {
double investment = 0.0;
double profitLoss = 0.0;
int completed = 0;
int expected = 0;
};
// Use heap allocation so it can be captured in lambdas
Totals *totals = new Totals();
QNetworkAccessManager *manager = new QNetworkAccessManager(this);
int rows = cryptoTable->rowCount();
// Handle edge case: no crypto entries
if (rows == 0) {
totalInvestmentLabel->setText("Total Investment: $0.00");
profitLossLabel->setText("Profit/Loss: $0.00");
profitLossLabel->setStyleSheet("color: gray;");
delete totals;
return;
}
totals->expected = rows;
// Loop over each crypto entry in the table
for (int i = 0; i < rows; ++i) {
QString symbol = cryptoTable->item(i, 2)->text();
double purchasePrice = cryptoTable->item(i, 3)->text().toDouble();
double quantity = cryptoTable->item(i, 4)->text().toDouble();
totals->investment += purchasePrice * quantity;
QString url = "https://min-api.cryptocompare.com/data/price?fsym=" + symbol + "&tsyms=USD";
QUrl qurl(url);
QNetworkRequest request(qurl);
QNetworkReply *reply = manager->get(request);
connect(reply, &QNetworkReply::finished, this, [=]() mutable {
if (reply->error() == QNetworkReply::NoError) {
QJsonObject json = QJsonDocument::fromJson(reply->readAll()).object();
if (json.contains("USD")) {
double currentPrice = json["USD"].toDouble();
double profit = (currentPrice - purchasePrice) * quantity;
totals->profitLoss += profit;
}
}
totals->completed++;
if (totals->completed == totals->expected) {
totalInvestmentLabel->setText("Total Investment: $" + QString::number(totals->investment, 'f', 2));
QString plText = QString("Profit/Loss: $%1").arg(QString::number(totals->profitLoss, 'f', 2));
profitLossLabel->setText(plText);
// Set color styling based on profit/loss value
if (totals->profitLoss > 0) {
profitLossLabel->setStyleSheet("color: green;");
} else if (totals->profitLoss < 0) {
profitLossLabel->setStyleSheet("color: red;");
} else {
profitLossLabel->setStyleSheet("color: gray;");
}
delete totals; // Clean up once complete
}
reply->deleteLater();
});
}
}