๐ Trade Tracker
Stock Symbol
Buy Price
Target Price
Stop Loss
Quantity
No active trades
Add a trade above to start tracking
Updating prices…
// Trade storage
let trades = JSON.parse(localStorage.getItem(‘trades’)) || [];
// API Configuration – Using Yahoo Finance via a CORS proxy
// For production, you’d want your own backend or a paid API
const API_BASE = ‘[query1.finance.yahoo.com](https://query1.finance.yahoo.com/v8/finance/chart/)’;
// Alternative free APIs to try:
// 1. Alpha Vantage (needs free API key): [alphavantage.co](https://www.alphavantage.co/)
// 2. Finnhub (needs free API key): [finnhub.io](https://finnhub.io/)
// DOM Elements
const tradeForm = document.getElementById(‘tradeForm’);
const tradesContainer = document.getElementById(‘tradesContainer’);
const refreshIndicator = document.getElementById(‘refreshIndicator’);
const errorMsg = document.getElementById(‘errorMsg’);
// Initialize
document.addEventListener(‘DOMContentLoaded’, () => {
renderTrades();
if (trades.length > 0) {
updateAllPrices();
}
// Auto-refresh every 30 seconds
setInterval(updateAllPrices, 30000);
});
// Add new trade
tradeForm.addEventListener(‘submit’, async (e) => {
e.preventDefault();
const symbol = document.getElementById(‘symbol’).value.toUpperCase().trim();
const buyPrice = parseFloat(document.getElementById(‘buyPrice’).value);
const target = parseFloat(document.getElementById(‘target’).value);
const stopLoss = parseFloat(document.getElementById(‘stopLoss’).value);
const quantity = parseInt(document.getElementById(‘quantity’).value);
// Validation
if (target = buyPrice) {
showError(‘Stop loss must be lower than buy price’);
return;
}
const trade = {
id: Date.now(),
symbol,
buyPrice,
target,
stopLoss,
quantity,
currentPrice: null,
status: ‘active’,
createdAt: new Date().toISOString(),
lastUpdated: null
};
// Try to fetch initial price
showRefreshIndicator(true);
const price = await fetchStockPrice(symbol);
showRefreshIndicator(false);
if (price) {
trade.currentPrice = price;
trade.lastUpdated = new Date().toISOString();
trade.status = getTradeStatus(trade);
}
trades.push(trade);
saveTrades();
renderTrades();
tradeForm.reset();
document.getElementById(‘quantity’).value = 1;
hideError();
});
// Fetch stock price
async function fetchStockPrice(symbol) {
try {
// Using a CORS proxy for Yahoo Finance
// In production, use your own backend
const corsProxy = ‘[corsproxy.io](https://corsproxy.io/)’;
const url = `${corsProxy}${encodeURIComponent(API_BASE + symbol)}`;
const response = await fetch(url);
const data = await response.json();
if (data.chart?.result?.[0]?.meta?.regularMarketPrice) {
return data.chart.result[0].meta.regularMarketPrice;
}
// Fallback: try without .NS suffix for Indian stocks
if (!symbol.includes(‘.’)) {
const indianSymbol = symbol + ‘.NS’;
const indiaUrl = `${corsProxy}${encodeURIComponent(API_BASE + indianSymbol)}`;
const indiaResponse = await fetch(indiaUrl);
const indiaData = await indiaResponse.json();
if (indiaData.chart?.result?.[0]?.meta?.regularMarketPrice) {
// Update the trade symbol to include .NS
return indiaData.chart.result[0].meta.regularMarketPrice;
}
}
return null;
} catch (error) {
console.error(`Error fetching price for ${symbol}:`, error);
return null;
}
}
// Update all prices
async function updateAllPrices() {
if (trades.length === 0) return;
showRefreshIndicator(true);
for (const trade of trades) {
if (trade.status === ‘active’) {
const price = await fetchStockPrice(trade.symbol);
if (price) {
trade.currentPrice = price;
trade.lastUpdated = new Date().toISOString();
trade.status = getTradeStatus(trade);
}
}
}
saveTrades();
renderTrades();
showRefreshIndicator(false);
}
// Get trade status
function getTradeStatus(trade) {
if (!trade.currentPrice) return ‘active’;
if (trade.currentPrice >= trade.target) return ‘target-hit’;
if (trade.currentPrice <= trade.stopLoss) return 'sl-hit';
return 'active';
}
// Calculate P&L
function calculatePnL(trade) {
if (!trade.currentPrice) return { amount: 0, percentage: 0 };
const amount = (trade.currentPrice – trade.buyPrice) * trade.quantity;
const percentage = ((trade.currentPrice – trade.buyPrice) / trade.buyPrice) * 100;
return { amount, percentage };
}
// Render trades
function renderTrades() {
if (trades.length === 0) {
tradesContainer.innerHTML = `
No active trades
Add a trade above to start tracking
${trade.symbol}
${statusText}
Buy Price
โน${trade.buyPrice.toFixed(2)}
Current Price
${trade.currentPrice ? ‘โน’ + trade.currentPrice.toFixed(2) : ‘Loading…’}
Target
โน${trade.target.toFixed(2)}
Stop Loss
โน${trade.stopLoss.toFixed(2)}
Quantity
${trade.quantity}
P&L
${isProfit ? ‘+’ : ”}โน${pnl.amount.toFixed(2)}
(${isProfit ? ‘+’ : ”}${pnl.percentage.toFixed(2)}%)
(${isProfit ? ‘+’ : ”}${pnl.percentage.toFixed(2)}%)
