Index: backend/src/main/java/com/tradingmk/backend/service/PortfolioService.java
===================================================================
--- backend/src/main/java/com/tradingmk/backend/service/PortfolioService.java	(revision b03a74cf409849ee8a9cd86fd7a30994969e5cfb)
+++ backend/src/main/java/com/tradingmk/backend/service/PortfolioService.java	(revision 3a93999f831bcf97e98decec6c6db863af74a5c5)
@@ -107,11 +107,23 @@
                 .orElseThrow(() -> new RuntimeException("stock not found in portfolio"));
 
+        // checks
         if (holding.getQuantity() < quantity) {
             throw new RuntimeException("not enough shares to sell");
         }
 
+        if (pricePerUnit == null) {
+            // fallback: get latest price from stock history or live API
+            Stock stock = stockRepository.findBySymbol(stockSymbol)
+                    .orElseThrow(() -> new RuntimeException("stock not found: " + stockSymbol));
+            pricePerUnit = BigDecimal.valueOf(stock.getCurrentPrice());
+        }
+
+        // gain from the sale made
         BigDecimal totalGain = pricePerUnit.multiply(BigDecimal.valueOf(quantity));
+
+
         holding.setQuantity(holding.getQuantity() - quantity);
 
+        // if holding is zero ==== remove it from database
         if (holding.getQuantity() == 0) {
             holdingRepository.delete(holding);
@@ -120,6 +132,23 @@
         }
 
+        // update
         portfolio.setBalance(portfolio.getBalance().add(totalGain));
         portfolioRepository.save(portfolio);
+
+
+        Stock stock = stockRepository.findBySymbol(stockSymbol)
+                .orElseThrow(() -> new RuntimeException("stock not found: " + stockSymbol));
+
+        Transaction transaction = new Transaction();
+        transaction.setUser(portfolio.getUser());
+        transaction.setStock(stock);
+        transaction.setType("SELL");
+        transaction.setQuantity(quantity);
+        transaction.setPrice(pricePerUnit.doubleValue());
+        transaction.setTimestamp(LocalDateTime.now());
+
+        transactionRepository.save(transaction);
+
+        System.out.println("saved sell");
     }
 }
Index: frontend/src/pages/DetailedStockView/DetailedStockView.jsx
===================================================================
--- frontend/src/pages/DetailedStockView/DetailedStockView.jsx	(revision b03a74cf409849ee8a9cd86fd7a30994969e5cfb)
+++ frontend/src/pages/DetailedStockView/DetailedStockView.jsx	(revision 3a93999f831bcf97e98decec6c6db863af74a5c5)
@@ -93,9 +93,4 @@
             return;
         }
-
-
-
-
-
         try {
             const response = await fetch("http://localhost:8080/api/portfolio/buy", {
Index: frontend/src/pages/Portfolio/Portfolio.jsx
===================================================================
--- frontend/src/pages/Portfolio/Portfolio.jsx	(revision b03a74cf409849ee8a9cd86fd7a30994969e5cfb)
+++ frontend/src/pages/Portfolio/Portfolio.jsx	(revision 3a93999f831bcf97e98decec6c6db863af74a5c5)
@@ -12,4 +12,9 @@
     const [percentage, setPercentage] = useState(null);
     const [portfolio, setPortfolio] = useState({balance: 0, holdings: []});
+
+
+    const portfolioId = portfolio?.id;
+
+
 
     useEffect(() => {
@@ -135,4 +140,49 @@
         }
     });
+
+
+    const handleSell = async (symbol, maxQuantity) => {
+        const quantity = parseInt(prompt(`Enter quantity to sell (max ${maxQuantity}):`), 10);
+
+        if (!quantity || quantity <= 0 || quantity > maxQuantity) {
+            alert("Enter a valid quantity");
+            return;
+        }
+
+        const token = localStorage.getItem("accessToken");
+        if (!token) {
+            alert("You must be logged in to sell stocks");
+            return;
+        }
+
+        try {
+            const response = await fetch("http://localhost:8080/api/portfolio/sell", {
+                method: "POST",
+                headers: {
+                    "Content-Type": "application/json",
+                    "Authorization": `Bearer ${token}`
+                },
+                body: JSON.stringify({
+                    portfolioId: portfolioId,
+                    stockSymbol: symbol,
+                    quantity: quantity,
+                    pricePerUnit: currentPrice
+                })
+            });
+
+            if (!response.ok) {
+                const text = await response.text();
+                console.error("Error:", text);
+                alert("Failed to sell stock: " + text);
+                return;
+            }
+
+
+            alert(`Sold ${quantity} shares of ${symbol}`);
+        } catch (err) {
+            console.error("Fetch error:", err);
+            alert("Network error");
+        }
+    };
 
     return (
@@ -238,5 +288,12 @@
                                 className="p-4 bg-gray-50 rounded-lg border border-gray-200"
                             >
+
                                 <div className="flex justify-between items-center mb-2">
+                                    <button
+                                        onClick={() => handleSell(holding.stockSymbol, holding.quantity)}
+                                        className="bg-red-500 hover:bg-red-600 text-white px-3 py-1 rounded text-sm"
+                                    >
+                                        Sell
+                                    </button>
                                     <div>
                                         <div className="font-semibold text-gray-900">
