-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstock.cpp
More file actions
806 lines (668 loc) · 28.4 KB
/
Copy pathstock.cpp
File metadata and controls
806 lines (668 loc) · 28.4 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
/**
* @file stock.cpp
* @brief Implementation of the Stock widget for tracking investments and showing visual stats.
*
* Handles stock data input, display, API integration for live prices and logos,
* profit/loss tracking, gauge visualization, and performance graphs.
*
* @author Darsh Vimal Shah, Sergio Andres Rangel
*/
#include "stock.h"
#include "database.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QHeaderView>
#include <QMessageBox>
#include <QFormLayout>
#include <QDialogButtonBox>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QUrlQuery>
#include <QPainter>
#include <QDateTime>
#include <QDebug>
#include <qdatetimeaxis.h>
/**
* @brief Constructs the Stock widget and initializes all UI components.
*
* Sets up:
* - Scrollable layout and stats section
* - Input fields for ticker, price, quantity, date
* - Table for stock entries including logos, P/L calculation
* - Circular gauge and interactive chart for performance visualization
* - Connections to API calls for live data and logo fetching
* - Event handlers for input, filtering, and table selection
*
* Also auto-loads existing stocks from the database and fetches live prices.
* If available, it pre-selects the first stock and displays its performance.
*
* @param parent Optional parent widget.
*/
Stock::Stock(QWidget *parent) : QWidget(parent)
{
// Scroll area for responsiveness
QScrollArea *scrollArea = new QScrollArea(this);
scrollArea->setWidgetResizable(true);
QWidget *container = new QWidget();
scrollArea->setWidget(container);
QVBoxLayout *outerLayout = new QVBoxLayout(this);
outerLayout->addWidget(scrollArea);
mainLayout = new QVBoxLayout(container);
mainLayout->setSpacing(15);
mainLayout->setContentsMargins(15, 15, 15, 15);
// Title
titleLabel = new QLabel("Stock Tracker", this);
titleLabel->setStyleSheet("font-size: 28px; font-weight: bold;");
titleLabel->setAlignment(Qt::AlignLeft);
mainLayout->addWidget(titleLabel);
// Stats
// Stats
QHBoxLayout *statsLayout = new QHBoxLayout();
totalInvestmentLabel = new QLabel("Total Investment: $0.00", this);
totalInvestmentLabel->setStyleSheet("font-size: 16px; font-weight: bold;");
topStockLabel = new QLabel("🥇 Top Performing Stock: N/A", this); // Icon added
topStockLabel->setStyleSheet("font-size: 16px; font-weight: bold;");
statsLayout->addWidget(totalInvestmentLabel);
statsLayout->addSpacing(30); // Space between the two labels
statsLayout->addWidget(topStockLabel);
statsLayout->addStretch();
mainLayout->addLayout(statsLayout);
// Chart and Gauge Layout
QHBoxLayout *chartLayout = new QHBoxLayout();
// Left side: Gauge
QVBoxLayout *gaugeLayout = new QVBoxLayout();
gaugeLayout->setSpacing(-10000);
gaugeLayout->setContentsMargins(0, 0, 0, 0);
profitLabel = new QLabel("Profit/Loss: $0.00", this);
profitLabel->setStyleSheet("font-size: 18px; font-weight: bold;");
profitLabel->setAlignment(Qt::AlignCenter);
gaugeLabel = new QLabel(this);
gaugeLabel->setAlignment(Qt::AlignCenter);
gaugeLabel->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
// Add profit label
gaugeLayout->addWidget(profitLabel, 0, Qt::AlignCenter);
// 👉 Add a negative spacer to collapse the space between profitLabel and gaugeLabel
QSpacerItem *negativeSpacer = new QSpacerItem(0, -40, QSizePolicy::Minimum, QSizePolicy::Fixed);
gaugeLayout->addItem(negativeSpacer);
// Add gauge label
gaugeLayout->addWidget(gaugeLabel, 0, Qt::AlignCenter);
// Add gauge layout to the main chart area
chartLayout->addLayout(gaugeLayout);
// Timeframe
QHBoxLayout *timeframeLayout = new QHBoxLayout();
timeframeBox = new QComboBox(this);
// Match crypto.cpp style: Hour, Day, Week
timeframeBox->addItems({"Hour", "Day", "Week"});
connect(timeframeBox, QOverload<int>::of(&QComboBox::currentIndexChanged),
this, &Stock::updatePerformanceGraph);
timeframeLayout->addWidget(new QLabel("Timeframe:"));
timeframeLayout->addWidget(timeframeBox);
timeframeLayout->addStretch();
mainLayout->addLayout(timeframeLayout);
QVBoxLayout *chartWithSpacingLayout = new QVBoxLayout();
chartWithSpacingLayout->setContentsMargins(0, 250, 0, 0); // Add top margin only
// Right side: Chart View
performanceChartView = new QChartView(new QChart(), this);
performanceChartView->setMinimumSize(500, 300);
performanceChartView->setRenderHint(QPainter::Antialiasing);
chartLayout->addWidget(performanceChartView, 0, Qt::AlignCenter);
mainLayout->addLayout(chartLayout);
// Input Form
QHBoxLayout *formLayout = new QHBoxLayout();
nameInput = new QLineEdit(this);
nameInput->setPlaceholderText("Ticker (e.g., AAPL)");
priceInput = new QLineEdit(this);
priceInput->setPlaceholderText("Purchase Price");
quantityInput = new QLineEdit(this);
quantityInput->setPlaceholderText("Quantity");
dateInput = new QDateEdit(QDate::currentDate(), this);
dateInput->setCalendarPopup(true);
addButton = new QPushButton("➕ Add Stock", this);
addButton->setStyleSheet("background-color: #27ae60; color: white; padding: 10px; border-radius: 5px;");
connect(addButton, &QPushButton::clicked, this, &Stock::addStock);
connect(nameInput, &QLineEdit::editingFinished, this, &Stock::onTickerEdited);
refreshButton = new QPushButton("🔄 Refresh", this);
refreshButton->setStyleSheet("background-color:rgb(5, 33, 52); color: white; padding: 10px; border-radius: 5px;");
connect(refreshButton, &QPushButton::clicked, this, &Stock::refreshData);
formLayout->addWidget(nameInput);
formLayout->addWidget(priceInput);
formLayout->addWidget(quantityInput);
formLayout->addWidget(dateInput);
formLayout->addWidget(addButton);
formLayout->addWidget(refreshButton);
// Add spacing before input fields
QSpacerItem *inputSpacer = new QSpacerItem(20, 50, QSizePolicy::Minimum, QSizePolicy::Fixed);
mainLayout->addItem(inputSpacer);
// Add input form layout
mainLayout->addLayout(formLayout);
// Stock Table
stockTable = new QTableWidget(this);
stockTable->setColumnCount(6);
stockTable->setHorizontalHeaderLabels({"Logo", "Date", "Ticker", "Purchase Price", "Quantity", "P/L"});
stockTable->horizontalHeader()->setStretchLastSection(true);
stockTable->verticalHeader()->hide();
stockTable->setSelectionBehavior(QAbstractItemView::SelectRows);
stockTable->setMinimumHeight(250);
stockTable->verticalHeader()->setDefaultSectionSize(60);
stockTable->setIconSize(QSize(48, 48));
connect(stockTable->selectionModel(), &QItemSelectionModel::currentChanged,
this, &Stock::onTableSelectionChanged);
mainLayout->addWidget(stockTable);
// Bottom Buttons
QHBoxLayout *buttonLayout = new QHBoxLayout();
filterButton = new QPushButton("🔍 Filter by Date", this);
deleteButton = new QPushButton("🗑 Delete Selected", this);
filterButton->setStyleSheet("background-color: #3498db; color: white;");
deleteButton->setStyleSheet("background-color: #e74c3c; color: white;");
connect(filterButton, &QPushButton::clicked, this, &Stock::filterByDate);
connect(deleteButton, &QPushButton::clicked, this, &Stock::deleteStock);
buttonLayout->addWidget(filterButton);
buttonLayout->addWidget(deleteButton);
buttonLayout->addStretch();
mainLayout->addLayout(buttonLayout);
// Network Managers
networkManager = new QNetworkAccessManager(this);
connect(networkManager, &QNetworkAccessManager::finished,
this, &Stock::handlePriceReply);
logoManager = new QNetworkAccessManager(this);
connect(logoManager, &QNetworkAccessManager::finished,
this, &Stock::handleLogoReply);
// *** REMOVE auto-refresh timer to avoid reloading chart every 15s ***
// updateTimer = new QTimer(this);
// connect(updateTimer, &QTimer::timeout, this, &Stock::fetchLivePrices);
// updateTimer->start(15000);
// ^^^ Removed as per request
// Initial load
loadStockData();
fetchLivePrices();
// Select first stock (if any) and show graph
if (stockTable->rowCount() > 0) {
stockTable->selectRow(0);
selectedTicker = stockTable->item(0, 2)->text();
updatePerformanceGraph();
}
}
// ---------------------- SLOTS ---------------------- //
/**
* @brief Handles row selection in the stock table.
*
* Sets the selected ticker and updates the performance chart accordingly.
*
* @param current Currently selected index.
* @param previous Previously selected index.
*/
void Stock::onTableSelectionChanged(const QModelIndex ¤t, const QModelIndex &previous)
{
Q_UNUSED(previous);
if (!current.isValid()) return;
int row = current.row();
if (row < 0) return;
selectedTicker = stockTable->item(row, 2)->text(); // Ticker is column 2
updatePerformanceGraph();
}
/**
* @brief Called when the ticker input field loses focus.
*
* Triggers the live price autofill request.
*/
void Stock::onTickerEdited()
{
updateLivePriceAutoFill();
}
/**
* @brief Automatically fills the stock price field based on ticker API lookup.
*/
void Stock::updateLivePriceAutoFill()
{
QString symbol = nameInput->text().trimmed().toUpper();
if (symbol.isEmpty()) return;
QString url = QString("https://finnhub.io/api/v1/quote?symbol=%1&token=cvjjovhr01qlscpckdc0cvjjovhr01qlscpckdcg")
.arg(symbol);
networkManager->get(QNetworkRequest(QUrl(url)));
}
/**
* @brief Adds a new stock entry to the database.
*
* Validates form inputs, inserts stock into the DB,
* clears form fields, and refreshes the stock table and visuals.
*/
void Stock::addStock()
{
if (nameInput->text().isEmpty() ||
quantityInput->text().isEmpty() ||
priceInput->text().isEmpty())
{
QMessageBox::warning(this, "Error", "Please fill all fields");
return;
}
QSqlQuery query(DatabaseManager::getDatabase());
query.prepare("INSERT INTO stocks (user_id, date, stock_name, purchase_price, quantity) "
"VALUES (:user_id, :date, :stock_name, :purchase_price, :quantity)");
query.bindValue(":user_id", DatabaseManager::currentUserId);
query.bindValue(":date", dateInput->date().toString("yyyy-MM-dd"));
query.bindValue(":stock_name", nameInput->text().toUpper());
query.bindValue(":purchase_price", priceInput->text().toDouble());
query.bindValue(":quantity", quantityInput->text().toInt());
if (!query.exec()) {
qDebug() << "Error adding stock:" << query.lastError().text();
}
nameInput->clear();
priceInput->clear();
quantityInput->clear();
dateInput->setDate(QDate::currentDate());
loadStockData();
fetchLivePrices();
}
/**
* @brief Deletes the currently selected stock entry from the table and database.
*
* Looks up ticker and date from the selected row, deletes it, then refreshes table and prices.
*/
void Stock::deleteStock()
{
int row = stockTable->currentRow();
if (row >= 0) {
QString ticker = stockTable->item(row, 2)->text();
QString date = stockTable->item(row, 1)->text();
QSqlQuery query(DatabaseManager::getDatabase());
query.prepare("DELETE FROM stocks WHERE stock_name = :ticker AND date = :date AND user_id = :user_id");
query.bindValue(":ticker", ticker);
query.bindValue(":date", date);
query.bindValue(":user_id", DatabaseManager::currentUserId);
query.exec();
loadStockData();
fetchLivePrices();
}
}
/**
* @brief Filters the stock table based on a user-selected date range.
*
* Displays a dialog with start and end date selectors. Hides rows that fall outside the range.
*/
void Stock::filterByDate()
{
QDialog dialog(this);
dialog.setWindowTitle("Select Date Range");
QFormLayout layout(&dialog);
QDateEdit *startDateEdit = new QDateEdit(QDate::currentDate().addMonths(-1), &dialog);
QDateEdit *endDateEdit = new QDateEdit(QDate::currentDate(), &dialog);
startDateEdit->setCalendarPopup(true);
endDateEdit->setCalendarPopup(true);
layout.addRow("Start Date:", startDateEdit);
layout.addRow("End Date:", endDateEdit);
QDialogButtonBox buttons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, &dialog);
layout.addRow(&buttons);
connect(&buttons, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
connect(&buttons, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);
if (dialog.exec() == QDialog::Accepted) {
QDate startDate = startDateEdit->date();
QDate endDate = endDateEdit->date();
if (startDate > endDate) std::swap(startDate, endDate);
for (int row = 0; row < stockTable->rowCount(); ++row) {
QDate entryDate = QDate::fromString(stockTable->item(row, 1)->text(), "yyyy-MM-dd");
bool show = (entryDate >= startDate && entryDate <= endDate);
stockTable->setRowHidden(row, !show);
}
}
}
/**
* @brief Loads all stock records for the current user and populates the table.
*
* Also fetches associated logos and updates profit/loss values per row.
*/
void Stock::loadStockData()
{
stockTable->setRowCount(0);
QSqlQuery query(DatabaseManager::getDatabase());
query.prepare("SELECT id, date, stock_name, purchase_price, quantity FROM stocks WHERE user_id = :user_id");
query.bindValue(":user_id", DatabaseManager::currentUserId);
query.exec();
double totalInvest = 0.0;
double bestPerformance = -1e9;
QString bestTicker = "N/A";
while (query.next()) {
int row = stockTable->rowCount();
stockTable->insertRow(row);
QString dateStr = query.value(1).toString();
QString ticker = query.value(2).toString();
double purchasePrice = query.value(3).toDouble();
int qty = query.value(4).toInt();
totalInvest += purchasePrice * qty;
double live = livePrices.value(ticker, purchasePrice);
double perfRatio = (purchasePrice > 0) ? ((live - purchasePrice) / purchasePrice) : 0.0;
if (perfRatio > bestPerformance) {
bestPerformance = perfRatio;
bestTicker = ticker;
}
// Column 0: Logo placeholder
QTableWidgetItem *logoItem = new QTableWidgetItem();
logoItem->setTextAlignment(Qt::AlignCenter);
logoItem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
logoItem->setText("Loading...");
stockTable->setItem(row, 0, logoItem);
// Fetch the logo
QString logoUrl = QString("https://storage.googleapis.com/iex/api/logos/%1.png").arg(ticker);
QNetworkRequest logoRequest{QUrl(logoUrl)};
QNetworkReply *logoReply = logoManager->get(logoRequest);
logoReplyMap[logoReply] = row;
// Column 1: Date
QTableWidgetItem *dateItem = new QTableWidgetItem(dateStr);
stockTable->setItem(row, 1, dateItem);
// Column 2: Ticker
QTableWidgetItem *tickerItem = new QTableWidgetItem(ticker);
stockTable->setItem(row, 2, tickerItem);
// Column 3: Purchase Price
QTableWidgetItem *priceItem = new QTableWidgetItem(QString::number(purchasePrice, 'f', 2));
stockTable->setItem(row, 3, priceItem);
// Column 4: Quantity
QTableWidgetItem *qtyItem = new QTableWidgetItem(QString::number(qty));
stockTable->setItem(row, 4, qtyItem);
// Column 5: Profit/Loss
double pl = (live - purchasePrice) * qty;
QString plText = (pl >= 0 ? "+" : "") + QString::number(pl, 'f', 2);
QTableWidgetItem *plItem = new QTableWidgetItem(plText);
plItem->setTextAlignment(Qt::AlignCenter);
plItem->setForeground(QBrush(pl >= 0 ? QColor("#1fb83c") : Qt::red));
stockTable->setItem(row, 5, plItem);
}
totalInvestmentLabel->setText(QString("Total Investment: $%1").arg(totalInvest, 0, 'f', 2));
topStockLabel->setText(QString("🥇 Top Performing Stock: %1").arg(bestTicker));
updateStats();
// If table is non-empty but no selection, select the first row
if (stockTable->rowCount() > 0 && !stockTable->selectionModel()->hasSelection()) {
stockTable->selectRow(0);
}
}
/**
* @brief Sends HTTP GET requests to fetch live prices for all tickers in the table.
*/
void Stock::fetchLivePrices()
{
// Only fetch for tickers that exist in the table
for (int i = 0; i < stockTable->rowCount(); ++i) {
QString ticker = stockTable->item(i, 2)->text();
QString url = QString("https://finnhub.io/api/v1/quote?symbol=%1&token=cvjjovhr01qlscpckdc0cvjjovhr01qlscpckdcg")
.arg(ticker);
networkManager->get(QNetworkRequest(QUrl(url)));
}
}
/**
* @brief Handles the HTTP response containing the live price for a stock.
*
* Updates the price map, fills price input if empty, updates table row and triggers visual updates.
*
* @param reply QNetworkReply from the live price API.
*/
void Stock::handlePriceReply(QNetworkReply *reply)
{
if (reply->error() != QNetworkReply::NoError) {
reply->deleteLater();
return;
}
QJsonObject obj = QJsonDocument::fromJson(reply->readAll()).object();
double currentPrice = obj["c"].toDouble();
QUrl url = reply->url();
QUrlQuery q(url);
QString symbol = q.queryItemValue("symbol");
// Update our local map of live prices
livePrices[symbol] = currentPrice;
// Update the row for this ticker in place
updateTableRowForPrice(symbol, currentPrice);
// Auto-fill price input if user typed this ticker
if (nameInput->text().trimmed().toUpper() == symbol && priceInput->text().isEmpty()) {
priceInput->setText(QString::number(currentPrice, 'f', 2));
}
// Recalculate stats
updateStats();
// If the selected ticker is the one we just updated, refresh the graph
if (selectedTicker == symbol) {
updatePerformanceGraph();
}
reply->deleteLater();
}
/**
* @brief Updates a specific table row’s P/L values based on live price.
*
* @param ticker Stock symbol to update
* @param newPrice Latest price from API
*/
void Stock::updateTableRowForPrice(const QString &ticker, double newPrice)
{
// Find row with matching ticker
for (int i = 0; i < stockTable->rowCount(); ++i) {
QString rowTicker = stockTable->item(i, 2)->text();
if (rowTicker == ticker) {
double purchasePrice = stockTable->item(i, 3)->text().toDouble();
int qty = stockTable->item(i, 4)->text().toInt();
double pl = (newPrice - purchasePrice) * qty;
QString plText = (pl >= 0 ? "+" : "") + QString::number(pl, 'f', 2);
// Update P/L cell
QTableWidgetItem *plItem = stockTable->item(i, 5);
plItem->setText(plText);
plItem->setForeground(QBrush(pl >= 0 ? QColor("#1fb83c") : Qt::red));
break;
}
}
}
/**
* @brief Recalculates total investment and P/L for all stocks.
*
* Updates labels and redraws the circular performance gauge.
*/
void Stock::updateStats()
{
double totalInvest = 0.0;
double marketValue = 0.0;
double bestPerformance = -1e9;
QString bestTicker = "N/A";
for (int i = 0; i < stockTable->rowCount(); ++i) {
QString ticker = stockTable->item(i, 2)->text();
double purchasePrice = stockTable->item(i, 3)->text().toDouble();
int qty = stockTable->item(i, 4)->text().toInt();
double live = livePrices.value(ticker, purchasePrice);
totalInvest += purchasePrice * qty;
marketValue += live * qty;
double perfRatio = (purchasePrice > 0) ? ((live - purchasePrice) / purchasePrice) : 0.0;
if (perfRatio > bestPerformance) {
bestPerformance = perfRatio;
bestTicker = ticker;
}
}
double diff = marketValue - totalInvest;
currentProfitValue = diff;
profitLabel->setText(QString("Profit/Loss: %1$%2")
.arg(diff >= 0 ? "+" : "-")
.arg(qAbs(diff), 0, 'f', 2));
profitLabel->setStyleSheet(QString("font-weight: bold; font-size: 18px; color: %1")
.arg(diff >= 0 ? "green" : "red"));
int gaugeValue = (totalInvest > 0) ? static_cast<int>((marketValue / totalInvest) * 100) : 0;
drawCircularGauge(gaugeValue);
// Update top performing label
topStockLabel->setText(QString("🥇 Top Performing Stock: %1").arg(bestTicker));
// Update total investment
totalInvestmentLabel->setText(QString("Total Investment: $%1").arg(totalInvest, 0, 'f', 2));
}
/**
* @brief Draws a circular gauge representing portfolio performance.
*
* @param value Value from 0 to 100 indicating percentage performance.
*/
void Stock::drawCircularGauge(int value)
{
QPixmap pixmap(200, 200);
pixmap.fill(Qt::transparent);
QPainter p(&pixmap);
p.setRenderHint(QPainter::Antialiasing);
QRectF rect(10, 10, pixmap.width() - 20, pixmap.height() - 20);
// Background arc
p.setPen(QPen(Qt::gray, 6));
p.drawArc(rect, 0, 360 * 16);
// Value arc
p.setPen(QPen(value > 100 ? Qt::green : Qt::blue, 8));
p.drawArc(rect, 90 * 16, -value * 360 / 100 * 16);
p.setFont(QFont("Arial", 12, QFont::Bold));
p.drawText(rect, Qt::AlignCenter, QString("%1%").arg(value));
gaugeLabel->setPixmap(pixmap);
}
// ------------------------
// UPDATED CHART FUNCTION:
// Uses dynamic date range & local times
// ------------------------
/**
* @brief Updates the line graph showing stock performance over time.
*
* Uses Polygon.io or other API to fetch and display stock history.
*/
void Stock::updatePerformanceGraph()
{
if (selectedTicker.isEmpty()) {
performanceChartView->setChart(new QChart());
return;
}
// Decide aggregator & date range based on "Hour", "Day", "Week"
QString tf = timeframeBox->currentText();
QString multiplier = "1";
QString timespan = "day";
// We'll figure out the start/end date relative to "now"
QDateTime endDateTime = QDateTime::currentDateTimeUtc();
QDateTime startDateTime = endDateTime;
if (tf == "Hour") {
// Last 24 hours => aggregator=15-minute
multiplier = "15";
timespan = "minute";
startDateTime = endDateTime.addDays(-1);
}
else if (tf == "Day") {
// Last 30 days => aggregator=1 day
multiplier = "1";
timespan = "day";
startDateTime = endDateTime.addDays(-30);
}
else if (tf == "Week") {
// Last ~90 days => aggregator=1 day
multiplier = "1";
timespan = "day";
startDateTime = endDateTime.addDays(-90);
}
// Convert to "yyyy-MM-dd" strings for Polygon
QString fromStr = startDateTime.date().toString("yyyy-MM-dd");
QString toStr = endDateTime.date().toString("yyyy-MM-dd");
// Build the URL for Polygon Aggregates endpoint
// /v2/aggs/ticker/<TICKER>/range/<multiplier>/<timespan>/<from>/<to>?adjusted=true&...
QString ticker = selectedTicker.toUpper();
QString urlString = QString("https://api.polygon.io/v2/aggs/ticker/%1/range/%2/%3/%4/%5"
"?adjusted=true&sort=asc&limit=500&apiKey=ooHpY6vj9OPt0xQn5GbK8bR_a_WPyUFD")
.arg(ticker)
.arg(multiplier)
.arg(timespan)
.arg(fromStr)
.arg(toStr);
QUrl url(urlString);
QNetworkRequest request(url);
// Make a local manager so it's similar to your crypto.cpp approach
QNetworkAccessManager *manager = new QNetworkAccessManager(this);
QNetworkReply *reply = manager->get(request);
connect(reply, &QNetworkReply::finished, this, [this, reply, tf]() {
if (reply->error() != QNetworkReply::NoError) {
qDebug() << "Error fetching polygon data for chart:" << reply->errorString();
performanceChartView->setChart(new QChart());
reply->deleteLater();
return;
}
QByteArray rawData = reply->readAll();
QJsonDocument doc = QJsonDocument::fromJson(rawData);
QJsonObject root = doc.object();
QJsonArray results = root.value("results").toArray();
QLineSeries *series = new QLineSeries();
// Build the data series
for (const QJsonValue &val : results) {
QJsonObject obj = val.toObject();
// "t" = millisecond timestamp
qint64 ts = obj["t"].toVariant().toLongLong();
double close = obj["c"].toDouble();
series->append(ts, close);
}
QChart *chart = new QChart();
chart->legend()->hide();
chart->setTitle(selectedTicker + " - " + tf + " Performance");
if (!series->points().isEmpty()) {
// Add series & axes only if we have data
chart->addSeries(series);
// X axis (time)
QDateTimeAxis *axisX = new QDateTimeAxis;
axisX->setTitleText("Date/Time");
if (tf == "Hour") {
axisX->setFormat("hh:mm");
} else {
axisX->setFormat("MMM d");
}
chart->addAxis(axisX, Qt::AlignBottom);
series->attachAxis(axisX);
// Y axis (price)
QValueAxis *axisY = new QValueAxis;
axisY->setTitleText("Price (USD)");
chart->addAxis(axisY, Qt::AlignLeft);
series->attachAxis(axisY);
// Optional tooltip on hover
QGraphicsSimpleTextItem *tooltipItem = new QGraphicsSimpleTextItem(chart);
tooltipItem->setZValue(11);
tooltipItem->hide();
connect(series, &QLineSeries::hovered, this, [=](const QPointF &pt, bool state) {
if (state) {
// Convert ms timestamp to local time
QDateTime timestamp = QDateTime::fromMSecsSinceEpoch((qint64)pt.x()).toLocalTime();
QString timeStr = (tf == "Hour")
? timestamp.toString("hh:mm")
: timestamp.toString("MMM d");
tooltipItem->setText(QString("%1\n$%2")
.arg(timeStr)
.arg(QString::number(pt.y(), 'f', 2)));
tooltipItem->setFont(QFont("Segoe UI", 10, QFont::Bold));
tooltipItem->setBrush(QColor("#222"));
tooltipItem->setPos(chart->mapToPosition(pt));
tooltipItem->show();
} else {
tooltipItem->hide();
}
});
}
performanceChartView->setChart(chart);
reply->deleteLater();
});
}
/**
* @brief Reloads stock data from the database and re-fetches live prices.
*
* Clears and repopulates the stock table, then sends updated API requests
* to fetch current prices for all stocks. Ensures that visuals and stats
* reflect the latest data.
*/
void Stock::refreshData()
{
loadStockData();
fetchLivePrices();
}
/**
* @brief Handles the HTTP response for a stock logo and updates the table cell.
*
* @param reply QNetworkReply containing logo image for the stock.
*/
void Stock::handleLogoReply(QNetworkReply *reply)
{
if (reply->error() != QNetworkReply::NoError) {
reply->deleteLater();
return;
}
QByteArray data = reply->readAll();
QPixmap logo;
logo.loadFromData(data);
int row = logoReplyMap.value(reply, -1);
if (row != -1 && !logo.isNull()) {
QTableWidgetItem *logoItem = stockTable->item(row, 0);
logoItem->setIcon(QIcon(logo.scaled(48, 48, Qt::KeepAspectRatio, Qt::SmoothTransformation)));
logoItem->setText(""); // Clear placeholder text
}
logoReplyMap.remove(reply);
reply->deleteLater();
}