Skip to content

Commit

Permalink
Exchange class
Browse files Browse the repository at this point in the history
  • Loading branch information
EspenTinius committed Feb 20, 2026
1 parent f3e7f30 commit 4890c16
Showing 1 changed file with 81 additions and 0 deletions.
81 changes: 81 additions & 0 deletions src/main/java/edu/ntnu/idi/idatt2003/g40/mappe/Exchange.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package edu.ntnu.idi.idatt2003.g40.mappe;

import java.math.BigDecimal;
import java.util.*;

/**
* Represents a stock exchange where stocks can be traded.
*/
public class Exchange {

private final String name;
private int week;
private final Map<String, Stock> stockMap;
private final Random random;

public Exchange(String name, List<Stock> stocks) {
this.name = name;
this.week = 1;
this.stockMap = new HashMap<>();
this.random = new Random();

for (Stock stock : stocks) {
stockMap.put(stock.getSymbol(), stock);
}
}

public String getName() {
return name;
}

public int getWeek() {
return week;
}

public boolean hasStock(String symbol) {
return stockMap.containsKey(symbol);
}

public Stock getStock(String symbol) {
return stockMap.get(symbol);
}

public List<Stock> findStocks(String searchTerm) {
List<Stock> result = new ArrayList<>();
for (Stock stock : stockMap.values()) {
if (stock.getSymbol().toLowerCase().contains(searchTerm.toLowerCase())
|| stock.getCompany().toLowerCase().contains(searchTerm.toLowerCase())) {
result.add(stock);
}
}
return result;
}

public Transaction buy(String symbol, BigDecimal quantity, Player player) {
Stock stock = stockMap.get(symbol);
Share share = new Share(stock, quantity, stock.getSalesPrice());
TransactionCalculator calculator = new PurchaseCalculator(share);
return new Purchase(share, week, calculator, player);
}

public Transaction sell(Share share, Player player) {
TransactionCalculator calculator = new SaleCalculator(share);
return new Sale(share, week, calculator, player);
}

* Advances the exchange to the next week and updates stock prices.
*/
public void advance() {
week++;

for (Stock stock : stockMap.values()) {
BigDecimal currentPrice = stock.getSalesPrice();

double change = (random.nextDouble() * 0.10) - 0.05;
BigDecimal factor = BigDecimal.valueOf(1 + change);

BigDecimal newPrice = currentPrice.multiply(factor);
stock.addNewSalesPrice(newPrice);
}
}
}

0 comments on commit 4890c16

Please sign in to comment.