-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStockTrading.java
33 lines (29 loc) · 1.04 KB
/
StockTrading.java
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
public class StockTrading {
private double userBalance; // User's balance for trading
public StockTrading(double initialBalance) {
this.userBalance = initialBalance;
}
// Buying stocks
public boolean buyStock(User user, Stock stock, int amount) {
double totalCost = stock.getCurrentPrice() * amount;
if (userBalance >= totalCost) {
user.addStock(stock.getStockName(), amount);
userBalance -= totalCost;
return true;
}
return false; // Not enough balance
}
// Selling stocks
public boolean sellStock(User user, Stock stock, int amount) {
if (user.getPortfolio().containsKey(stock.getStockName()) &&
user.getPortfolio().get(stock.getStockName()) >= amount) {
user.removeStock(stock.getStockName(), amount);
userBalance += stock.getCurrentPrice() * amount;
return true;
}
return false; // Not enough stocks
}
public double getUserBalance() {
return userBalance;
}
}