-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
545 lines (468 loc) · 19 KB
/
script.js
File metadata and controls
545 lines (468 loc) · 19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
// ===========================
// STATE MANAGEMENT
// ===========================
let currentDate = new Date();
let selectedDate = null;
let trades = JSON.parse(localStorage.getItem('trades')) || [];
let mediaRecorder = null;
let audioChunks = [];
let recordingInterval = null;
let recordingSeconds = 0;
// ===========================
// INITIALIZATION
// ===========================
document.addEventListener('DOMContentLoaded', () => {
initializeApp();
});
function initializeApp() {
setupNavigation();
renderCalendar();
renderTrades();
setupModal();
setupPositionCalculator();
updateMarketHours();
setInterval(updateMarketHours, 1000);
// Set default date to today
const today = new Date();
document.getElementById('trade-date').valueAsDate = today;
}
// ===========================
// NAVIGATION
// ===========================
function setupNavigation() {
const navItems = document.querySelectorAll('.nav-item');
const tabContents = document.querySelectorAll('.tab-content');
navItems.forEach(item => {
item.addEventListener('click', () => {
const tabName = item.dataset.tab;
// Update active nav item
navItems.forEach(nav => nav.classList.remove('active'));
item.classList.add('active');
// Update active tab content
tabContents.forEach(tab => tab.classList.remove('active'));
document.getElementById(`${tabName}-tab`).classList.add('active');
});
});
}
// ===========================
// CALENDAR
// ===========================
function renderCalendar() {
const calendarGrid = document.getElementById('calendar-grid');
const calendarTitle = document.getElementById('calendar-title');
// Update title
const monthNames = ['January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'];
calendarTitle.textContent = `${monthNames[currentDate.getMonth()]} ${currentDate.getFullYear()}`;
// Clear calendar
calendarGrid.innerHTML = '';
// Add day headers
const dayHeaders = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
dayHeaders.forEach(day => {
const header = document.createElement('div');
header.className = 'calendar-day-header';
header.textContent = day;
calendarGrid.appendChild(header);
});
// Get first day of month and number of days
const firstDay = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1);
const lastDay = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0);
const prevLastDay = new Date(currentDate.getFullYear(), currentDate.getMonth(), 0);
const firstDayIndex = firstDay.getDay();
const lastDayDate = lastDay.getDate();
const prevLastDayDate = prevLastDay.getDate();
// Add previous month days
for (let i = firstDayIndex - 1; i >= 0; i--) {
const day = document.createElement('div');
day.className = 'calendar-day other-month';
day.textContent = prevLastDayDate - i;
calendarGrid.appendChild(day);
}
// Add current month days
const today = new Date();
for (let i = 1; i <= lastDayDate; i++) {
const day = document.createElement('div');
day.className = 'calendar-day';
day.textContent = i;
const dayDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), i);
// Check if today
if (dayDate.toDateString() === today.toDateString()) {
day.classList.add('today');
}
// Check if selected
if (selectedDate && dayDate.toDateString() === selectedDate.toDateString()) {
day.classList.add('selected');
}
// Check if has trades
if (hasTradeOnDate(dayDate)) {
day.classList.add('has-trade');
}
day.addEventListener('click', () => selectDate(dayDate));
calendarGrid.appendChild(day);
}
// Add next month days
const remainingDays = 42 - (firstDayIndex + lastDayDate);
for (let i = 1; i <= remainingDays; i++) {
const day = document.createElement('div');
day.className = 'calendar-day other-month';
day.textContent = i;
calendarGrid.appendChild(day);
}
}
function selectDate(date) {
selectedDate = date;
renderCalendar();
filterTradesByDate(date);
}
function hasTradeOnDate(date) {
return trades.some(trade => {
const tradeDate = new Date(trade.date);
return tradeDate.toDateString() === date.toDateString();
});
}
function filterTradesByDate(date) {
const filteredTrades = trades.filter(trade => {
const tradeDate = new Date(trade.date);
return tradeDate.toDateString() === date.toDateString();
});
renderTrades(filteredTrades);
}
// Calendar navigation
document.getElementById('prev-month').addEventListener('click', () => {
currentDate.setMonth(currentDate.getMonth() - 1);
renderCalendar();
});
document.getElementById('next-month').addEventListener('click', () => {
currentDate.setMonth(currentDate.getMonth() + 1);
renderCalendar();
});
// ===========================
// TRADES
// ===========================
function renderTrades(tradesToRender = trades) {
const container = document.getElementById('trades-container');
if (tradesToRender.length === 0) {
container.innerHTML = `
<div class="empty-state">
<svg width="64" height="64" viewBox="0 0 64 64" fill="none">
<circle cx="32" cy="32" r="30" stroke="currentColor" stroke-width="2" opacity="0.2"/>
<path d="M32 20V32L40 36" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
</svg>
<p>No trades recorded yet</p>
<p class="empty-subtitle">Click "Add Trade" to start tracking</p>
</div>
`;
return;
}
// Sort trades by date (newest first)
const sortedTrades = [...tradesToRender].sort((a, b) => new Date(b.date) - new Date(a.date));
container.innerHTML = sortedTrades.map(trade => `
<div class="trade-card">
<div class="trade-card-header">
<span class="trade-pair">${trade.pair}</span>
<span class="trade-badge ${trade.bias.toLowerCase()}">${trade.bias}</span>
</div>
<div class="trade-details">
<div class="trade-detail-item">
<span class="trade-detail-label">Date</span>
<span class="trade-detail-value">${formatDate(trade.date)}</span>
</div>
<div class="trade-detail-item">
<span class="trade-detail-label">Timeframe</span>
<span class="trade-detail-value">${trade.timeframe}</span>
</div>
<div class="trade-detail-item">
<span class="trade-detail-label">Session</span>
<span class="trade-detail-value">${trade.session}</span>
</div>
<div class="trade-detail-item">
<span class="trade-detail-label">Confluences</span>
<span class="trade-detail-value">${trade.confluences.length}</span>
</div>
</div>
${trade.comments ? `<p style="margin-top: 1rem; color: var(--text-secondary); font-size: 0.875rem;">${trade.comments}</p>` : ''}
</div>
`).join('');
}
function formatDate(dateString) {
const date = new Date(dateString);
const options = { month: 'short', day: 'numeric', year: 'numeric' };
return date.toLocaleDateString('en-US', options);
}
// ===========================
// MODAL
// ===========================
function setupModal() {
const modal = document.getElementById('trade-modal');
const addBtn = document.getElementById('add-trade-btn');
const closeBtn = document.getElementById('close-modal');
const cancelBtn = document.getElementById('cancel-btn');
const form = document.getElementById('trade-form');
const overlay = document.querySelector('.modal-overlay');
addBtn.addEventListener('click', () => {
modal.classList.add('active');
});
const closeModal = () => {
modal.classList.remove('active');
form.reset();
resetVoiceRecorder();
};
closeBtn.addEventListener('click', closeModal);
cancelBtn.addEventListener('click', closeModal);
overlay.addEventListener('click', closeModal);
// Form submission
form.addEventListener('submit', (e) => {
e.preventDefault();
saveTrade();
closeModal();
});
// File upload preview
const fileInput = document.getElementById('trade-screenshot');
fileInput.addEventListener('change', handleFileUpload);
// Voice recorder
setupVoiceRecorder();
}
function handleFileUpload(e) {
const files = e.target.files;
const preview = document.getElementById('screenshot-preview');
preview.innerHTML = '';
Array.from(files).forEach(file => {
if (file.type.startsWith('image/')) {
const reader = new FileReader();
reader.onload = (e) => {
const div = document.createElement('div');
div.className = 'preview-image';
div.innerHTML = `<img src="${e.target.result}" alt="Screenshot">`;
preview.appendChild(div);
};
reader.readAsDataURL(file);
}
});
}
function saveTrade() {
const trade = {
id: Date.now(),
date: document.getElementById('trade-date').value,
pair: document.getElementById('trade-pair').value,
timeframe: document.getElementById('trade-timeframe').value,
session: document.getElementById('trade-session').value,
confluences: Array.from(document.querySelectorAll('input[name="confluence"]:checked')).map(cb => cb.value),
bias: document.querySelector('input[name="bias"]:checked').value,
comments: document.getElementById('trade-comments').value,
mistakes: document.getElementById('trade-mistakes').value,
screenshots: [], // In a real app, you'd upload these to a server
voiceNote: null // In a real app, you'd upload this to a server
};
trades.push(trade);
localStorage.setItem('trades', JSON.stringify(trades));
renderTrades();
renderCalendar();
}
// ===========================
// VOICE RECORDER
// ===========================
function setupVoiceRecorder() {
const recordBtn = document.getElementById('record-btn');
recordBtn.addEventListener('click', toggleRecording);
}
async function toggleRecording() {
const recordBtn = document.getElementById('record-btn');
const recordText = document.getElementById('record-text');
if (!mediaRecorder || mediaRecorder.state === 'inactive') {
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
mediaRecorder = new MediaRecorder(stream);
audioChunks = [];
mediaRecorder.ondataavailable = (event) => {
audioChunks.push(event.data);
};
mediaRecorder.onstop = () => {
const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
const audioUrl = URL.createObjectURL(audioBlob);
const audioPlayback = document.getElementById('audio-playback');
audioPlayback.src = audioUrl;
audioPlayback.style.display = 'block';
};
mediaRecorder.start();
recordBtn.classList.add('recording');
recordText.textContent = 'Stop Recording';
// Start timer
recordingSeconds = 0;
updateRecordingTime();
recordingInterval = setInterval(updateRecordingTime, 1000);
} catch (error) {
console.error('Error accessing microphone:', error);
alert('Unable to access microphone. Please check permissions.');
}
} else {
mediaRecorder.stop();
mediaRecorder.stream.getTracks().forEach(track => track.stop());
recordBtn.classList.remove('recording');
recordText.textContent = 'Start Recording';
clearInterval(recordingInterval);
}
}
function updateRecordingTime() {
recordingSeconds++;
const minutes = Math.floor(recordingSeconds / 60);
const seconds = recordingSeconds % 60;
document.getElementById('recording-time').textContent =
`${minutes}:${seconds.toString().padStart(2, '0')}`;
}
function resetVoiceRecorder() {
if (mediaRecorder && mediaRecorder.state === 'recording') {
mediaRecorder.stop();
mediaRecorder.stream.getTracks().forEach(track => track.stop());
}
const recordBtn = document.getElementById('record-btn');
const recordText = document.getElementById('record-text');
const audioPlayback = document.getElementById('audio-playback');
recordBtn.classList.remove('recording');
recordText.textContent = 'Start Recording';
audioPlayback.style.display = 'none';
audioPlayback.src = '';
document.getElementById('recording-time').textContent = '0:00';
clearInterval(recordingInterval);
recordingSeconds = 0;
}
// ===========================
// POSITION SIZE CALCULATOR
// ===========================
function setupPositionCalculator() {
const calculateBtn = document.getElementById('calculate-position');
calculateBtn.addEventListener('click', calculatePositionSize);
}
function calculatePositionSize() {
const accountBalance = parseFloat(document.getElementById('account-balance').value);
const riskPercentage = parseFloat(document.getElementById('risk-percentage').value);
const entryPrice = parseFloat(document.getElementById('entry-price').value);
const stopLoss = parseFloat(document.getElementById('stop-loss').value);
const pipValue = parseFloat(document.getElementById('pip-value').value);
// Validate inputs
if (!accountBalance || !riskPercentage || !entryPrice || !stopLoss || !pipValue) {
alert('Please fill in all fields');
return;
}
if (riskPercentage > 5) {
alert('Risk percentage should not exceed 5%');
return;
}
// Calculate risk amount
const riskAmount = accountBalance * (riskPercentage / 100);
// Calculate pips at risk
const pipsAtRisk = Math.abs(entryPrice - stopLoss) * 10000; // For 4 decimal pairs
// Calculate position size in lots
const positionSize = riskAmount / (pipsAtRisk * pipValue);
// Display results
const resultDiv = document.getElementById('position-result');
resultDiv.style.display = 'block';
document.getElementById('position-size').textContent = positionSize.toFixed(2) + ' lots';
document.getElementById('risk-amount').textContent = '$' + riskAmount.toFixed(2);
document.getElementById('pips-risk').textContent = pipsAtRisk.toFixed(1) + ' pips';
}
// ===========================
// MARKET HOURS
// ===========================
function updateMarketHours() {
const now = new Date();
// Convert to IST (UTC+5:30)
const istOffset = 5.5 * 60; // in minutes
const utcTime = now.getTime() + (now.getTimezoneOffset() * 60000);
const istTime = new Date(utcTime + (istOffset * 60000));
// Update current time display
const timeString = istTime.toLocaleTimeString('en-IN', {
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false
});
document.getElementById('current-ist-time').textContent = timeString;
// Market sessions in IST
const sessions = [
{ name: 'sydney', start: 3.5, end: 12.5, element: 'sydney-status', progress: '.sydney' },
{ name: 'tokyo', start: 5.5, end: 14.5, element: 'tokyo-status', progress: '.tokyo' },
{ name: 'london', start: 13.5, end: 22.5, element: 'london-status', progress: '.london' },
{ name: 'newyork', start: 19, end: 28, element: 'newyork-status', progress: '.newyork' } // 28 = 4 AM next day
];
const currentHour = istTime.getHours() + (istTime.getMinutes() / 60);
sessions.forEach(session => {
const statusElement = document.getElementById(session.element);
const progressBar = document.querySelector(`.session-progress${session.progress}`);
let isOpen = false;
let progress = 0;
if (session.start < session.end) {
isOpen = currentHour >= session.start && currentHour < session.end;
if (isOpen) {
progress = ((currentHour - session.start) / (session.end - session.start)) * 100;
}
} else {
// Handles overnight sessions
isOpen = currentHour >= session.start || currentHour < (session.end - 24);
if (currentHour >= session.start) {
progress = ((currentHour - session.start) / (session.end - session.start)) * 100;
} else if (currentHour < (session.end - 24)) {
progress = (((24 - session.start) + currentHour) / (session.end - session.start)) * 100;
}
}
if (isOpen) {
statusElement.textContent = 'Open';
statusElement.classList.add('open');
progressBar.style.width = progress + '%';
} else {
statusElement.textContent = 'Closed';
statusElement.classList.remove('open');
progressBar.style.width = '0%';
}
});
}
// ===========================
// UTILITY FUNCTIONS
// ===========================
function showNotification(message, type = 'info') {
// Simple notification system
const notification = document.createElement('div');
notification.className = `notification notification-${type}`;
notification.textContent = message;
notification.style.cssText = `
position: fixed;
top: 20px;
right: 20px;
padding: 1rem 1.5rem;
background: var(--bg-secondary);
border: 1px solid var(--border-color);
border-radius: var(--radius-lg);
box-shadow: var(--shadow-xl);
z-index: 10000;
animation: slideIn 0.3s ease;
`;
document.body.appendChild(notification);
setTimeout(() => {
notification.style.animation = 'slideOut 0.3s ease';
setTimeout(() => notification.remove(), 300);
}, 3000);
}
// Add CSS animations for notifications
const style = document.createElement('style');
style.textContent = `
@keyframes slideIn {
from {
transform: translateX(400px);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
}
@keyframes slideOut {
from {
transform: translateX(0);
opacity: 1;
}
to {
transform: translateX(400px);
opacity: 0;
}
}
`;
document.head.appendChild(style);