ariel / index.html
ARIELKA's picture
Add 1 files
57d01c3 verified
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>US Market Tracker | Real-time Trading</title>
<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<script>
tailwind.config = {
theme: {
extend: {
colors: {
primary: '#2563eb',
secondary: '#1e40af',
dark: '#1e293b',
light: '#f8fafc',
success: '#10b981',
danger: '#ef4444',
warning: '#f59e0b'
}
}
}
}
</script>
<style>
.stock-up {
color: #10b981;
}
.stock-down {
color: #ef4444;
}
.chart-container {
height: 300px;
}
.blink {
animation: blink-animation 1s steps(2, start) infinite;
}
@keyframes blink-animation {
to {
opacity: 0.5;
}
}
.gradient-bg {
background: linear-gradient(135deg, #2563eb 0%, #1e40af 100%);
}
.trading-panel {
transition: all 0.3s ease;
max-height: 0;
overflow: hidden;
}
.trading-panel.open {
max-height: 500px;
}
.news-ticker {
white-space: nowrap;
animation: ticker 30s linear infinite;
}
@keyframes ticker {
0% { transform: translateX(100%); }
100% { transform: translateX(-100%); }
}
</style>
</head>
<body class="bg-gray-50 text-gray-800 font-sans">
<!-- Breaking News Ticker -->
<div class="bg-dark text-white py-2 px-4 overflow-hidden">
<div class="flex items-center">
<span class="bg-danger px-2 py-1 rounded text-xs font-bold mr-3">BREAKING</span>
<div class="news-ticker">
<span class="mr-8">Fed signals more rate hikes ahead despite banking turmoil</span>
<span class="mr-8">Tech stocks lead market rally as inflation cools</span>
<span class="mr-8">Tesla shares jump after record deliveries</span>
<span>Apple announces new products event next week</span>
</div>
</div>
</div>
<!-- Header -->
<header class="gradient-bg text-white shadow-lg">
<div class="container mx-auto px-4 py-6">
<div class="flex justify-between items-center">
<div class="flex items-center space-x-2">
<i class="fas fa-chart-line text-2xl"></i>
<h1 class="text-2xl font-bold">US Market Tracker</h1>
</div>
<div class="flex items-center space-x-4">
<div class="hidden md:flex items-center space-x-2">
<span class="text-sm">Last updated:</span>
<span id="update-time" class="font-semibold blink">Loading...</span>
</div>
<button id="refresh-btn" class="bg-white text-primary px-4 py-2 rounded-lg font-medium hover:bg-opacity-90 transition">
<i class="fas fa-sync-alt mr-2"></i>Refresh
</button>
</div>
</div>
</div>
</header>
<!-- Trading Panel -->
<section class="container mx-auto px-4 pt-6">
<div class="bg-white rounded-xl shadow-md overflow-hidden">
<div class="flex justify-between items-center p-4 cursor-pointer" id="trading-toggle">
<div class="flex items-center space-x-3">
<i class="fas fa-coins text-yellow-500 text-xl"></i>
<h2 class="text-lg font-semibold">Virtual Trading Portfolio</h2>
</div>
<div class="flex items-center space-x-4">
<div class="text-right">
<p class="text-sm text-gray-500">Balance</p>
<p id="portfolio-balance" class="font-bold">₪100,000.00</p>
</div>
<div id="portfolio-change" class="text-right">
<p class="text-sm text-gray-500">Today's P&L</p>
<p id="portfolio-today" class="font-bold">₪0.00</p>
</div>
<i class="fas fa-chevron-down transition-transform duration-300" id="trading-arrow"></i>
</div>
</div>
<div class="trading-panel bg-gray-50" id="trading-panel">
<div class="grid grid-cols-1 md:grid-cols-3 gap-6 p-4">
<!-- Buy/Sell Panel -->
<div class="bg-white p-4 rounded-lg shadow-sm border border-gray-200">
<h3 class="font-medium mb-3 flex items-center">
<i class="fas fa-exchange-alt mr-2 text-gray-500"></i> Trade Stocks
</h3>
<div class="space-y-3">
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">Action</label>
<div class="flex space-x-2">
<button id="buy-btn" class="flex-1 bg-success bg-opacity-20 text-success py-2 px-4 rounded border border-success border-opacity-50 font-medium">
<i class="fas fa-arrow-up mr-1"></i> Buy
</button>
<button id="sell-btn" class="flex-1 bg-danger bg-opacity-10 text-danger py-2 px-4 rounded border border-danger border-opacity-30 font-medium">
<i class="fas fa-arrow-down mr-1"></i> Sell
</button>
</div>
</div>
<div>
<label for="trade-symbol" class="block text-sm font-medium text-gray-700 mb-1">Symbol</label>
<input type="text" id="trade-symbol" placeholder="e.g. AAPL, TSLA" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary">
</div>
<div>
<label for="trade-shares" class="block text-sm font-medium text-gray-700 mb-1">Shares</label>
<input type="number" id="trade-shares" value="1" min="1" class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary">
</div>
<div class="pt-2">
<button id="execute-trade" class="w-full bg-primary text-white py-2 px-4 rounded-md font-medium hover:bg-secondary transition">
Execute Trade
</button>
</div>
</div>
</div>
<!-- Portfolio Holdings -->
<div class="bg-white p-4 rounded-lg shadow-sm border border-gray-200">
<h3 class="font-medium mb-3 flex items-center">
<i class="fas fa-chart-pie mr-2 text-gray-500"></i> Your Holdings
</h3>
<div class="overflow-y-auto max-h-64">
<table class="min-w-full divide-y divide-gray-200">
<thead>
<tr>
<th class="px-2 py-1 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Symbol</th>
<th class="px-2 py-1 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Shares</th>
<th class="px-2 py-1 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Avg Price</th>
<th class="px-2 py-1 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Value</th>
<th class="px-2 py-1 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">P&L</th>
<th class="px-2 py-1 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Last Update</th>
</tr>
</thead>
<tbody id="holdings-table" class="bg-white divide-y divide-gray-200 text-sm">
<!-- Holdings will be added here -->
<tr>
<td colspan="6" class="px-2 py-4 text-center text-gray-500">No holdings yet</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- Trade History -->
<div class="bg-white p-4 rounded-lg shadow-sm border border-gray-200">
<h3 class="font-medium mb-3 flex items-center">
<i class="fas fa-history mr-2 text-gray-500"></i> Trade History
</h3>
<div class="overflow-y-auto max-h-64">
<table class="min-w-full divide-y divide-gray-200">
<thead>
<tr>
<th class="px-2 py-1 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Date</th>
<th class="px-2 py-1 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Action</th>
<th class="px-2 py-1 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Symbol</th>
<th class="px-2 py-1 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Shares</th>
<th class="px-2 py-1 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Price</th>
</tr>
</thead>
<tbody id="history-table" class="bg-white divide-y divide-gray-200 text-sm">
<!-- Trade history will be added here -->
<tr>
<td colspan="5" class="px-2 py-4 text-center text-gray-500">No trades yet</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- Market Overview -->
<section class="container mx-auto px-4 py-6">
<div class="grid grid-cols-1 md:grid-cols-4 gap-4">
<!-- S&P 500 -->
<div class="bg-white rounded-xl shadow-md p-4 border-l-4 border-primary">
<div class="flex justify-between items-start">
<div>
<h3 class="text-gray-500 text-sm font-medium">S&P 500</h3>
<p id="sp500-price" class="text-2xl font-bold mt-1">-</p>
</div>
<div id="sp500-change" class="text-right">
<p class="text-sm">-</p>
<p class="text-sm">-</p>
</div>
</div>
<div class="chart-container mt-4">
<canvas id="sp500-chart"></canvas>
</div>
</div>
<!-- Dow Jones -->
<div class="bg-white rounded-xl shadow-md p-4 border-l-4 border-secondary">
<div class="flex justify-between items-start">
<div>
<h3 class="text-gray-500 text-sm font-medium">Dow Jones</h3>
<p id="dow-price" class="text-2xl font-bold mt-1">-</p>
</div>
<div id="dow-change" class="text-right">
<p class="text-sm">-</p>
<p class="text-sm">-</p>
</div>
</div>
<div class="chart-container mt-4">
<canvas id="dow-chart"></canvas>
</div>
</div>
<!-- NASDAQ -->
<div class="bg-white rounded-xl shadow-md p-4 border-l-4 border-success">
<div class="flex justify-between items-start">
<div>
<h3 class="text-gray-500 text-sm font-medium">NASDAQ</h3>
<p id="nasdaq-price" class="text-2xl font-bold mt-1">-</p>
</div>
<div id="nasdaq-change" class="text-right">
<p class="text-sm">-</p>
<p class="text-sm">-</p>
</div>
</div>
<div class="chart-container mt-4">
<canvas id="nasdaq-chart"></canvas>
</div>
</div>
<!-- Russell 2000 -->
<div class="bg-white rounded-xl shadow-md p-4 border-l-4 border-warning">
<div class="flex justify-between items-start">
<div>
<h3 class="text-gray-500 text-sm font-medium">Russell 2000</h3>
<p id="russell-price" class="text-2xl font-bold mt-1">-</p>
</div>
<div id="russell-change" class="text-right">
<p class="text-sm">-</p>
<p class="text-sm">-</p>
</div>
</div>
<div class="chart-container mt-4">
<canvas id="russell-chart"></canvas>
</div>
</div>
</div>
</section>
<!-- Market Data -->
<section class="container mx-auto px-4 py-6">
<div class="bg-white rounded-xl shadow-md overflow-hidden">
<!-- Tabs -->
<div class="border-b border-gray-200">
<nav class="flex -mb-px">
<button id="stocks-tab" class="tab-button active py-4 px-6 text-center border-b-2 font-medium text-sm border-primary text-primary">
<i class="fas fa-chart-bar mr-2"></i>Top Stocks
</button>
<button id="sectors-tab" class="tab-button py-4 px-6 text-center border-b-2 font-medium text-sm border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300">
<i class="fas fa-industry mr-2"></i>Sectors
</button>
<button id="news-tab" class="tab-button py-4 px-6 text-center border-b-2 font-medium text-sm border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300">
<i class="fas fa-newspaper mr-2"></i>Market News
</button>
</nav>
</div>
<!-- Tab Content -->
<div id="stocks-content" class="tab-content block p-4">
<div class="flex justify-between items-center mb-4">
<h2 class="text-lg font-semibold">Top US Stocks</h2>
<div class="relative">
<select id="stock-filter" class="block appearance-none bg-gray-100 border border-gray-200 text-gray-700 py-2 px-4 pr-8 rounded leading-tight focus:outline-none focus:bg-white focus:border-primary">
<option value="gainers">Top Gainers</option>
<option value="losers">Top Losers</option>
<option value="active">Most Active</option>
</select>
<div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-2 text-gray-700">
<i class="fas fa-chevron-down"></i>
</div>
</div>
</div>
<div class="overflow-x-auto">
<table class="min-w-full divide-y divide-gray-200">
<thead class="bg-gray-50">
<tr>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Symbol</th>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Name</th>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Price</th>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Change</th>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">% Change</th>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Last Update</th>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Volume</th>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Trade</th>
</tr>
</thead>
<tbody id="stocks-table-body" class="bg-white divide-y divide-gray-200">
<!-- Stocks data will be inserted here -->
</tbody>
</table>
</div>
</div>
<div id="sectors-content" class="tab-content hidden p-4">
<h2 class="text-lg font-semibold mb-4">Sector Performance</h2>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<canvas id="sector-chart"></canvas>
</div>
<div>
<div class="space-y-3">
<!-- Sector performance will be inserted here -->
</div>
</div>
</div>
</div>
<div id="news-content" class="tab-content hidden p-4">
<h2 class="text-lg font-semibold mb-4">Latest Market News</h2>
<div id="news-container" class="space-y-4">
<!-- News articles will be inserted here -->
</div>
</div>
</div>
</section>
<!-- Search Section -->
<section class="container mx-auto px-4 py-6">
<div class="bg-white rounded-xl shadow-md p-6">
<h2 class="text-lg font-semibold mb-4">Search Stocks</h2>
<div class="flex">
<input id="stock-search" type="text" placeholder="Enter stock symbol (e.g. AAPL, MSFT)" class="flex-grow px-4 py-2 border border-gray-300 rounded-l-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
<button id="search-btn" class="bg-primary text-white px-6 py-2 rounded-r-lg hover:bg-secondary transition">
<i class="fas fa-search mr-2"></i>Search
</button>
</div>
<div id="search-results" class="mt-4 hidden">
<!-- Search results will be displayed here -->
</div>
</div>
</section>
<!-- Footer -->
<footer class="bg-dark text-white py-8">
<div class="container mx-auto px-4">
<div class="flex flex-col md:flex-row justify-between items-center">
<div class="mb-4 md:mb-0">
<div class="flex items-center space-x-2">
<i class="fas fa-chart-line text-2xl"></i>
<h2 class="text-xl font-bold">US Market Tracker</h2>
</div>
<p class="text-gray-400 mt-2">Real-time stock market data and virtual trading</p>
</div>
<div class="flex space-x-6">
<a href="#" class="text-gray-400 hover:text-white transition"><i class="fab fa-twitter"></i></a>
<a href="#" class="text-gray-400 hover:text-white transition"><i class="fab fa-linkedin"></i></a>
<a href="#" class="text-gray-400 hover:text-white transition"><i class="fab fa-github"></i></a>
</div>
</div>
<div class="border-t border-gray-700 mt-6 pt-6 text-sm text-gray-400">
<p>© 2023 US Market Tracker. Virtual trading for educational purposes only.</p>
<p class="mt-2">Data provided by financial APIs. Prices are simulated for demonstration.</p>
</div>
</div>
</footer>
<!-- Stock Details Modal -->
<div id="stock-modal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
<div class="bg-white rounded-xl w-full max-w-4xl max-h-[90vh] overflow-y-auto">
<div class="p-6">
<div class="flex justify-between items-start">
<div>
<h2 id="modal-stock-name" class="text-2xl font-bold">-</h2>
<p id="modal-stock-symbol" class="text-gray-500">-</p>
</div>
<button id="close-modal" class="text-gray-500 hover:text-gray-700">
<i class="fas fa-times text-2xl"></i>
</button>
</div>
<div class="mt-6 grid grid-cols-1 md:grid-cols-3 gap-6">
<div class="col-span-2">
<div class="chart-container">
<canvas id="modal-stock-chart"></canvas>
</div>
</div>
<div>
<div class="bg-gray-50 p-4 rounded-lg">
<h3 class="font-semibold mb-3">Key Statistics</h3>
<div class="space-y-3">
<div class="flex justify-between">
<span class="text-gray-600">Price</span>
<span id="modal-price" class="font-medium">-</span>
</div>
<div class="flex justify-between">
<span class="text-gray-600">Change</span>
<span id="modal-change" class="font-medium">-</span>
</div>
<div class="flex justify-between">
<span class="text-gray-600">% Change</span>
<span id="modal-change-percent" class="font-medium">-</span>
</div>
<div class="flex justify-between">
<span class="text-gray-600">Market Cap</span>
<span id="modal-market-cap" class="font-medium">-</span>
</div>
<div class="flex justify-between">
<span class="text-gray-600">PE Ratio</span>
<span id="modal-pe-ratio" class="font-medium">-</span>
</div>
<div class="flex justify-between">
<span class="text-gray-600">52 Week High</span>
<span id="modal-52-high" class="font-medium">-</span>
</div>
<div class="flex justify-between">
<span class="text-gray-600">52 Week Low</span>
<span id="modal-52-low" class="font-medium">-</span>
</div>
<div class="flex justify-between">
<span class="text-gray-600">Last Update</span>
<span id="modal-last-update" class="font-medium">-</span>
</div>
</div>
</div>
<div class="mt-4 bg-gray-50 p-4 rounded-lg">
<h3 class="font-semibold mb-3">Quick Trade</h3>
<div class="flex space-x-2 mb-2">
<button id="modal-buy-btn" class="flex-1 bg-success bg-opacity-20 text-success py-2 px-4 rounded border border-success border-opacity-50 font-medium">
<i class="fas fa-arrow-up mr-1"></i> Buy
</button>
<button id="modal-sell-btn" class="flex-1 bg-danger bg-opacity-10 text-danger py-2 px-4 rounded border border-danger border-opacity-30 font-medium">
<i class="fas fa-arrow-down mr-1"></i> Sell
</button>
</div>
<div class="flex items-center space-x-2">
<input type="number" id="modal-trade-shares" value="1" min="1" class="flex-1 px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary">
<button id="modal-execute-trade" class="bg-primary text-white py-2 px-4 rounded-md font-medium hover:bg-secondary transition">
Execute
</button>
</div>
</div>
</div>
</div>
<div class="mt-6">
<h3 class="font-semibold mb-3">About</h3>
<p id="modal-company-description" class="text-gray-700">-</p>
</div>
</div>
</div>
</div>
<!-- Trade Confirmation Toast -->
<div id="trade-toast" class="fixed bottom-4 right-4 bg-green-500 text-white px-6 py-3 rounded-lg shadow-lg flex items-center space-x-3 transform translate-y-10 opacity-0 transition-all duration-300 z-50">
<i class="fas fa-check-circle text-xl"></i>
<span id="toast-message">Trade executed successfully!</span>
</div>
<!-- Breaking News Alert -->
<div id="breaking-news-alert" class="fixed top-20 right-4 bg-red-600 text-white px-4 py-2 rounded-lg shadow-lg flex items-center space-x-2 transform translate-x-full transition-transform duration-300 z-50">
<i class="fas fa-bolt"></i>
<span id="breaking-news-text">Breaking: Fed announces rate hike</span>
</div>
<!-- Scripts -->
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
// Mock data - in a real app, you would fetch this from a financial API
const mockIndices = {
"S&P 500": {
price: 4532.76,
change: 12.34,
changePercent: 0.27,
history: Array.from({length: 30}, (_, i) => 4500 + Math.sin(i/3) * 50 + Math.random() * 20),
lastUpdate: new Date()
},
"Dow Jones": {
price: 34721.12,
change: -45.67,
changePercent: -0.13,
history: Array.from({length: 30}, (_, i) => 34600 + Math.sin(i/3) * 150 + Math.random() * 50),
lastUpdate: new Date()
},
"NASDAQ": {
price: 14138.57,
change: 78.90,
changePercent: 0.56,
history: Array.from({length: 30}, (_, i) => 14000 + Math.sin(i/3) * 200 + Math.random() * 80),
lastUpdate: new Date()
},
"Russell 2000": {
price: 1987.34,
change: 5.43,
changePercent: 0.27,
history: Array.from({length: 30}, (_, i) => 1950 + Math.sin(i/3) * 50 + Math.random() * 20),
lastUpdate: new Date()
}
};
const mockStocks = {
gainers: [
{symbol: "TSLA", name: "Tesla Inc", price: 275.34, change: 25.67, changePercent: 10.28, volume: "45.2M", lastUpdate: new Date()},
{symbol: "NVDA", name: "NVIDIA Corporation", price: 456.78, change: 32.45, changePercent: 7.65, volume: "32.1M", lastUpdate: new Date()},
{symbol: "AMD", name: "Advanced Micro Devices", price: 112.34, change: 8.76, changePercent: 8.45, volume: "28.7M", lastUpdate: new Date()},
{symbol: "MRNA", name: "Moderna Inc", price: 145.67, change: 12.34, changePercent: 9.25, volume: "15.3M", lastUpdate: new Date()},
{symbol: "SHOP", name: "Shopify Inc", price: 78.90, change: 6.78, changePercent: 9.41, volume: "12.4M", lastUpdate: new Date()}
],
losers: [
{symbol: "INTC", name: "Intel Corporation", price: 34.56, change: -2.34, changePercent: -6.34, volume: "45.6M", lastUpdate: new Date()},
{symbol: "WBA", name: "Walgreens Boots Alliance", price: 23.45, change: -1.23, changePercent: -4.98, volume: "12.3M", lastUpdate: new Date()},
{symbol: "DIS", name: "Walt Disney Company", price: 87.65, change: -3.45, changePercent: -3.79, volume: "18.9M", lastUpdate: new Date()},
{symbol: "CSCO", name: "Cisco Systems", price: 56.78, change: -1.23, changePercent: -2.12, volume: "15.6M", lastUpdate: new Date()},
{symbol: "IBM", name: "International Business Machines", price: 134.56, change: -2.34, changePercent: -1.71, volume: "4.5M", lastUpdate: new Date()}
],
active: [
{symbol: "AAPL", name: "Apple Inc", price: 189.37, change: 1.23, changePercent: 0.65, volume: "78.9M", lastUpdate: new Date()},
{symbol: "AMZN", name: "Amazon.com Inc", price: 134.56, change: -0.78, changePercent: -0.58, volume: "45.6M", lastUpdate: new Date()},
{symbol: "MSFT", name: "Microsoft Corporation", price: 345.67, change: 2.34, changePercent: 0.68, volume: "56.7M", lastUpdate: new Date()},
{symbol: "GOOGL", name: "Alphabet Inc", price: 134.56, change: 1.23, changePercent: 0.92, volume: "34.5M", lastUpdate: new Date()},
{symbol: "META", name: "Meta Platforms Inc", price: 298.76, change: 5.67, changePercent: 1.93, volume: "32.1M", lastUpdate: new Date()}
]
};
const mockSectors = [
{name: "Technology", performance: 1.23},
{name: "Healthcare", performance: 0.87},
{name: "Financials", performance: 0.45},
{name: "Consumer Discretionary", performance: 0.78},
{name: "Communication Services", performance: 0.56},
{name: "Industrials", performance: 0.34},
{name: "Consumer Staples", performance: -0.12},
{name: "Energy", performance: -0.45},
{name: "Utilities", performance: -0.23},
{name: "Real Estate", performance: -0.34},
{name: "Materials", performance: 0.12}
];
const mockNews = [
{
title: "Fed Signals More Rate Hikes Ahead Despite Banking Turmoil",
source: "Wall Street Journal",
time: "2 hours ago",
summary: "Federal Reserve officials signaled they expect to raise interest rates further this year despite recent stress in the banking sector, according to minutes from their March meeting released Wednesday."
},
{
title: "Tech Stocks Lead Market Rally as Inflation Cools",
source: "Bloomberg",
time: "4 hours ago",
summary: "Technology stocks led a broad market rally Wednesday after fresh data showed inflation cooling more than expected in March, raising hopes the Federal Reserve may soon pause its interest-rate hikes."
},
{
title: "Tesla Shares Jump After Record Deliveries",
source: "CNBC",
time: "6 hours ago",
summary: "Tesla shares surged more than 7% Wednesday after the electric-vehicle maker reported record quarterly deliveries that beat Wall Street estimates, easing concerns about softening demand."
}
];
const mockStockDetails = {
"AAPL": {
name: "Apple Inc.",
price: 189.37,
change: 1.23,
changePercent: 0.65,
marketCap: "2.85T",
peRatio: 29.45,
high52: 198.23,
low52: 124.17,
description: "Apple Inc. designs, manufactures, and markets smartphones, personal computers, tablets, wearables, and accessories worldwide. The company offers iPhone, Mac, iPad, and Wearables, Home and Accessories. It also provides Apple TV+, Apple Music, Apple Arcade, Apple Fitness+, Apple Card, and Apple Pay, as well as licenses its intellectual property.",
history: Array.from({length: 30}, (_, i) => 180 + Math.sin(i/3) * 10 + Math.random() * 5),
lastUpdate: new Date()
},
"TSLA": {
name: "Tesla Inc.",
price: 275.34,
change: 25.67,
changePercent: 10.28,
marketCap: "872.54B",
peRatio: 58.23,
high52: 384.29,
low52: 101.81,
description: "Tesla, Inc. designs, develops, manufactures, leases, and sells electric vehicles, and energy generation and storage systems in the United States, China, and internationally. The company operates in two segments, Automotive, and Energy Generation and Storage. It produces and sells electric vehicles. The company also offers vehicle service centers, superchargers, and self-driving capabilities.",
history: Array.from({length: 30}, (_, i) => 250 + Math.sin(i/3) * 30 + Math.random() * 15),
lastUpdate: new Date()
}
};
// Breaking news items
const breakingNews = [
"Fed announces 0.25% rate hike",
"Apple unveils new products at special event",
"Tesla reports record quarterly earnings",
"Microsoft acquires AI startup for $2 billion",
"Amazon announces major layoffs"
];
// Virtual Trading Variables
let virtualPortfolio = {
balance: 100000, // Starting with ₪100,000
holdings: {}, // {symbol: {shares, avgPrice, lastUpdate}}
history: [], // Array of trade history
todayStartBalance: 100000 // For calculating today's P&L
};
let currentAction = 'buy'; // 'buy' or 'sell'
let stockPrices = {}; // To track current prices for P&L calculation
// DOM Elements
const updateTimeEl = document.getElementById('update-time');
const refreshBtn = document.getElementById('refresh-btn');
// Trading elements
const tradingToggle = document.getElementById('trading-toggle');
const tradingPanel = document.getElementById('trading-panel');
const tradingArrow = document.getElementById('trading-arrow');
const portfolioBalance = document.getElementById('portfolio-balance');
const portfolioToday = document.getElementById('portfolio-today');
const buyBtn = document.getElementById('buy-btn');
const sellBtn = document.getElementById('sell-btn');
const tradeSymbol = document.getElementById('trade-symbol');
const tradeShares = document.getElementById('trade-shares');
const executeTradeBtn = document.getElementById('execute-trade');
const holdingsTable = document.getElementById('holdings-table');
const historyTable = document.getElementById('history-table');
// Modal trade elements
const modalBuyBtn = document.getElementById('modal-buy-btn');
const modalSellBtn = document.getElementById('modal-sell-btn');
const modalTradeShares = document.getElementById('modal-trade-shares');
const modalExecuteTradeBtn = document.getElementById('modal-execute-trade');
const modalLastUpdate = document.getElementById('modal-last-update');
// Toast element
const tradeToast = document.getElementById('trade-toast');
const toastMessage = document.getElementById('toast-message');
// Breaking news elements
const breakingNewsAlert = document.getElementById('breaking-news-alert');
const breakingNewsText = document.getElementById('breaking-news-text');
// Index elements
const indexElements = {
"S&P 500": {
price: document.getElementById('sp500-price'),
change: document.getElementById('sp500-change'),
chart: document.getElementById('sp500-chart')
},
"Dow Jones": {
price: document.getElementById('dow-price'),
change: document.getElementById('dow-change'),
chart: document.getElementById('dow-chart')
},
"NASDAQ": {
price: document.getElementById('nasdaq-price'),
change: document.getElementById('nasdaq-change'),
chart: document.getElementById('nasdaq-chart')
},
"Russell 2000": {
price: document.getElementById('russell-price'),
change: document.getElementById('russell-change'),
chart: document.getElementById('russell-chart')
}
};
// Tab elements
const tabButtons = {
stocks: document.getElementById('stocks-tab'),
sectors: document.getElementById('sectors-tab'),
news: document.getElementById('news-tab')
};
const tabContents = {
stocks: document.getElementById('stocks-content'),
sectors: document.getElementById('sectors-content'),
news: document.getElementById('news-content')
};
// Stock table elements
const stockFilter = document.getElementById('stock-filter');
const stocksTableBody = document.getElementById('stocks-table-body');
// Sector elements
const sectorChartEl = document.getElementById('sector-chart');
// News elements
const newsContainer = document.getElementById('news-container');
// Search elements
const stockSearch = document.getElementById('stock-search');
const searchBtn = document.getElementById('search-btn');
const searchResults = document.getElementById('search-results');
// Modal elements
const stockModal = document.getElementById('stock-modal');
const closeModalBtn = document.getElementById('close-modal');
const modalStockName = document.getElementById('modal-stock-name');
const modalStockSymbol = document.getElementById('modal-stock-symbol');
const modalStockChart = document.getElementById('modal-stock-chart');
const modalPrice = document.getElementById('modal-price');
const modalChange = document.getElementById('modal-change');
const modalChangePercent = document.getElementById('modal-change-percent');
const modalMarketCap = document.getElementById('modal-market-cap');
const modalPeRatio = document.getElementById('modal-pe-ratio');
const modal52High = document.getElementById('modal-52-high');
const modal52Low = document.getElementById('modal-52-low');
const modalCompanyDescription = document.getElementById('modal-company-description');
// Charts
let indexCharts = {};
let sectorChart = null;
let modalChart = null;
// Initialize the app
function init() {
updateTime();
loadIndices();
loadStocks('gainers');
loadSectors();
loadNews();
setupEventListeners();
updatePortfolioDisplay();
// Update time every minute
setInterval(updateTime, 60000);
// Simulate real-time price updates every 5 seconds
setInterval(simulatePriceChanges, 5000);
// Show breaking news alerts randomly
setInterval(showBreakingNews, 30000);
}
// Show breaking news alert
function showBreakingNews() {
const randomNews = breakingNews[Math.floor(Math.random() * breakingNews.length)];
breakingNewsText.textContent = `Breaking: ${randomNews}`;
// Show alert
breakingNewsAlert.classList.remove('translate-x-full');
breakingNewsAlert.classList.add('-translate-x-0');
// Hide after 5 seconds
setTimeout(() => {
breakingNewsAlert.classList.remove('-translate-x-0');
breakingNewsAlert.classList.add('translate-x-full');
}, 5000);
}
// Update the time display
function updateTime() {
const now = new Date();
const timeString = now.toLocaleTimeString('en-US', {hour: '2-digit', minute: '2-digit'});
const dateString = now.toLocaleDateString('en-US', {weekday: 'short', month: 'short', day: 'numeric'});
updateTimeEl.textContent = `${dateString} ${timeString}`;
updateTimeEl.classList.remove('blink');
}
// Format date for display
function formatDate(date) {
return date.toLocaleTimeString('en-US', {hour: '2-digit', minute: '2-digit'});
}
// Simulate small price changes for realism
function simulatePriceChanges() {
const now = new Date();
// Update indices
Object.keys(mockIndices).forEach(indexName => {
const index = mockIndices[indexName];
const change = (Math.random() - 0.5) * index.price * 0.001; // Small random change
index.price += change;
index.change += change;
index.changePercent = (index.change / (index.price - index.change)) * 100;
index.lastUpdate = now;
// Shift history
index.history.shift();
index.history.push(index.price);
// Update display
updateIndexDisplay(indexName);
});
// Update stocks
Object.keys(mockStocks).forEach(type => {
mockStocks[type].forEach(stock => {
const change = (Math.random() - 0.5) * stock.price * 0.01; // Larger random change for stocks
stock.price += change;
stock.change += change;
stock.changePercent = (stock.change / (stock.price - stock.change)) * 100;
stock.lastUpdate = now;
// Store current price for P&L calculation
stockPrices[stock.symbol] = stock.price;
});
});
// Update stock details
Object.keys(mockStockDetails).forEach(symbol => {
const stock = mockStockDetails[symbol];
const change = (Math.random() - 0.5) * stock.price * 0.01;
stock.price += change;
stock.change += change;
stock.changePercent = (stock.change / (stock.price - stock.change)) * 100;
stock.lastUpdate = now;
// Shift history
stock.history.shift();
stock.history.push(stock.price);
// Store current price for P&L calculation
stockPrices[symbol] = stock.price;
});
// Update portfolio P&L
updatePortfolioDisplay();
}
// Update index display
function updateIndexDisplay(indexName) {
const indexData = mockIndices[indexName];
const elements = indexElements[indexName];
// Update price
elements.price.textContent = indexData.price.toFixed(2);
// Update change
const isPositive = indexData.change >= 0;
const changeClass = isPositive ? 'stock-up' : 'stock-down';
const changeIcon = isPositive ? '▲' : '▼';
elements.change.innerHTML = `
<p class="${changeClass}">${changeIcon} ${Math.abs(indexData.change).toFixed(2)}</p>
<p class="${changeClass}">(${isPositive ? '+' : ''}${indexData.changePercent.toFixed(2)}%)</p>
`;
// Update chart
if (indexCharts[indexName]) {
indexCharts[indexName].data.datasets[0].data = indexData.history;
indexCharts[indexName].update();
}
}
// Load and display market indices
function loadIndices() {
Object.keys(mockIndices).forEach(indexName => {
const indexData = mockIndices[indexName];
// Store initial prices for P&L calculation
stockPrices[indexName] = indexData.price;
// Update display
updateIndexDisplay(indexName);
// Create chart
createIndexChart(indexName, indexElements[indexName].chart, indexData.history);
});
}
// Create a chart for a market index
function createIndexChart(indexName, chartEl, historyData) {
const ctx = chartEl.getContext('2d');
// Destroy previous chart if it exists
if (indexCharts[indexName]) {
indexCharts[indexName].destroy();
}
const isPositive = mockIndices[indexName].change >= 0;
const borderColor = isPositive ? '#10b981' : '#ef4444';
const backgroundColor = isPositive ? 'rgba(16, 185, 129, 0.1)' : 'rgba(239, 68, 68, 0.1)';
indexCharts[indexName] = new Chart(ctx, {
type: 'line',
data: {
labels: historyData.map((_, i) => i + 1),
datasets: [{
data: historyData,
borderColor: borderColor,
backgroundColor: backgroundColor,
borderWidth: 2,
fill: true,
tension: 0.4,
pointRadius: 0
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
display: false
},
tooltip: {
enabled: false
}
},
scales: {
x: {
display: false
},
y: {
display: false
}
},
interaction: {
intersect: false,
mode: 'index'
}
}
});
}
// Load and display stocks
function loadStocks(type) {
const stocks = mockStocks[type];
stocksTableBody.innerHTML = '';
stocks.forEach(stock => {
const isPositive = stock.change >= 0;
const changeClass = isPositive ? 'stock-up' : 'stock-down';
const changeIcon = isPositive ? '▲' : '▼';
// Store current price for P&L calculation
stockPrices[stock.symbol] = stock.price;
const row = document.createElement('tr');
row.className = 'hover:bg-gray-50';
row.innerHTML = `
<td class="px-6 py-4 whitespace-nowrap font-medium text-gray-900">${stock.symbol}</td>
<td class="px-6 py-4 whitespace-nowrap text-gray-500">${stock.name}</td>
<td class="px-6 py-4 whitespace-nowrap font-medium">${stock.price.toFixed(2)}</td>
<td class="px-6 py-4 whitespace-nowrap ${changeClass}">${changeIcon} ${Math.abs(stock.change).toFixed(2)}</td>
<td class="px-6 py-4 whitespace-nowrap ${changeClass}">(${isPositive ? '+' : ''}${stock.changePercent.toFixed(2)}%)</td>
<td class="px-6 py-4 whitespace-nowrap text-gray-500 text-sm">${formatDate(stock.lastUpdate)}</td>
<td class="px-6 py-4 whitespace-nowrap text-gray-500">${stock.volume}</td>
<td class="px-6 py-4 whitespace-nowrap">
<button class="text-primary hover:text-secondary mr-2 trade-btn" data-symbol="${stock.symbol}" data-action="buy">
<i class="fas fa-arrow-up"></i>
</button>
<button class="text-danger hover:text-red-700 trade-btn" data-symbol="${stock.symbol}" data-action="sell">
<i class="fas fa-arrow-down"></i>
</button>
</td>
`;
// Add click event to open stock details
row.addEventListener('click', (e) => {
// Don't open modal if clicking on trade buttons
if (!e.target.closest('.trade-btn')) {
openStockModal(stock.symbol);
}
});
stocksTableBody.appendChild(row);
});
// Add event listeners to trade buttons
document.querySelectorAll('.trade-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
e.stopPropagation(); // Prevent row click event
const symbol = e.target.closest('button').dataset.symbol;
const action = e.target.closest('button').dataset.action;
openTradePanel(symbol, action);
});
});
}
// Open trade panel with symbol pre-filled
function openTradePanel(symbol, action) {
// Open trading panel if closed
if (!tradingPanel.classList.contains('open')) {
tradingToggle.click();
}
// Set the trade action
if (action === 'buy') {
buyBtn.click();
} else {
sellBtn.click();
}
// Set the symbol
tradeSymbol.value = symbol;
// Focus on shares input
tradeShares.focus();
}
// Load and display sectors
function loadSectors() {
// Create sector chart
const ctx = sectorChartEl.getContext('2d');
if (sectorChart) {
sectorChart.destroy();
}
const labels = mockSectors.map(sector => sector.name);
const data = mockSectors.map(sector => sector.performance);
const backgroundColors = data.map(perf =>
perf >= 0 ? `rgba(16, 185, 129, ${0.3 + Math.min(0.7, perf/3)})` : `rgba(239, 68, 68, ${0.3 + Math.min(0.7, Math.abs(perf)/3)})`
);
const borderColors = data.map(perf =>
perf >= 0 ? 'rgba(16, 185, 129, 1)' : 'rgba(239, 68, 68, 1)'
);
sectorChart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
data: data,
backgroundColor: backgroundColors,
borderColor: borderColors,
borderWidth: 1
}]
},
options: {
responsive: true,
plugins: {
legend: {
display: false
},
tooltip: {
callbacks: {
label: function(context) {
const value = context.raw;
return `${value >= 0 ? '+' : ''}${value.toFixed(2)}%`;
}
}
}
},
scales: {
x: {
display: false
},
y: {
display: true,
title: {
display: true,
text: '% Change'
}
}
}
}
});
// Add sector performance list
const sectorList = document.querySelector('#sectors-content .space-y-3');
sectorList.innerHTML = '';
mockSectors.forEach(sector => {
const isPositive = sector.performance >= 0;
const changeClass = isPositive ? 'text-success' : 'text-danger';
const changeIcon = isPositive ? '▲' : '▼';
const sectorEl = document.createElement('div');
sectorEl.className = 'flex justify-between items-center p-2 hover:bg-gray-50 rounded';
sectorEl.innerHTML = `
<span class="font-medium">${sector.name}</span>
<span class="${changeClass}">${changeIcon} ${isPositive ? '+' : ''}${sector.performance.toFixed(2)}%</span>
`;
sectorList.appendChild(sectorEl);
});
}
// Load and display news
function loadNews() {
newsContainer.innerHTML = '';
mockNews.forEach(news => {
const newsEl = document.createElement('div');
newsEl.className = 'bg-gray-50 p-4 rounded-lg hover:bg-gray-100 transition cursor-pointer';
newsEl.innerHTML = `
<h3 class="font-semibold text-lg mb-1">${news.title}</h3>
<div class="flex items-center text-sm text-gray-500 mb-2">
<span>${news.source}</span>
<span class="mx-2">•</span>
<span>${news.time}</span>
</div>
<p class="text-gray-700">${news.summary}</p>
`;
newsContainer.appendChild(newsEl);
});
}
// Open stock details modal
function openStockModal(symbol) {
const stock = mockStockDetails[symbol] || {
name: `${symbol} Company`,
price: 0,
change: 0,
changePercent: 0,
marketCap: "-",
peRatio: "-",
high52: "-",
low52: "-",
description: "No description available for this stock.",
history: Array.from({length: 30}, (_, i) => 100 + Math.sin(i/3) * 20 + Math.random() * 10),
lastUpdate: new Date()
};
// Update modal content
modalStockName.textContent = stock.name;
modalStockSymbol.textContent = symbol;
modalPrice.textContent = stock.price.toFixed(2);
const isPositive = stock.change >= 0;
const changeClass = isPositive ? 'text-success' : 'text-danger';
const changeIcon = isPositive ? '▲' : '▼';
modalChange.className = changeClass;
modalChange.textContent = `${changeIcon} ${Math.abs(stock.change).toFixed(2)}`;
modalChangePercent.className = changeClass;
modalChangePercent.textContent = `(${isPositive ? '+' : ''}${stock.changePercent.toFixed(2)}%)`;
modalMarketCap.textContent = stock.marketCap;
modalPeRatio.textContent = stock.peRatio;
modal52High.textContent = stock.high52;
modal52Low.textContent = stock.low52;
modalLastUpdate.textContent = formatDate(stock.lastUpdate);
modalCompanyDescription.textContent = stock.description;
// Create chart
const ctx = modalStockChart.getContext('2d');
if (modalChart) {
modalChart.destroy();
}
modalChart = new Chart(ctx, {
type: 'line',
data: {
labels: stock.history.map((_, i) => i + 1),
datasets: [{
data: stock.history,
borderColor: isPositive ? '#10b981' : '#ef4444',
backgroundColor: isPositive ? 'rgba(16, 185, 129, 0.1)' : 'rgba(239, 68, 68, 0.1)',
borderWidth: 2,
fill: true,
tension: 0.4,
pointRadius: 0
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
display: false
},
tooltip: {
callbacks: {
label: function(context) {
return `$${context.raw.toFixed(2)}`;
}
}
}
},
scales: {
x: {
grid: {
display: false
}
},
y: {
grid: {
display: true
}
}
}
}
});
// Show modal
stockModal.classList.remove('hidden');
}
// Execute a trade (buy or sell)
function executeTrade(symbol, shares, action) {
// Get current price (from mock data or use a default)
let price = stockPrices[symbol] || 0;
if (price <= 0) {
showToast("Error: Invalid stock price", "error");
return;
}
if (isNaN(shares) || shares < 1) {
showToast("Error: Invalid number of shares", "error");
return;
}
const totalValue = price * shares;
const now = new Date();
if (action === 'buy') {
if (totalValue > virtualPortfolio.balance) {
showToast("Error: Insufficient funds", "error");
return;
}
// Deduct from balance
virtualPortfolio.balance -= totalValue;
// Add to holdings
if (virtualPortfolio.holdings[symbol]) {
// Update existing holding
const holding = virtualPortfolio.holdings[symbol];
const totalShares = holding.shares + shares;
const newAvgPrice = ((holding.avgPrice * holding.shares) + totalValue) / totalShares;
virtualPortfolio.holdings[symbol] = {
shares: totalShares,
avgPrice: newAvgPrice,
lastUpdate: now
};
} else {
// New holding
virtualPortfolio.holdings[symbol] = {
shares: shares,
avgPrice: price,
lastUpdate: now
};
}
showToast(`Bought ${shares} shares of ${symbol} at $${price.toFixed(2)}`, "success");
} else { // sell
if (!virtualPortfolio.holdings[symbol] || virtualPortfolio.holdings[symbol].shares < shares) {
showToast("Error: Not enough shares to sell", "error");
return;
}
// Add to balance
virtualPortfolio.balance += totalValue;
// Update holdings
const holding = virtualPortfolio.holdings[symbol];
const remainingShares = holding.shares - shares;
if (remainingShares > 0) {
virtualPortfolio.holdings[symbol].shares = remainingShares;
virtualPortfolio.holdings[symbol].lastUpdate = now;
} else {
delete virtualPortfolio.holdings[symbol];
}
showToast(`Sold ${shares} shares of ${symbol} at $${price.toFixed(2)}`, "success");
}
// Add to trade history
virtualPortfolio.history.unshift({
date: now,
action: action,
symbol: symbol,
shares: shares,
price: price
});
// Update display
updatePortfolioDisplay();
}
// Update portfolio display
function updatePortfolioDisplay() {
// Format balance
portfolioBalance.textContent = `₪${virtualPortfolio.balance.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`;
// Calculate today's P&L
let holdingsValue = 0;
let totalPnl = 0;
// Update holdings table
holdingsTable.innerHTML = '';
if (Object.keys(virtualPortfolio.holdings).length === 0) {
holdingsTable.innerHTML = `
<tr>
<td colspan="6" class="px-2 py-4 text-center text-gray-500">No holdings yet</td>
</tr>
`;
} else {
Object.keys(virtualPortfolio.holdings).forEach(symbol => {
const holding = virtualPortfolio.holdings[symbol];
const currentPrice = stockPrices[symbol] || holding.avgPrice;
const value = currentPrice * holding.shares;
const pnl = (currentPrice - holding.avgPrice) * holding.shares;
const pnlPercent = ((currentPrice - holding.avgPrice) / holding.avgPrice) * 100;
holdingsValue += value;
totalPnl += pnl;
const isPositive = pnl >= 0;
const pnlClass = isPositive ? 'text-success' : 'text-danger';
const pnlIcon = isPositive ? '▲' : '▼';
const row = document.createElement('tr');
row.className = 'hover:bg-gray-50 cursor-pointer';
row.innerHTML = `
<td class="px-2 py-3 whitespace-nowrap font-medium">${symbol}</td>
<td class="px-2 py-3 whitespace-nowrap">${holding.shares}</td>
<td class="px-2 py-3 whitespace-nowrap">$${holding.avgPrice.toFixed(2)}</td>
<td class="px-2 py-3 whitespace-nowrap">$${value.toFixed(2)}</td>
<td class="px-2 py-3 whitespace-nowrap ${pnlClass}">
${pnlIcon} $${Math.abs(pnl).toFixed(2)} (${isPositive ? '+' : ''}${pnlPercent.toFixed(2)}%)
</td>
<td class="px-2 py-3 whitespace-nowrap text-gray-500 text-sm">${formatDate(holding.lastUpdate)}</td>
`;
row.addEventListener('click', () => openStockModal(symbol));
holdingsTable.appendChild(row);
});
}
// Update history table
historyTable.innerHTML = '';
if (virtualPortfolio.history.length === 0) {
historyTable.innerHTML = `
<tr>
<td colspan="5" class="px-2 py-4 text-center text-gray-500">No trades yet</td>
</tr>
`;
} else {
virtualPortfolio.history.slice(0, 10).forEach(trade => {
const isBuy = trade.action === 'buy';
const actionClass = isBuy ? 'text-success' : 'text-danger';
const actionText = isBuy ? 'Buy' : 'Sell';
const row = document.createElement('tr');
row.className = 'hover:bg-gray-50';
row.innerHTML = `
<td class="px-2 py-3 whitespace-nowrap">${formatDate(trade.date)}</td>
<td class="px-2 py-3 whitespace-nowrap ${actionClass}">${actionText}</td>
<td class="px-2 py-3 whitespace-nowrap font-medium">${trade.symbol}</td>
<td class="px-2 py-3 whitespace-nowrap">${trade.shares}</td>
<td class="px-2 py-3 whitespace-nowrap">$${trade.price.toFixed(2)}</td>
`;
historyTable.appendChild(row);
});
}
// Calculate today's P&L
const totalAssets = virtualPortfolio.balance + holdingsValue;
const todayPnl = totalAssets - virtualPortfolio.todayStartBalance;
const isPositivePnl = todayPnl >= 0;
const pnlClass = isPositivePnl ? 'text-success' : 'text-danger';
const pnlIcon = isPositivePnl ? '▲' : '▼';
portfolioToday.className = `font-bold ${pnlClass}`;
portfolioToday.textContent = `${pnlIcon}${Math.abs(todayPnl).toFixed(2)}`;
}
// Show toast notification
function showToast(message, type = "success") {
toastMessage.textContent = message;
// Set color based on type
if (type === "error") {
tradeToast.className = tradeToast.className.replace('bg-green-500', 'bg-red-500');
} else {
tradeToast.className = tradeToast.className.replace('bg-red-500', 'bg-green-500');
}
// Show toast
tradeToast.classList.remove('translate-y-10', 'opacity-0');
tradeToast.classList.add('translate-y-0', 'opacity-100');
// Hide after 3 seconds
setTimeout(() => {
tradeToast.classList.remove('translate-y-0', 'opacity-100');
tradeToast.classList.add('translate-y-10', 'opacity-0');
}, 3000);
}
// Setup event listeners
function setupEventListeners() {
// Trading panel toggle
tradingToggle.addEventListener('click', () => {
tradingPanel.classList.toggle('open');
tradingArrow.classList.toggle('rotate-180');
});
// Trade action buttons
buyBtn.addEventListener('click', () => {
currentAction = 'buy';
buyBtn.classList.remove('bg-opacity-10', 'border-opacity-30');
buyBtn.classList.add('bg-opacity-20', 'border-opacity-50');
sellBtn.classList.remove('bg-opacity-20', 'border-opacity-50');
sellBtn.classList.add('bg-opacity-10', 'border-opacity-30');
});
sellBtn.addEventListener('click', () => {
currentAction = 'sell';
sellBtn.classList.remove('bg-opacity-10', 'border-opacity-30');
sellBtn.classList.add('bg-opacity-20', 'border-opacity-50');
buyBtn.classList.remove('bg-opacity-20', 'border-opacity-50');
buyBtn.classList.add('bg-opacity-10', 'border-opacity-30');
});
// Execute trade button
executeTradeBtn.addEventListener('click', () => {
const symbol = tradeSymbol.value.trim().toUpperCase();
const shares = parseInt(tradeShares.value);
if (!symbol) {
showToast("Error: Please enter a stock symbol", "error");
return;
}
executeTrade(symbol, shares, currentAction);
});
// Modal trade action buttons
modalBuyBtn.addEventListener('click', () => {
currentAction = 'buy';
modalBuyBtn.classList.remove('bg-opacity-10', 'border-opacity-30');
modalBuyBtn.classList.add('bg-opacity-20', 'border-opacity-50');
modalSellBtn.classList.remove('bg-opacity-20', 'border-opacity-50');
modalSellBtn.classList.add('bg-opacity-10', 'border-opacity-30');
});
modalSellBtn.addEventListener('click', () => {
currentAction = 'sell';
modalSellBtn.classList.remove('bg-opacity-10', 'border-opacity-30');
modalSellBtn.classList.add('bg-opacity-20', 'border-opacity-50');
modalBuyBtn.classList.remove('bg-opacity-20', 'border-opacity-50');
modalBuyBtn.classList.add('bg-opacity-10', 'border-opacity-30');
});
// Modal execute trade button
modalExecuteTradeBtn.addEventListener('click', () => {
const symbol = modalStockSymbol.textContent;
const shares = parseInt(modalTradeShares.value);
executeTrade(symbol, shares, currentAction);
});
// Refresh button
refreshBtn.addEventListener('click', () => {
updateTimeEl.classList.add('blink');
updateTime();
loadIndices();
loadStocks(stockFilter.value);
loadSectors();
loadNews();
});
// Tab buttons
Object.keys(tabButtons).forEach(tab => {
tabButtons[tab].addEventListener('click', () => {
// Remove active class from all tabs
Object.keys(tabButtons).forEach(t => {
tabButtons[t].classList.remove('border-primary', 'text-primary');
tabButtons[t].classList.add('border-transparent', 'text-gray-500');
tabContents[t].classList.add('hidden');
});
// Add active class to clicked tab
tabButtons[tab].classList.add('border-primary', 'text-primary');
tabButtons[tab].classList.remove('border-transparent', 'text-gray-500');
tabContents[tab].classList.remove('hidden');
});
});
// Stock filter
stockFilter.addEventListener('change', (e) => {
loadStocks(e.target.value);
});
// Stock search
searchBtn.addEventListener('click', () => {
const query = stockSearch.value.trim().toUpperCase();
if (query) {
// In a real app, you would search an API here
// For demo, we'll just show a mock result
searchResults.innerHTML = `
<div class="bg-white rounded-lg shadow p-4">
<div class="flex justify-between items-center mb-2">
<h3 class="font-semibold">Search Results for "${query}"</h3>
<button id="close-search" class="text-gray-500 hover:text-gray-700">
<i class="fas fa-times"></i>
</button>
</div>
<div class="space-y-2">
<div class="p-2 hover:bg-gray-50 rounded cursor-pointer flex justify-between items-center" onclick="openStockModal('${query}')">
<div>
<span class="font-medium">${query}</span>
<span class="text-gray-500 text-sm ml-2">${query} Company Inc.</span>
</div>
<span class="text-primary">View Details</span>
</div>
<div class="text-sm text-gray-500 p-2">
Note: This is a demo. In a real application, you would see actual search results from a financial API.
</div>
</div>
</div>
`;
searchResults.classList.remove('hidden');
document.getElementById('close-search').addEventListener('click', () => {
searchResults.classList.add('hidden');
});
}
});
// Close modal
closeModalBtn.addEventListener('click', () => {
stockModal.classList.add('hidden');
});
// Close modal when clicking outside
stockModal.addEventListener('click', (e) => {
if (e.target === stockModal) {
stockModal.classList.add('hidden');
}
});
}
// Make openStockModal available globally for search results
window.openStockModal = openStockModal;
// Initialize the app when the DOM is loaded
document.addEventListener('DOMContentLoaded', init);
</script>
<p style="border-radius: 8px; text-align: center; font-size: 12px; color: #fff; margin-top: 16px;position: fixed; left: 8px; bottom: 8px; z-index: 10; background: rgba(0, 0, 0, 0.8); padding: 4px 8px;">Made with <img src="https://enzostvs-deepsite.hf.space/logo.svg" alt="DeepSite Logo" style="width: 16px; height: 16px; vertical-align: middle;display:inline-block;margin-right:3px;filter:brightness(0) invert(1);"><a href="https://enzostvs-deepsite.hf.space" style="color: #fff;text-decoration: underline;" target="_blank" >DeepSite</a> - 🧬 <a href="https://enzostvs-deepsite.hf.space?remix=ARIELKA/ariel" style="color: #fff;text-decoration: underline;" target="_blank" >Remix</a></p></body>
</html>