Spaces:
Sleeping
Sleeping
Update app.js
Browse files
app.js
CHANGED
|
@@ -2,15 +2,14 @@
|
|
| 2 |
// WALLET FUNCTIONS
|
| 3 |
// ============================================================================
|
| 4 |
|
| 5 |
-
let walletBalance =
|
| 6 |
|
| 7 |
function showWallet() {
|
| 8 |
document.getElementById("walletPanel").classList.remove("hidden");
|
| 9 |
document.getElementById("walletActionArea").innerHTML = "";
|
| 10 |
document.getElementById("walletMessage").classList.add("hidden");
|
| 11 |
-
|
| 12 |
-
// Load current wallet balance from backend
|
| 13 |
loadWalletBalance();
|
|
|
|
| 14 |
}
|
| 15 |
|
| 16 |
function closeWallet() {
|
|
@@ -21,21 +20,45 @@ async function loadWalletBalance() {
|
|
| 21 |
try {
|
| 22 |
const res = await fetch(`${API}/api/wallet/balance`);
|
| 23 |
const data = await res.json();
|
| 24 |
-
|
| 25 |
if (data.balance !== undefined) {
|
| 26 |
walletBalance = data.balance;
|
| 27 |
document.getElementById("walletBalance").textContent = "βΉ" + formatNumber(walletBalance);
|
| 28 |
-
//
|
| 29 |
const portBalanceEl = document.getElementById("portBalance");
|
| 30 |
if (portBalanceEl) portBalanceEl.textContent = "βΉ" + formatNumber(walletBalance);
|
| 31 |
}
|
| 32 |
} catch (e) {
|
| 33 |
console.error("Error loading wallet balance:", e);
|
| 34 |
-
// Fallback to local balance
|
| 35 |
document.getElementById("walletBalance").textContent = "βΉ" + formatNumber(walletBalance);
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
}
|
| 40 |
}
|
| 41 |
|
|
@@ -43,8 +66,8 @@ function showAddMoney() {
|
|
| 43 |
document.getElementById("walletActionArea").innerHTML = `
|
| 44 |
<div class='wallet-form'>
|
| 45 |
<h3>Add Money</h3>
|
| 46 |
-
<input type='number' id='addAmount' placeholder='Enter amount' min='1' />
|
| 47 |
-
<button onclick='startRazorpayPayment()'>
|
| 48 |
</div>
|
| 49 |
`;
|
| 50 |
document.getElementById("walletMessage").classList.add("hidden");
|
|
@@ -54,8 +77,8 @@ function showWithdrawMoney() {
|
|
| 54 |
document.getElementById("walletActionArea").innerHTML = `
|
| 55 |
<div class='wallet-form'>
|
| 56 |
<h3>Withdraw Money</h3>
|
| 57 |
-
<input type='number' id='withdrawAmount' placeholder='Enter amount' min='1' />
|
| 58 |
-
<button onclick='startWithdraw()'>Withdraw</button>
|
| 59 |
</div>
|
| 60 |
`;
|
| 61 |
document.getElementById("walletMessage").classList.add("hidden");
|
|
@@ -66,11 +89,17 @@ function showWalletMessage(message, type = 'success') {
|
|
| 66 |
msgEl.textContent = message;
|
| 67 |
msgEl.className = `wallet-message ${type}`;
|
| 68 |
msgEl.classList.remove("hidden");
|
| 69 |
-
|
| 70 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
setTimeout(() => {
|
| 72 |
-
|
| 73 |
-
|
|
|
|
|
|
|
| 74 |
}
|
| 75 |
|
| 76 |
// Razorpay integration
|
|
@@ -83,31 +112,29 @@ function startRazorpayPayment() {
|
|
| 83 |
|
| 84 |
const amountInPaise = Math.round(parseFloat(amt) * 100);
|
| 85 |
|
| 86 |
-
// Create Razorpay order
|
| 87 |
const options = {
|
| 88 |
-
key: 'rzp_test_SDdi0bRwia1AA4',
|
| 89 |
amount: amountInPaise,
|
| 90 |
currency: 'INR',
|
| 91 |
name: 'StockSense Wallet',
|
| 92 |
description: 'Add Money to Wallet',
|
| 93 |
handler: function (response) {
|
| 94 |
-
// Payment successful - verify and credit wallet
|
| 95 |
verifyAndCreditWallet(response.razorpay_payment_id, parseFloat(amt));
|
| 96 |
},
|
| 97 |
prefill: {
|
| 98 |
name: 'User',
|
| 99 |
email: 'user@example.com'
|
| 100 |
},
|
| 101 |
-
theme: {
|
| 102 |
-
color: '#22c55e'
|
| 103 |
},
|
| 104 |
modal: {
|
| 105 |
-
ondismiss: function() {
|
| 106 |
showWalletMessage('Payment cancelled', 'error');
|
| 107 |
}
|
| 108 |
}
|
| 109 |
};
|
| 110 |
-
|
| 111 |
try {
|
| 112 |
const rzp = new Razorpay(options);
|
| 113 |
rzp.open();
|
|
@@ -119,35 +146,29 @@ function startRazorpayPayment() {
|
|
| 119 |
|
| 120 |
async function verifyAndCreditWallet(paymentId, amount) {
|
| 121 |
try {
|
| 122 |
-
// Call backend to verify payment and credit wallet
|
| 123 |
const res = await fetch(`${API}/api/wallet/add`, {
|
| 124 |
method: 'POST',
|
| 125 |
-
headers: {
|
| 126 |
-
|
| 127 |
-
},
|
| 128 |
-
body: JSON.stringify({
|
| 129 |
-
payment_id: paymentId,
|
| 130 |
-
amount: amount
|
| 131 |
-
})
|
| 132 |
});
|
| 133 |
|
| 134 |
const data = await res.json();
|
| 135 |
|
| 136 |
-
if (data.status === 'success') {
|
| 137 |
walletBalance = data.new_balance;
|
| 138 |
document.getElementById("walletBalance").textContent = "βΉ" + formatNumber(walletBalance);
|
| 139 |
-
|
|
|
|
|
|
|
|
|
|
| 140 |
document.getElementById("walletActionArea").innerHTML = "";
|
|
|
|
| 141 |
} else {
|
| 142 |
-
showWalletMessage('Payment verification failed.
|
| 143 |
}
|
| 144 |
} catch (e) {
|
| 145 |
console.error("Wallet credit error:", e);
|
| 146 |
-
|
| 147 |
-
walletBalance += amount;
|
| 148 |
-
document.getElementById("walletBalance").textContent = "βΉ" + formatNumber(walletBalance);
|
| 149 |
-
showWalletMessage(`β
βΉ${formatNumber(amount)} added successfully! Payment ID: ${paymentId}`, 'success');
|
| 150 |
-
document.getElementById("walletActionArea").innerHTML = "";
|
| 151 |
}
|
| 152 |
}
|
| 153 |
|
|
@@ -160,49 +181,43 @@ async function startWithdraw() {
|
|
| 160 |
|
| 161 |
const withdrawAmount = parseFloat(amt);
|
| 162 |
|
| 163 |
-
// Check if sufficient balance
|
| 164 |
if (withdrawAmount > walletBalance) {
|
| 165 |
showWalletMessage('Insufficient balance', 'error');
|
| 166 |
return;
|
| 167 |
}
|
| 168 |
|
| 169 |
-
// Confirm withdrawal
|
| 170 |
if (!confirm(`Withdraw βΉ${formatNumber(withdrawAmount)} from your wallet?`)) {
|
| 171 |
return;
|
| 172 |
}
|
| 173 |
|
| 174 |
try {
|
| 175 |
-
// Call backend to process withdrawal
|
| 176 |
const res = await fetch(`${API}/api/wallet/withdraw`, {
|
| 177 |
method: 'POST',
|
| 178 |
-
headers: {
|
| 179 |
-
|
| 180 |
-
},
|
| 181 |
-
body: JSON.stringify({
|
| 182 |
-
amount: withdrawAmount
|
| 183 |
-
})
|
| 184 |
});
|
| 185 |
|
| 186 |
const data = await res.json();
|
| 187 |
|
| 188 |
-
if (data.status === 'success') {
|
| 189 |
walletBalance = data.new_balance;
|
| 190 |
document.getElementById("walletBalance").textContent = "βΉ" + formatNumber(walletBalance);
|
|
|
|
|
|
|
|
|
|
| 191 |
showWalletMessage(`β
βΉ${formatNumber(withdrawAmount)} withdrawn successfully!`, 'success');
|
| 192 |
document.getElementById("walletActionArea").innerHTML = "";
|
|
|
|
| 193 |
} else {
|
| 194 |
-
showWalletMessage(data.
|
| 195 |
}
|
| 196 |
} catch (e) {
|
| 197 |
console.error("Withdrawal error:", e);
|
| 198 |
-
|
| 199 |
-
walletBalance -= withdrawAmount;
|
| 200 |
-
document.getElementById("walletBalance").textContent = "βΉ" + formatNumber(walletBalance);
|
| 201 |
-
showWalletMessage(`β
βΉ${formatNumber(withdrawAmount)} withdrawn successfully!`, 'success');
|
| 202 |
-
document.getElementById("walletActionArea").innerHTML = "";
|
| 203 |
}
|
| 204 |
}
|
| 205 |
|
|
|
|
| 206 |
// ============================================================================
|
| 207 |
// MAIN APP CODE
|
| 208 |
// ============================================================================
|
|
@@ -1040,3 +1055,667 @@ function formatVolume(v) {
|
|
| 1040 |
function formatNumber(n) {
|
| 1041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|
|
| 5 |
+
let walletBalance = 1000000.00; // Initial wallet balance (synced with backend)
|
| 6 |
|
| 7 |
function showWallet() {
|
| 8 |
document.getElementById("walletPanel").classList.remove("hidden");
|
| 9 |
document.getElementById("walletActionArea").innerHTML = "";
|
| 10 |
document.getElementById("walletMessage").classList.add("hidden");
|
|
|
|
|
|
|
| 11 |
loadWalletBalance();
|
| 12 |
+
loadWalletTransactions();
|
| 13 |
}
|
| 14 |
|
| 15 |
function closeWallet() {
|
|
|
|
| 20 |
try {
|
| 21 |
const res = await fetch(`${API}/api/wallet/balance`);
|
| 22 |
const data = await res.json();
|
|
|
|
| 23 |
if (data.balance !== undefined) {
|
| 24 |
walletBalance = data.balance;
|
| 25 |
document.getElementById("walletBalance").textContent = "βΉ" + formatNumber(walletBalance);
|
| 26 |
+
// Sync portfolio cash balance display
|
| 27 |
const portBalanceEl = document.getElementById("portBalance");
|
| 28 |
if (portBalanceEl) portBalanceEl.textContent = "βΉ" + formatNumber(walletBalance);
|
| 29 |
}
|
| 30 |
} catch (e) {
|
| 31 |
console.error("Error loading wallet balance:", e);
|
|
|
|
| 32 |
document.getElementById("walletBalance").textContent = "βΉ" + formatNumber(walletBalance);
|
| 33 |
+
}
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
async function loadWalletTransactions() {
|
| 37 |
+
try {
|
| 38 |
+
const res = await fetch(`${API}/api/wallet/transactions`);
|
| 39 |
+
const data = await res.json();
|
| 40 |
+
const list = document.getElementById("walletTxnList");
|
| 41 |
+
if (!data.transactions || data.transactions.length === 0) {
|
| 42 |
+
list.innerHTML = '<div class="wallet-txn-empty">No transactions yet</div>';
|
| 43 |
+
return;
|
| 44 |
+
}
|
| 45 |
+
list.innerHTML = data.transactions.slice(-10).reverse().map(txn => {
|
| 46 |
+
const date = new Date(txn.timestamp);
|
| 47 |
+
const dateStr = date.toLocaleDateString('en-IN', { day: '2-digit', month: 'short', year: '2-digit' }) + ' ' +
|
| 48 |
+
date.toLocaleTimeString('en-IN', { hour: '2-digit', minute: '2-digit' });
|
| 49 |
+
const sign = txn.type === 'credit' ? '+' : '-';
|
| 50 |
+
return `
|
| 51 |
+
<div class="wallet-txn-item">
|
| 52 |
+
<div class="wallet-txn-left">
|
| 53 |
+
<span class="wallet-txn-type ${txn.type}">${txn.type === 'credit' ? 'β Deposit' : 'β Withdrawal'}</span>
|
| 54 |
+
<span class="wallet-txn-date">${dateStr}</span>
|
| 55 |
+
</div>
|
| 56 |
+
<span class="wallet-txn-amount" style="color: ${txn.type === 'credit' ? '#22c55e' : '#ef4444'}">${sign}βΉ${formatNumber(txn.amount)}</span>
|
| 57 |
+
</div>
|
| 58 |
+
`;
|
| 59 |
+
}).join("");
|
| 60 |
+
} catch (e) {
|
| 61 |
+
console.error("Error loading transactions:", e);
|
| 62 |
}
|
| 63 |
}
|
| 64 |
|
|
|
|
| 66 |
document.getElementById("walletActionArea").innerHTML = `
|
| 67 |
<div class='wallet-form'>
|
| 68 |
<h3>Add Money</h3>
|
| 69 |
+
<input type='number' id='addAmount' placeholder='Enter amount (βΉ)' min='1' />
|
| 70 |
+
<button onclick='startRazorpayPayment()'>Pay with Razorpay</button>
|
| 71 |
</div>
|
| 72 |
`;
|
| 73 |
document.getElementById("walletMessage").classList.add("hidden");
|
|
|
|
| 77 |
document.getElementById("walletActionArea").innerHTML = `
|
| 78 |
<div class='wallet-form'>
|
| 79 |
<h3>Withdraw Money</h3>
|
| 80 |
+
<input type='number' id='withdrawAmount' placeholder='Enter amount (βΉ)' min='1' />
|
| 81 |
+
<button onclick='startWithdraw()'>Withdraw to Bank</button>
|
| 82 |
</div>
|
| 83 |
`;
|
| 84 |
document.getElementById("walletMessage").classList.add("hidden");
|
|
|
|
| 89 |
msgEl.textContent = message;
|
| 90 |
msgEl.className = `wallet-message ${type}`;
|
| 91 |
msgEl.classList.remove("hidden");
|
| 92 |
+
setTimeout(() => { msgEl.classList.add("hidden"); }, 5000);
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
function quickAdd(amount) {
|
| 96 |
+
// Pre-fill the add money form and trigger Razorpay
|
| 97 |
+
showAddMoney();
|
| 98 |
setTimeout(() => {
|
| 99 |
+
const input = document.getElementById('addAmount');
|
| 100 |
+
if (input) input.value = amount;
|
| 101 |
+
startRazorpayPayment();
|
| 102 |
+
}, 100);
|
| 103 |
}
|
| 104 |
|
| 105 |
// Razorpay integration
|
|
|
|
| 112 |
|
| 113 |
const amountInPaise = Math.round(parseFloat(amt) * 100);
|
| 114 |
|
|
|
|
| 115 |
const options = {
|
| 116 |
+
key: 'rzp_test_SDdi0bRwia1AA4',
|
| 117 |
amount: amountInPaise,
|
| 118 |
currency: 'INR',
|
| 119 |
name: 'StockSense Wallet',
|
| 120 |
description: 'Add Money to Wallet',
|
| 121 |
handler: function (response) {
|
|
|
|
| 122 |
verifyAndCreditWallet(response.razorpay_payment_id, parseFloat(amt));
|
| 123 |
},
|
| 124 |
prefill: {
|
| 125 |
name: 'User',
|
| 126 |
email: 'user@example.com'
|
| 127 |
},
|
| 128 |
+
theme: {
|
| 129 |
+
color: '#22c55e'
|
| 130 |
},
|
| 131 |
modal: {
|
| 132 |
+
ondismiss: function () {
|
| 133 |
showWalletMessage('Payment cancelled', 'error');
|
| 134 |
}
|
| 135 |
}
|
| 136 |
};
|
| 137 |
+
|
| 138 |
try {
|
| 139 |
const rzp = new Razorpay(options);
|
| 140 |
rzp.open();
|
|
|
|
| 146 |
|
| 147 |
async function verifyAndCreditWallet(paymentId, amount) {
|
| 148 |
try {
|
|
|
|
| 149 |
const res = await fetch(`${API}/api/wallet/add`, {
|
| 150 |
method: 'POST',
|
| 151 |
+
headers: { 'Content-Type': 'application/json' },
|
| 152 |
+
body: JSON.stringify({ payment_id: paymentId, amount: amount })
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
});
|
| 154 |
|
| 155 |
const data = await res.json();
|
| 156 |
|
| 157 |
+
if (res.ok && data.status === 'success') {
|
| 158 |
walletBalance = data.new_balance;
|
| 159 |
document.getElementById("walletBalance").textContent = "βΉ" + formatNumber(walletBalance);
|
| 160 |
+
// Sync portfolio cash balance
|
| 161 |
+
const portBalanceEl = document.getElementById("portBalance");
|
| 162 |
+
if (portBalanceEl) portBalanceEl.textContent = "βΉ" + formatNumber(walletBalance);
|
| 163 |
+
showWalletMessage(`β
βΉ${formatNumber(amount)} added successfully!`, 'success');
|
| 164 |
document.getElementById("walletActionArea").innerHTML = "";
|
| 165 |
+
loadWalletTransactions();
|
| 166 |
} else {
|
| 167 |
+
showWalletMessage(data.detail || 'Payment verification failed. Contact support.', 'error');
|
| 168 |
}
|
| 169 |
} catch (e) {
|
| 170 |
console.error("Wallet credit error:", e);
|
| 171 |
+
showWalletMessage('Network error. Please check your connection and try again.', 'error');
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
}
|
| 173 |
}
|
| 174 |
|
|
|
|
| 181 |
|
| 182 |
const withdrawAmount = parseFloat(amt);
|
| 183 |
|
|
|
|
| 184 |
if (withdrawAmount > walletBalance) {
|
| 185 |
showWalletMessage('Insufficient balance', 'error');
|
| 186 |
return;
|
| 187 |
}
|
| 188 |
|
|
|
|
| 189 |
if (!confirm(`Withdraw βΉ${formatNumber(withdrawAmount)} from your wallet?`)) {
|
| 190 |
return;
|
| 191 |
}
|
| 192 |
|
| 193 |
try {
|
|
|
|
| 194 |
const res = await fetch(`${API}/api/wallet/withdraw`, {
|
| 195 |
method: 'POST',
|
| 196 |
+
headers: { 'Content-Type': 'application/json' },
|
| 197 |
+
body: JSON.stringify({ amount: withdrawAmount })
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
});
|
| 199 |
|
| 200 |
const data = await res.json();
|
| 201 |
|
| 202 |
+
if (res.ok && data.status === 'success') {
|
| 203 |
walletBalance = data.new_balance;
|
| 204 |
document.getElementById("walletBalance").textContent = "βΉ" + formatNumber(walletBalance);
|
| 205 |
+
// Sync portfolio cash balance
|
| 206 |
+
const portBalanceEl = document.getElementById("portBalance");
|
| 207 |
+
if (portBalanceEl) portBalanceEl.textContent = "βΉ" + formatNumber(walletBalance);
|
| 208 |
showWalletMessage(`β
βΉ${formatNumber(withdrawAmount)} withdrawn successfully!`, 'success');
|
| 209 |
document.getElementById("walletActionArea").innerHTML = "";
|
| 210 |
+
loadWalletTransactions();
|
| 211 |
} else {
|
| 212 |
+
showWalletMessage(data.detail || 'Withdrawal failed', 'error');
|
| 213 |
}
|
| 214 |
} catch (e) {
|
| 215 |
console.error("Withdrawal error:", e);
|
| 216 |
+
showWalletMessage('Network error. Please check your connection and try again.', 'error');
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
}
|
| 218 |
}
|
| 219 |
|
| 220 |
+
|
| 221 |
// ============================================================================
|
| 222 |
// MAIN APP CODE
|
| 223 |
// ============================================================================
|
|
|
|
| 1055 |
function formatNumber(n) {
|
| 1056 |
return parseFloat(n).toLocaleString("en-IN", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
| 1057 |
}
|
| 1058 |
+
|
| 1059 |
+
|
| 1060 |
+
// ============================================================================
|
| 1061 |
+
// TRADE PANEL
|
| 1062 |
+
// ============================================================================
|
| 1063 |
+
|
| 1064 |
+
let tradePanelTicker = "";
|
| 1065 |
+
let tradePanelPrice = 0;
|
| 1066 |
+
let tradePanelAction = "buy"; // "buy" or "sell"
|
| 1067 |
+
let tradePanelInterval = null;
|
| 1068 |
+
let accountValueChart = null;
|
| 1069 |
+
let watchlistRefreshInterval = null;
|
| 1070 |
+
|
| 1071 |
+
function openTradePanel(ticker) {
|
| 1072 |
+
const panel = document.getElementById("tradePanel");
|
| 1073 |
+
panel.classList.remove("hidden");
|
| 1074 |
+
document.body.style.overflow = "hidden";
|
| 1075 |
+
|
| 1076 |
+
// Set up trade search
|
| 1077 |
+
const searchInput = document.getElementById("tradeSearchInput");
|
| 1078 |
+
searchInput.value = "";
|
| 1079 |
+
document.getElementById("tradeSearchDropdown").classList.add("hidden");
|
| 1080 |
+
|
| 1081 |
+
// Update market badge
|
| 1082 |
+
updateTradePanelMarketBadge();
|
| 1083 |
+
|
| 1084 |
+
// Update wallet balance in summary
|
| 1085 |
+
document.getElementById("tpSummaryBalance").textContent = "βΉ" + formatNumber(walletBalance);
|
| 1086 |
+
|
| 1087 |
+
if (ticker) {
|
| 1088 |
+
selectTradeStock(ticker);
|
| 1089 |
+
searchInput.value = ticker;
|
| 1090 |
+
} else {
|
| 1091 |
+
document.getElementById("tpStockCard").classList.add("hidden");
|
| 1092 |
+
}
|
| 1093 |
+
|
| 1094 |
+
// Setup search listeners
|
| 1095 |
+
setupTradePanelSearch();
|
| 1096 |
+
|
| 1097 |
+
// Load holdings, history, watchlist
|
| 1098 |
+
loadTradeHoldings();
|
| 1099 |
+
loadTradeHistory();
|
| 1100 |
+
renderWatchlist();
|
| 1101 |
+
|
| 1102 |
+
// Start watchlist price refresh
|
| 1103 |
+
if (watchlistRefreshInterval) clearInterval(watchlistRefreshInterval);
|
| 1104 |
+
watchlistRefreshInterval = setInterval(refreshWatchlistPrices, 15000);
|
| 1105 |
+
}
|
| 1106 |
+
|
| 1107 |
+
function closeTradePanel() {
|
| 1108 |
+
document.getElementById("tradePanel").classList.add("hidden");
|
| 1109 |
+
document.body.style.overflow = "";
|
| 1110 |
+
if (tradePanelInterval) {
|
| 1111 |
+
clearInterval(tradePanelInterval);
|
| 1112 |
+
tradePanelInterval = null;
|
| 1113 |
+
}
|
| 1114 |
+
if (watchlistRefreshInterval) {
|
| 1115 |
+
clearInterval(watchlistRefreshInterval);
|
| 1116 |
+
watchlistRefreshInterval = null;
|
| 1117 |
+
}
|
| 1118 |
+
}
|
| 1119 |
+
|
| 1120 |
+
function switchTradeTab(tab) {
|
| 1121 |
+
document.querySelectorAll(".tp-tab").forEach(t => t.classList.remove("active"));
|
| 1122 |
+
document.querySelector(`.tp-tab[data-tab="${tab}"]`).classList.add("active");
|
| 1123 |
+
|
| 1124 |
+
document.querySelectorAll(".tp-tab-content").forEach(c => c.classList.add("hidden"));
|
| 1125 |
+
|
| 1126 |
+
if (tab === "search") {
|
| 1127 |
+
document.getElementById("tpSearchTab").classList.remove("hidden");
|
| 1128 |
+
} else if (tab === "holdings") {
|
| 1129 |
+
document.getElementById("tpHoldingsTab").classList.remove("hidden");
|
| 1130 |
+
loadTradeHoldings();
|
| 1131 |
+
} else if (tab === "history") {
|
| 1132 |
+
document.getElementById("tpHistoryTab").classList.remove("hidden");
|
| 1133 |
+
loadTradeHistory();
|
| 1134 |
+
} else if (tab === "watchlist") {
|
| 1135 |
+
document.getElementById("tpWatchlistTab").classList.remove("hidden");
|
| 1136 |
+
renderWatchlist();
|
| 1137 |
+
refreshWatchlistPrices();
|
| 1138 |
+
}
|
| 1139 |
+
}
|
| 1140 |
+
|
| 1141 |
+
let tradeSearchTimeout = null;
|
| 1142 |
+
function setupTradePanelSearch() {
|
| 1143 |
+
const input = document.getElementById("tradeSearchInput");
|
| 1144 |
+
const dropdown = document.getElementById("tradeSearchDropdown");
|
| 1145 |
+
|
| 1146 |
+
// Remove old listeners by cloning
|
| 1147 |
+
const newInput = input.cloneNode(true);
|
| 1148 |
+
input.parentNode.replaceChild(newInput, input);
|
| 1149 |
+
|
| 1150 |
+
newInput.addEventListener("input", () => {
|
| 1151 |
+
clearTimeout(tradeSearchTimeout);
|
| 1152 |
+
const q = newInput.value.trim();
|
| 1153 |
+
if (q.length < 1) {
|
| 1154 |
+
dropdown.classList.add("hidden");
|
| 1155 |
+
return;
|
| 1156 |
+
}
|
| 1157 |
+
tradeSearchTimeout = setTimeout(() => tradeSearchStocks(q), 250);
|
| 1158 |
+
});
|
| 1159 |
+
|
| 1160 |
+
newInput.addEventListener("keydown", (e) => {
|
| 1161 |
+
if (e.key === "Escape") dropdown.classList.add("hidden");
|
| 1162 |
+
});
|
| 1163 |
+
}
|
| 1164 |
+
|
| 1165 |
+
async function tradeSearchStocks(query) {
|
| 1166 |
+
const dropdown = document.getElementById("tradeSearchDropdown");
|
| 1167 |
+
try {
|
| 1168 |
+
const res = await fetch(`${API}/api/search?q=${encodeURIComponent(query)}`);
|
| 1169 |
+
const data = await res.json();
|
| 1170 |
+
|
| 1171 |
+
if (!data.results || data.results.length === 0) {
|
| 1172 |
+
dropdown.innerHTML = '<div class="tp-search-no-results">No stocks found</div>';
|
| 1173 |
+
dropdown.classList.remove("hidden");
|
| 1174 |
+
return;
|
| 1175 |
+
}
|
| 1176 |
+
|
| 1177 |
+
dropdown.innerHTML = data.results.map(s => `
|
| 1178 |
+
<div class="tp-search-item" data-ticker="${s.ticker}" data-name="${s.name}">
|
| 1179 |
+
<span class="tp-search-ticker">${s.ticker}</span>
|
| 1180 |
+
<span class="tp-search-name">${s.name}</span>
|
| 1181 |
+
</div>
|
| 1182 |
+
`).join("");
|
| 1183 |
+
|
| 1184 |
+
dropdown.querySelectorAll(".tp-search-item").forEach(item => {
|
| 1185 |
+
item.addEventListener("click", () => {
|
| 1186 |
+
const ticker = item.dataset.ticker;
|
| 1187 |
+
document.getElementById("tradeSearchInput").value = ticker;
|
| 1188 |
+
dropdown.classList.add("hidden");
|
| 1189 |
+
selectTradeStock(ticker);
|
| 1190 |
+
});
|
| 1191 |
+
});
|
| 1192 |
+
|
| 1193 |
+
dropdown.classList.remove("hidden");
|
| 1194 |
+
} catch (e) {
|
| 1195 |
+
console.error("Trade search error:", e);
|
| 1196 |
+
dropdown.classList.add("hidden");
|
| 1197 |
+
}
|
| 1198 |
+
}
|
| 1199 |
+
|
| 1200 |
+
async function selectTradeStock(ticker) {
|
| 1201 |
+
tradePanelTicker = ticker;
|
| 1202 |
+
const card = document.getElementById("tpStockCard");
|
| 1203 |
+
card.classList.remove("hidden");
|
| 1204 |
+
|
| 1205 |
+
document.getElementById("tpStockTicker").textContent = ticker;
|
| 1206 |
+
document.getElementById("tpStockName").textContent = ticker;
|
| 1207 |
+
document.getElementById("tpStockPrice").textContent = "Loading...";
|
| 1208 |
+
document.getElementById("tpStockChange").textContent = "";
|
| 1209 |
+
|
| 1210 |
+
// Check if in watchlist
|
| 1211 |
+
updateWatchlistButton(ticker);
|
| 1212 |
+
|
| 1213 |
+
// Fetch live price
|
| 1214 |
+
await updateTradePanelPrice(ticker);
|
| 1215 |
+
|
| 1216 |
+
// Auto-refresh price every 10s
|
| 1217 |
+
if (tradePanelInterval) clearInterval(tradePanelInterval);
|
| 1218 |
+
tradePanelInterval = setInterval(() => updateTradePanelPrice(ticker), 10000);
|
| 1219 |
+
|
| 1220 |
+
// Also fetch stock info for name
|
| 1221 |
+
try {
|
| 1222 |
+
const infoRes = await fetch(`${API}/api/stock/${ticker}`);
|
| 1223 |
+
const infoData = await infoRes.json();
|
| 1224 |
+
if (infoData.info && infoData.info.name) {
|
| 1225 |
+
document.getElementById("tpStockName").textContent = infoData.info.name;
|
| 1226 |
+
}
|
| 1227 |
+
} catch (e) { /* ignore */ }
|
| 1228 |
+
|
| 1229 |
+
// Check if position exists to default to sell
|
| 1230 |
+
try {
|
| 1231 |
+
const portRes = await fetch(`${API}/api/trade/portfolio`);
|
| 1232 |
+
const portData = await portRes.json();
|
| 1233 |
+
if (portData.positions && portData.positions[ticker]) {
|
| 1234 |
+
setTradeAction("sell");
|
| 1235 |
+
} else {
|
| 1236 |
+
setTradeAction("buy");
|
| 1237 |
+
}
|
| 1238 |
+
} catch (e) { /* ignore */ }
|
| 1239 |
+
}
|
| 1240 |
+
|
| 1241 |
+
async function updateTradePanelPrice(ticker) {
|
| 1242 |
+
try {
|
| 1243 |
+
const res = await fetch(`${API}/api/live/${ticker}`);
|
| 1244 |
+
const data = await res.json();
|
| 1245 |
+
tradePanelPrice = data.price;
|
| 1246 |
+
|
| 1247 |
+
document.getElementById("tpStockPrice").textContent = "βΉ" + formatPrice(data.price);
|
| 1248 |
+
const sign = data.change >= 0 ? "+" : "";
|
| 1249 |
+
const changeEl = document.getElementById("tpStockChange");
|
| 1250 |
+
changeEl.textContent = `${sign}${data.change} (${sign}${data.change_pct}%)`;
|
| 1251 |
+
changeEl.className = `tp-stock-change ${data.direction}`;
|
| 1252 |
+
|
| 1253 |
+
document.getElementById("tpSummaryPrice").textContent = "βΉ" + formatPrice(data.price);
|
| 1254 |
+
updateOrderSummary();
|
| 1255 |
+
} catch (e) {
|
| 1256 |
+
console.error("Trade panel price error:", e);
|
| 1257 |
+
}
|
| 1258 |
+
}
|
| 1259 |
+
|
| 1260 |
+
function setTradeAction(action) {
|
| 1261 |
+
tradePanelAction = action;
|
| 1262 |
+
const buyBtn = document.getElementById("tpBuyBtn");
|
| 1263 |
+
const sellBtn = document.getElementById("tpSellBtn");
|
| 1264 |
+
const execBtn = document.getElementById("tpExecuteBtn");
|
| 1265 |
+
|
| 1266 |
+
if (action === "buy") {
|
| 1267 |
+
buyBtn.classList.add("active");
|
| 1268 |
+
buyBtn.classList.remove("sell");
|
| 1269 |
+
sellBtn.classList.remove("active");
|
| 1270 |
+
execBtn.textContent = "β‘ Place BUY Order";
|
| 1271 |
+
execBtn.className = "tp-execute-btn buy";
|
| 1272 |
+
} else {
|
| 1273 |
+
sellBtn.classList.add("active");
|
| 1274 |
+
buyBtn.classList.remove("active");
|
| 1275 |
+
execBtn.textContent = "β‘ Place SELL Order";
|
| 1276 |
+
execBtn.className = "tp-execute-btn sell-mode";
|
| 1277 |
+
}
|
| 1278 |
+
}
|
| 1279 |
+
|
| 1280 |
+
function updateOrderSummary() {
|
| 1281 |
+
const qty = parseInt(document.getElementById("tpQuantity").value) || 1;
|
| 1282 |
+
const total = qty * tradePanelPrice;
|
| 1283 |
+
document.getElementById("tpSummaryQty").textContent = qty;
|
| 1284 |
+
document.getElementById("tpSummaryTotal").textContent = "βΉ" + formatNumber(total);
|
| 1285 |
+
document.getElementById("tpSummaryBalance").textContent = "βΉ" + formatNumber(walletBalance);
|
| 1286 |
+
}
|
| 1287 |
+
|
| 1288 |
+
// Attach qty input listener
|
| 1289 |
+
document.addEventListener("DOMContentLoaded", () => {
|
| 1290 |
+
// Delayed to ensure element exists
|
| 1291 |
+
setTimeout(() => {
|
| 1292 |
+
const qtyInput = document.getElementById("tpQuantity");
|
| 1293 |
+
if (qtyInput) {
|
| 1294 |
+
qtyInput.addEventListener("input", updateOrderSummary);
|
| 1295 |
+
}
|
| 1296 |
+
}, 500);
|
| 1297 |
+
});
|
| 1298 |
+
|
| 1299 |
+
|
| 1300 |
+
async function executeTradeFromPanel() {
|
| 1301 |
+
if (!tradePanelTicker) {
|
| 1302 |
+
alert("Select a stock first!");
|
| 1303 |
+
return;
|
| 1304 |
+
}
|
| 1305 |
+
|
| 1306 |
+
const btn = document.getElementById("tpExecuteBtn");
|
| 1307 |
+
const origText = btn.textContent;
|
| 1308 |
+
btn.disabled = true;
|
| 1309 |
+
btn.textContent = "Processing...";
|
| 1310 |
+
|
| 1311 |
+
try {
|
| 1312 |
+
if (tradePanelAction === "buy") {
|
| 1313 |
+
// Execute buy via the AI trade endpoint
|
| 1314 |
+
const res = await fetch(`${API}/api/trade/execute/${tradePanelTicker}`, { method: "POST" });
|
| 1315 |
+
const data = await res.json();
|
| 1316 |
+
|
| 1317 |
+
if (data.action === "BUY" && data.trade_result) {
|
| 1318 |
+
const tr = data.trade_result;
|
| 1319 |
+
alert(`β
Bought ${tr.shares} shares of ${tradePanelTicker} @ βΉ${data.current_price}\nSL: βΉ${tr.stop_loss} | TP: βΉ${tr.tp1}`);
|
| 1320 |
+
addToFeed(`π’ <strong>BOUGHT ${tr.shares} x ${tradePanelTicker}</strong> @ βΉ${data.current_price}`, "buy");
|
| 1321 |
+
} else if (data.action === "WAIT") {
|
| 1322 |
+
alert(`βΈ AI recommends WAIT for ${tradePanelTicker}.\nReason: ${data.reason || "Conditions not met"}`);
|
| 1323 |
+
} else if (data.action === "HOLD") {
|
| 1324 |
+
alert(`π Already holding ${tradePanelTicker}. AI says HOLD.`);
|
| 1325 |
+
} else if (data.action === "SELL" && data.trade_result) {
|
| 1326 |
+
const tr = data.trade_result;
|
| 1327 |
+
alert(`π΄ AI triggered SELL for ${tradePanelTicker}\nP&L: βΉ${tr.profit} (${tr.profit_pct}%)`);
|
| 1328 |
+
addToFeed(`π΄ <strong>SOLD ${tradePanelTicker}</strong> | P&L: βΉ${tr.profit}`, "sell");
|
| 1329 |
+
}
|
| 1330 |
+
} else {
|
| 1331 |
+
// Execute sell
|
| 1332 |
+
const res = await fetch(`${API}/api/trade/sell/${tradePanelTicker}`, { method: "POST" });
|
| 1333 |
+
const data = await res.json();
|
| 1334 |
+
|
| 1335 |
+
if (data.status === "sold") {
|
| 1336 |
+
const profitSign = data.profit >= 0 ? "+" : "";
|
| 1337 |
+
alert(`β
Sold ${tradePanelTicker} @ βΉ${data.price}\nP&L: ${profitSign}βΉ${data.profit} (${profitSign}${data.profit_pct}%)`);
|
| 1338 |
+
addToFeed(`π΄ <strong>SOLD ${tradePanelTicker}</strong> @ βΉ${data.price} | P&L: ${profitSign}βΉ${data.profit}`, "sell");
|
| 1339 |
+
} else {
|
| 1340 |
+
alert(`β οΈ ${data.reason || "Could not sell"}`);
|
| 1341 |
+
}
|
| 1342 |
+
}
|
| 1343 |
+
|
| 1344 |
+
// Reload
|
| 1345 |
+
loadPortfolio();
|
| 1346 |
+
loadWalletBalance();
|
| 1347 |
+
loadTradeHoldings();
|
| 1348 |
+
loadTradeHistory();
|
| 1349 |
+
updateOrderSummary();
|
| 1350 |
+
|
| 1351 |
+
} catch (e) {
|
| 1352 |
+
console.error("Trade execution error:", e);
|
| 1353 |
+
alert(`β Trade failed: ${e.message}`);
|
| 1354 |
+
} finally {
|
| 1355 |
+
btn.disabled = false;
|
| 1356 |
+
btn.textContent = origText;
|
| 1357 |
+
}
|
| 1358 |
+
}
|
| 1359 |
+
|
| 1360 |
+
|
| 1361 |
+
// ββ Holdings Tab ββββββββββββββββββββββββββββββββββββββββ
|
| 1362 |
+
|
| 1363 |
+
async function loadTradeHoldings() {
|
| 1364 |
+
const list = document.getElementById("tpHoldingsList");
|
| 1365 |
+
try {
|
| 1366 |
+
const res = await fetch(`${API}/api/trade/portfolio`);
|
| 1367 |
+
const data = await res.json();
|
| 1368 |
+
const positions = data.positions || {};
|
| 1369 |
+
|
| 1370 |
+
if (Object.keys(positions).length === 0) {
|
| 1371 |
+
list.innerHTML = '<div class="tp-empty">No holdings. Start trading to see your positions here.</div>';
|
| 1372 |
+
return;
|
| 1373 |
+
}
|
| 1374 |
+
|
| 1375 |
+
list.innerHTML = Object.entries(positions).map(([ticker, pos]) => {
|
| 1376 |
+
const pnl = pos.unrealized_pnl || 0;
|
| 1377 |
+
const pnlPct = pos.pnl_pct || 0;
|
| 1378 |
+
const pnlClass = pnl >= 0 ? "positive" : "negative";
|
| 1379 |
+
const pnlSign = pnl >= 0 ? "+" : "";
|
| 1380 |
+
const currentPrice = pos.current_price || pos.buy_price;
|
| 1381 |
+
|
| 1382 |
+
return `
|
| 1383 |
+
<div class="tp-holding-card">
|
| 1384 |
+
<div class="tp-holding-main">
|
| 1385 |
+
<div class="tp-holding-left">
|
| 1386 |
+
<span class="tp-holding-ticker">${ticker}</span>
|
| 1387 |
+
<span class="tp-holding-shares">${pos.shares} shares @ βΉ${pos.buy_price}</span>
|
| 1388 |
+
</div>
|
| 1389 |
+
<div class="tp-holding-right">
|
| 1390 |
+
<span class="tp-holding-price">βΉ${formatPrice(currentPrice)}</span>
|
| 1391 |
+
<span class="tp-holding-pnl ${pnlClass}">${pnlSign}βΉ${formatNumber(Math.abs(pnl))} (${pnlSign}${pnlPct}%)</span>
|
| 1392 |
+
</div>
|
| 1393 |
+
</div>
|
| 1394 |
+
<div class="tp-holding-actions">
|
| 1395 |
+
<button class="tp-holding-trade-btn" onclick="selectTradeStock('${ticker}'); switchTradeTab('search');">Trade</button>
|
| 1396 |
+
<button class="tp-holding-sell-btn" onclick="forceSellFromPanel('${ticker}')">Quick Sell</button>
|
| 1397 |
+
</div>
|
| 1398 |
+
</div>
|
| 1399 |
+
`;
|
| 1400 |
+
}).join("");
|
| 1401 |
+
|
| 1402 |
+
} catch (e) {
|
| 1403 |
+
console.error("Holdings load error:", e);
|
| 1404 |
+
list.innerHTML = '<div class="tp-empty">Error loading holdings</div>';
|
| 1405 |
+
}
|
| 1406 |
+
}
|
| 1407 |
+
|
| 1408 |
+
async function forceSellFromPanel(ticker) {
|
| 1409 |
+
if (!confirm(`Sell all ${ticker} shares at market price?`)) return;
|
| 1410 |
+
try {
|
| 1411 |
+
const res = await fetch(`${API}/api/trade/sell/${ticker}`, { method: "POST" });
|
| 1412 |
+
const data = await res.json();
|
| 1413 |
+
if (data.status === "sold") {
|
| 1414 |
+
const profitSign = data.profit >= 0 ? "+" : "";
|
| 1415 |
+
alert(`β
Sold ${ticker} @ βΉ${data.price}\nP&L: ${profitSign}βΉ${data.profit}`);
|
| 1416 |
+
addToFeed(`π΄ <strong>SOLD ${ticker}</strong> @ βΉ${data.price}`, "sell");
|
| 1417 |
+
} else {
|
| 1418 |
+
alert(data.reason || "Could not sell");
|
| 1419 |
+
}
|
| 1420 |
+
loadTradeHoldings();
|
| 1421 |
+
loadPortfolio();
|
| 1422 |
+
loadWalletBalance();
|
| 1423 |
+
} catch (e) {
|
| 1424 |
+
alert(`Error: ${e.message}`);
|
| 1425 |
+
}
|
| 1426 |
+
}
|
| 1427 |
+
|
| 1428 |
+
|
| 1429 |
+
// ββ History Tab βββββββββββββββββββββββββββββββββββββββββ
|
| 1430 |
+
|
| 1431 |
+
async function loadTradeHistory() {
|
| 1432 |
+
const list = document.getElementById("tpHistoryList");
|
| 1433 |
+
try {
|
| 1434 |
+
const res = await fetch(`${API}/api/trade/portfolio`);
|
| 1435 |
+
const data = await res.json();
|
| 1436 |
+
const trades = data.trade_history || [];
|
| 1437 |
+
|
| 1438 |
+
if (trades.length === 0) {
|
| 1439 |
+
list.innerHTML = '<div class="tp-empty">No trade history yet. Complete a trade to see it here.</div>';
|
| 1440 |
+
return;
|
| 1441 |
+
}
|
| 1442 |
+
|
| 1443 |
+
list.innerHTML = [...trades].reverse().map(t => {
|
| 1444 |
+
const profit = (typeof t.profit === "number" && !isNaN(t.profit)) ? t.profit : 0;
|
| 1445 |
+
const profitPct = (typeof t.profit_pct === "number" && !isNaN(t.profit_pct)) ? t.profit_pct : 0;
|
| 1446 |
+
const profitClass = profit >= 0 ? "positive" : "negative";
|
| 1447 |
+
const profitSign = profit >= 0 ? "+" : "";
|
| 1448 |
+
const time = new Date(t.sell_time).toLocaleString("en-IN");
|
| 1449 |
+
|
| 1450 |
+
return `
|
| 1451 |
+
<div class="tp-history-card">
|
| 1452 |
+
<div class="tp-history-main">
|
| 1453 |
+
<div class="tp-history-left">
|
| 1454 |
+
<span class="tp-history-ticker">${t.ticker}</span>
|
| 1455 |
+
<span class="tp-history-details">${t.shares} shares @ βΉ${t.buy_price} β βΉ${t.sell_price}</span>
|
| 1456 |
+
<span class="tp-history-time">${time}</span>
|
| 1457 |
+
</div>
|
| 1458 |
+
<div class="tp-history-right">
|
| 1459 |
+
<span class="tp-history-pnl ${profitClass}">${profitSign}βΉ${formatNumber(Math.abs(profit))}</span>
|
| 1460 |
+
<span class="tp-history-pnl-pct ${profitClass}">${profitSign}${profitPct}%</span>
|
| 1461 |
+
</div>
|
| 1462 |
+
</div>
|
| 1463 |
+
<span class="tp-history-reason">${t.reason || ""}</span>
|
| 1464 |
+
</div>
|
| 1465 |
+
`;
|
| 1466 |
+
}).join("");
|
| 1467 |
+
|
| 1468 |
+
} catch (e) {
|
| 1469 |
+
console.error("History load error:", e);
|
| 1470 |
+
list.innerHTML = '<div class="tp-empty">Error loading trade history</div>';
|
| 1471 |
+
}
|
| 1472 |
+
}
|
| 1473 |
+
|
| 1474 |
+
|
| 1475 |
+
// ββ Watchlist βββββββββββββββββββββββββββββββββββββββββββ
|
| 1476 |
+
|
| 1477 |
+
function getWatchlist() {
|
| 1478 |
+
try {
|
| 1479 |
+
return JSON.parse(localStorage.getItem("stocksense_watchlist") || "[]");
|
| 1480 |
+
} catch (e) { return []; }
|
| 1481 |
+
}
|
| 1482 |
+
|
| 1483 |
+
function saveWatchlist(wl) {
|
| 1484 |
+
localStorage.setItem("stocksense_watchlist", JSON.stringify(wl));
|
| 1485 |
+
}
|
| 1486 |
+
|
| 1487 |
+
function addToWatchlist(ticker) {
|
| 1488 |
+
const wl = getWatchlist();
|
| 1489 |
+
if (!wl.includes(ticker)) {
|
| 1490 |
+
wl.push(ticker);
|
| 1491 |
+
saveWatchlist(wl);
|
| 1492 |
+
}
|
| 1493 |
+
}
|
| 1494 |
+
|
| 1495 |
+
function removeFromWatchlist(ticker) {
|
| 1496 |
+
let wl = getWatchlist();
|
| 1497 |
+
wl = wl.filter(t => t !== ticker);
|
| 1498 |
+
saveWatchlist(wl);
|
| 1499 |
+
renderWatchlist();
|
| 1500 |
+
}
|
| 1501 |
+
|
| 1502 |
+
function toggleWatchlistFromPanel() {
|
| 1503 |
+
if (!tradePanelTicker) return;
|
| 1504 |
+
const wl = getWatchlist();
|
| 1505 |
+
if (wl.includes(tradePanelTicker)) {
|
| 1506 |
+
removeFromWatchlist(tradePanelTicker);
|
| 1507 |
+
} else {
|
| 1508 |
+
addToWatchlist(tradePanelTicker);
|
| 1509 |
+
}
|
| 1510 |
+
updateWatchlistButton(tradePanelTicker);
|
| 1511 |
+
renderWatchlist();
|
| 1512 |
+
}
|
| 1513 |
+
|
| 1514 |
+
function updateWatchlistButton(ticker) {
|
| 1515 |
+
const btn = document.getElementById("tpWatchlistBtn");
|
| 1516 |
+
const wl = getWatchlist();
|
| 1517 |
+
if (wl.includes(ticker)) {
|
| 1518 |
+
btn.textContent = "β Remove from Watchlist";
|
| 1519 |
+
btn.classList.add("in-watchlist");
|
| 1520 |
+
} else {
|
| 1521 |
+
btn.textContent = "β Add to Watchlist";
|
| 1522 |
+
btn.classList.remove("in-watchlist");
|
| 1523 |
+
}
|
| 1524 |
+
}
|
| 1525 |
+
|
| 1526 |
+
function renderWatchlist() {
|
| 1527 |
+
const list = document.getElementById("tpWatchlistList");
|
| 1528 |
+
const wl = getWatchlist();
|
| 1529 |
+
|
| 1530 |
+
if (wl.length === 0) {
|
| 1531 |
+
list.innerHTML = '<div class="tp-empty">Your watchlist is empty. Search for a stock and click β to add.</div>';
|
| 1532 |
+
return;
|
| 1533 |
+
}
|
| 1534 |
+
|
| 1535 |
+
list.innerHTML = wl.map(ticker => `
|
| 1536 |
+
<div class="tp-watchlist-item" id="wl-${ticker.replace('.', '-')}">
|
| 1537 |
+
<div class="tp-wl-left" onclick="selectTradeStock('${ticker}'); switchTradeTab('search');" style="cursor:pointer;">
|
| 1538 |
+
<span class="tp-wl-ticker">${ticker}</span>
|
| 1539 |
+
<span class="tp-wl-price" id="wlPrice-${ticker.replace('.', '-')}">β</span>
|
| 1540 |
+
</div>
|
| 1541 |
+
<div class="tp-wl-right">
|
| 1542 |
+
<span class="tp-wl-change" id="wlChange-${ticker.replace('.', '-')}">β</span>
|
| 1543 |
+
<button class="tp-wl-remove" onclick="removeFromWatchlist('${ticker}')" title="Remove">β</button>
|
| 1544 |
+
</div>
|
| 1545 |
+
</div>
|
| 1546 |
+
`).join("");
|
| 1547 |
+
}
|
| 1548 |
+
|
| 1549 |
+
async function refreshWatchlistPrices() {
|
| 1550 |
+
const wl = getWatchlist();
|
| 1551 |
+
for (const ticker of wl) {
|
| 1552 |
+
try {
|
| 1553 |
+
const res = await fetch(`${API}/api/live/${ticker}`);
|
| 1554 |
+
const data = await res.json();
|
| 1555 |
+
const safeId = ticker.replace('.', '-');
|
| 1556 |
+
const priceEl = document.getElementById(`wlPrice-${safeId}`);
|
| 1557 |
+
const changeEl = document.getElementById(`wlChange-${safeId}`);
|
| 1558 |
+
if (priceEl) priceEl.textContent = "βΉ" + formatPrice(data.price);
|
| 1559 |
+
if (changeEl) {
|
| 1560 |
+
const sign = data.change >= 0 ? "+" : "";
|
| 1561 |
+
changeEl.textContent = `${sign}${data.change_pct}%`;
|
| 1562 |
+
changeEl.className = `tp-wl-change ${data.direction}`;
|
| 1563 |
+
}
|
| 1564 |
+
} catch (e) { /* ignore */ }
|
| 1565 |
+
}
|
| 1566 |
+
}
|
| 1567 |
+
|
| 1568 |
+
|
| 1569 |
+
// ββ Market Hours Detection (IST) ββββββββββββββββββββββββ
|
| 1570 |
+
|
| 1571 |
+
function isIndianMarketOpen() {
|
| 1572 |
+
const now = new Date();
|
| 1573 |
+
// Convert to IST (UTC+5:30)
|
| 1574 |
+
const utc = now.getTime() + now.getTimezoneOffset() * 60000;
|
| 1575 |
+
const ist = new Date(utc + 5.5 * 3600000);
|
| 1576 |
+
|
| 1577 |
+
const day = ist.getDay(); // 0=Sun, 6=Sat
|
| 1578 |
+
if (day === 0 || day === 6) return false;
|
| 1579 |
+
|
| 1580 |
+
const hours = ist.getHours();
|
| 1581 |
+
const minutes = ist.getMinutes();
|
| 1582 |
+
const timeMinutes = hours * 60 + minutes;
|
| 1583 |
+
|
| 1584 |
+
// 9:15 AM to 3:30 PM IST
|
| 1585 |
+
return timeMinutes >= 555 && timeMinutes <= 930;
|
| 1586 |
+
}
|
| 1587 |
+
|
| 1588 |
+
function updateTradePanelMarketBadge() {
|
| 1589 |
+
const live = isIndianMarketOpen();
|
| 1590 |
+
const badge = document.getElementById("tpMarketBadge");
|
| 1591 |
+
const status = document.getElementById("tpMarketStatus");
|
| 1592 |
+
const dot = badge ? badge.querySelector(".dot") : null;
|
| 1593 |
+
|
| 1594 |
+
if (status) status.textContent = live ? "MARKET OPEN" : "MARKET CLOSED";
|
| 1595 |
+
if (dot) {
|
| 1596 |
+
dot.style.background = live ? "#22c55e" : "#6b7280";
|
| 1597 |
+
dot.style.animation = live ? "pulse 1.5s infinite" : "none";
|
| 1598 |
+
}
|
| 1599 |
+
if (badge) badge.className = `tp-market-badge ${live ? "live" : "offline"}`;
|
| 1600 |
+
}
|
| 1601 |
+
|
| 1602 |
+
|
| 1603 |
+
// ββ Account Value Chart βββββββββββββββββββββββββββββββββ
|
| 1604 |
+
|
| 1605 |
+
async function drawAccountValueChart() {
|
| 1606 |
+
try {
|
| 1607 |
+
const res = await fetch(`${API}/api/portfolio/value-history`);
|
| 1608 |
+
const data = await res.json();
|
| 1609 |
+
const snapshots = data.snapshots || [];
|
| 1610 |
+
|
| 1611 |
+
if (snapshots.length === 0) return;
|
| 1612 |
+
|
| 1613 |
+
// Also add current value
|
| 1614 |
+
try {
|
| 1615 |
+
const portRes = await fetch(`${API}/api/trade/portfolio`);
|
| 1616 |
+
const portData = await portRes.json();
|
| 1617 |
+
const currentVal = portData.total_value || portData.balance;
|
| 1618 |
+
snapshots.push({
|
| 1619 |
+
timestamp: new Date().toISOString(),
|
| 1620 |
+
value: currentVal,
|
| 1621 |
+
});
|
| 1622 |
+
} catch (e) { /* ignore */ }
|
| 1623 |
+
|
| 1624 |
+
const labels = snapshots.map(s => {
|
| 1625 |
+
const d = new Date(s.timestamp);
|
| 1626 |
+
return d.toLocaleDateString("en-IN", { day: "2-digit", month: "short" }) + " " +
|
| 1627 |
+
d.toLocaleTimeString("en-IN", { hour: "2-digit", minute: "2-digit" });
|
| 1628 |
+
});
|
| 1629 |
+
const values = snapshots.map(s => s.value);
|
| 1630 |
+
|
| 1631 |
+
const isUp = values[values.length - 1] >= values[0];
|
| 1632 |
+
const lineColor = isUp ? "#22c55e" : "#ef4444";
|
| 1633 |
+
const fillColor = isUp ? "rgba(34,197,94,0.1)" : "rgba(239,68,68,0.1)";
|
| 1634 |
+
|
| 1635 |
+
if (accountValueChart) accountValueChart.destroy();
|
| 1636 |
+
|
| 1637 |
+
const ctx = document.getElementById("accountValueChart");
|
| 1638 |
+
if (!ctx) return;
|
| 1639 |
+
|
| 1640 |
+
accountValueChart = new Chart(ctx.getContext("2d"), {
|
| 1641 |
+
type: "line",
|
| 1642 |
+
data: {
|
| 1643 |
+
labels,
|
| 1644 |
+
datasets: [{
|
| 1645 |
+
label: "Account Value",
|
| 1646 |
+
data: values,
|
| 1647 |
+
borderColor: lineColor,
|
| 1648 |
+
backgroundColor: fillColor,
|
| 1649 |
+
fill: true,
|
| 1650 |
+
tension: 0.4,
|
| 1651 |
+
pointRadius: values.length > 20 ? 0 : 3,
|
| 1652 |
+
borderWidth: 2,
|
| 1653 |
+
pointBackgroundColor: lineColor,
|
| 1654 |
+
}],
|
| 1655 |
+
},
|
| 1656 |
+
options: {
|
| 1657 |
+
responsive: true,
|
| 1658 |
+
maintainAspectRatio: false,
|
| 1659 |
+
plugins: {
|
| 1660 |
+
legend: { display: false },
|
| 1661 |
+
tooltip: {
|
| 1662 |
+
backgroundColor: "#1a1f2e",
|
| 1663 |
+
borderColor: "#242a38",
|
| 1664 |
+
borderWidth: 1,
|
| 1665 |
+
titleColor: "#fff",
|
| 1666 |
+
bodyColor: "#d1d5db",
|
| 1667 |
+
callbacks: {
|
| 1668 |
+
label: (ctx) => "βΉ" + formatNumber(ctx.parsed.y),
|
| 1669 |
+
},
|
| 1670 |
+
},
|
| 1671 |
+
},
|
| 1672 |
+
scales: {
|
| 1673 |
+
x: {
|
| 1674 |
+
ticks: { color: "#4b5563", maxTicksLimit: 6, maxRotation: 0, font: { size: 9 } },
|
| 1675 |
+
grid: { color: "#1f2937" },
|
| 1676 |
+
},
|
| 1677 |
+
y: {
|
| 1678 |
+
ticks: {
|
| 1679 |
+
color: "#4b5563",
|
| 1680 |
+
font: { size: 10 },
|
| 1681 |
+
callback: (v) => "βΉ" + (v / 1000).toFixed(0) + "K",
|
| 1682 |
+
},
|
| 1683 |
+
grid: { color: "#1f2937" },
|
| 1684 |
+
},
|
| 1685 |
+
},
|
| 1686 |
+
},
|
| 1687 |
+
});
|
| 1688 |
+
|
| 1689 |
+
// Update market badge on account value section
|
| 1690 |
+
updateAccountValueMarketBadge();
|
| 1691 |
+
|
| 1692 |
+
} catch (e) {
|
| 1693 |
+
console.error("Account value chart error:", e);
|
| 1694 |
+
}
|
| 1695 |
+
}
|
| 1696 |
+
|
| 1697 |
+
function updateAccountValueMarketBadge() {
|
| 1698 |
+
const live = isIndianMarketOpen();
|
| 1699 |
+
const dot = document.getElementById("avMarketDot");
|
| 1700 |
+
const label = document.getElementById("avMarketLabel");
|
| 1701 |
+
const badge = document.getElementById("avMarketBadge");
|
| 1702 |
+
|
| 1703 |
+
if (label) label.textContent = live ? "LIVE" : "OFFLINE";
|
| 1704 |
+
if (dot) {
|
| 1705 |
+
dot.style.background = live ? "#22c55e" : "#6b7280";
|
| 1706 |
+
dot.style.animation = live ? "pulse 1.5s infinite" : "none";
|
| 1707 |
+
}
|
| 1708 |
+
if (badge) badge.className = `av-market-badge ${live ? "live" : "offline"}`;
|
| 1709 |
+
}
|
| 1710 |
+
|
| 1711 |
+
// Load account value chart when switching to trading tab
|
| 1712 |
+
const origSwitchTab = switchTab;
|
| 1713 |
+
switchTab = function (tab) {
|
| 1714 |
+
origSwitchTab(tab);
|
| 1715 |
+
if (tab === "trading") {
|
| 1716 |
+
setTimeout(drawAccountValueChart, 300);
|
| 1717 |
+
}
|
| 1718 |
+
};
|
| 1719 |
+
|
| 1720 |
+
// Initial market badge update
|
| 1721 |
+
setInterval(updateAccountValueMarketBadge, 60000);
|