File size: 48,110 Bytes
7285374 |
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 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 |
// Global variables
let apiConnected = false;
let affirmationTimerInterval;
let affirmationTimeLeft = 300; // 5 minutes in seconds
let affirmationTimerRunning = false;
// Initialize the app
document.addEventListener('DOMContentLoaded', function() {
initTabs();
updateDateTime();
fetchAndUpdateTicker();
checkStoredApiKey();
// Set interval updates
setInterval(updateDateTime, 1000);
setInterval(fetchAndUpdateTicker, 60000); // Update ticker every minute
setInterval(updateActiveTrades, 5000);
// Check if Gemini API key is pre-set in environment
checkPresetGeminiKey();
});
// Check if Gemini API key is preset in environment variables
function checkPresetGeminiKey() {
fetch('/api/gemini_key')
.then(response => response.json())
.then(data => {
if (data.status === 'available') {
// Auto-fill the field with masked key
document.getElementById('geminiApiKey').value = data.key;
// Auto-connect if key is available
connectApi(true);
}
})
.catch(error => console.error('Error checking preset Gemini key:', error));
}
// Tab navigation
function initTabs() {
const tabs = document.querySelectorAll('.tab');
tabs.forEach(tab => {
tab.addEventListener('click', function() {
// Remove active class from all tabs and contents
document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
// Add active class to clicked tab
this.classList.add('active');
// Show corresponding content
const tabId = this.getAttribute('data-tab');
document.getElementById(tabId).classList.add('active');
// Load tab-specific data if needed
if (tabId === 'sessions') {
loadSessionsData();
} else if (tabId === 'intermarket') {
loadIntermarketData();
}
});
});
}
// Load sessions data
function loadSessionsData() {
// Load Asia session data
fetch('/api/market_data/asia')
.then(response => response.json())
.then(data => {
updateMarketMovements('asia', data);
})
.catch(error => console.error('Error loading Asia data:', error));
// Load Europe session data
fetch('/api/market_data/europe')
.then(response => response.json())
.then(data => {
updateMarketMovements('europe', data);
})
.catch(error => console.error('Error loading Europe data:', error));
// Load US session data
fetch('/api/market_data/us')
.then(response => response.json())
.then(data => {
updateMarketMovements('us', data);
})
.catch(error => console.error('Error loading US data:', error));
// Load economic calendar
fetch('/api/economic_calendar')
.then(response => response.json())
.then(data => {
updateEconomicCalendar(data);
})
.catch(error => console.error('Error loading economic calendar:', error));
}
// Load intermarket data
function loadIntermarketData() {
fetch('/api/intermarket')
.then(response => response.json())
.then(data => {
updateIntermarketDisplay(data);
})
.catch(error => console.error('Error loading intermarket data:', error));
}
// Update market movements display
function updateMarketMovements(region, data) {
// Find the container for this region (would need to add IDs to the HTML)
let container;
if (region === 'asia') {
container = document.querySelector('#sessions .section:nth-child(1) .widget:nth-child(4)');
} else if (region === 'europe') {
container = document.querySelector('#sessions .section:nth-child(2) .widget:nth-child(4)');
} else if (region === 'us') {
container = document.querySelector('#sessions .section:nth-child(3) .widget:nth-child(4)');
}
if (!container) return;
// Clear existing content
container.innerHTML = '<div class="widget-title">Marktbewegungen</div>';
// Add each market item
data.forEach(market => {
const marketItem = document.createElement('div');
marketItem.className = 'market-item';
marketItem.innerHTML = `
<div class="market-name">${market.name}</div>
<div class="market-value ${market.direction}">${market.direction === 'up' ? '+' : '-'}${market.change_percent.toFixed(1)}%</div>
`;
container.appendChild(marketItem);
});
}
// Update economic calendar
function updateEconomicCalendar(events) {
// Update all three economic calendar sections
const containers = [
document.querySelector('#sessions .section:nth-child(1) .widget:nth-child(3)'), // Asia
document.querySelector('#sessions .section:nth-child(2) .widget:nth-child(3)'), // Europe
document.querySelector('#sessions .section:nth-child(3) .widget:nth-child(3)') // US
];
containers.forEach(container => {
if (!container) return;
// Keep the title
const title = container.querySelector('.widget-title');
const titleHTML = title ? title.outerHTML : '<div class="widget-title">Wirtschaftskalender</div>';
// Clear existing content
container.innerHTML = titleHTML;
// Add first 3 events to each calendar
events.slice(0, 3).forEach(event => {
const eventItem = document.createElement('div');
eventItem.className = 'event-item';
// Determine impact level
let impactClass = 'low';
if (event.impact === 'high') impactClass = 'high';
else if (event.impact === 'medium') impactClass = 'medium';
eventItem.innerHTML = `
<div class="flex justify-between">
<div>
<span class="event-impact ${impactClass}"></span>
<span class="event-name">${event.country} ${event.event}</span>
</div>
<div class="event-time">${new Date(event.time).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})}</div>
</div>
<div class="text-sm text-gray-600 mt-1">
Prognose: ${event.forecast || 'N/A'} | Vorher: ${event.previous || 'N/A'}
</div>
`;
container.appendChild(eventItem);
});
});
}
// Update intermarket display
function updateIntermarketDisplay(data) {
// Update correlation matrix
const correlationCells = document.querySelectorAll('.correlation-matrix .matrix-table tbody td:not(:first-child)');
if (correlationCells.length > 0 && data.correlations) {
// Map cell indexes to correlation keys
const correlationMap = [
null, 'stocks_bonds', 'stocks_commodities', 'stocks_dollar', // Row 1 (Stocks)
'stocks_bonds', null, 'bonds_commodities', 'bonds_dollar', // Row 2 (Bonds)
'stocks_commodities', 'bonds_commodities', null, 'commodities_dollar', // Row 3 (Commodities)
'stocks_dollar', 'bonds_dollar', 'commodities_dollar', null // Row 4 (Dollar)
];
correlationCells.forEach((cell, index) => {
const key = correlationMap[index];
if (key && data.correlations[key] !== undefined) {
const value = data.correlations[key];
cell.textContent = value.toFixed(2);
// Update correlation class
cell.className = '';
if (value > 0.3) cell.classList.add('correlation-positive');
else if (value < -0.3) cell.classList.add('correlation-negative');
else cell.classList.add('correlation-neutral');
}
});
}
// Update asset data if available
if (data.assets) {
// Could update specific asset information on the page
console.log('Asset data available for further display:', data.assets);
}
}
// API key functions
function saveApiKey() {
const keyInput = document.getElementById('geminiApiKey');
if (keyInput.value.trim()) {
const apiKey = keyInput.value.trim();
localStorage.setItem('geminiApiKey', apiKey);
// Visual confirmation that key was saved
keyInput.style.borderColor = '#2ecc71';
setTimeout(() => {
keyInput.style.borderColor = '';
}, 2000);
return apiKey;
}
return null;
}
function checkStoredApiKey() {
const storedKey = localStorage.getItem('geminiApiKey');
if (storedKey) {
document.getElementById('geminiApiKey').value = storedKey;
// Optional: Auto-connect with stored key
// connectApi();
}
}
function connectApi(isPreset = false) {
let apiKey;
if (isPreset) {
apiKey = document.getElementById('geminiApiKey').value;
} else {
apiKey = saveApiKey();
if (!apiKey) {
alert('Bitte gib einen API-Schlüssel ein.');
return;
}
}
const connectText = document.getElementById('connectText');
const apiSpinner = document.getElementById('apiSpinner');
const apiStatus = document.getElementById('apiStatus');
// Show spinner, change button text
connectText.textContent = 'Verbinde...';
apiSpinner.style.display = 'inline-block';
// Simulate API connection (in a real app, we'd validate the key)
setTimeout(() => {
// Connection successful
apiConnected = true;
connectText.textContent = 'Verbunden';
apiSpinner.style.display = 'none';
apiStatus.classList.add('connected');
// Add success class to button
const connectButton = document.querySelector('button[onclick="connectApi()"]');
connectButton.style.backgroundColor = '#2ecc71';
connectButton.disabled = true;
// Show a welcome message in chat
addChatMessage('ai', 'API-Verbindung hergestellt! Ich bin jetzt bereit, dir mit KI-gestützten Trading-Analysen zu helfen. Frag mich etwas zu Märkten, Trading-Strategien oder deinen aktuellen Trades.');
}, 2000);
}
// Update date and time
function updateDateTime() {
const now = new Date();
// Update trading session status
updateSessionStatus(now);
// Update any countdown timers
updateCountdowns(now);
}
function updateSessionStatus(now) {
const hour = now.getUTCHours();
const isWeekend = now.getUTCDay() === 0 || now.getUTCDay() === 6;
// Get market status from the backend to determine if markets are open
fetch('/api/market_overview')
.then(response => response.json())
.then(data => {
const marketStatus = data.market_status;
// This is a simplified version - a real implementation would be more nuanced
if (!isWeekend && marketStatus === 'open') {
// Asia session (roughly 00:00-09:00 CET / 23:00-08:00 UTC)
if (hour >= 23 || hour < 8) {
updateSessionElement('asia', 'active');
updateSessionElement('europe', 'upcoming');
updateSessionElement('us', 'closed');
}
// Europe session (roughly 08:00-16:30 CET / 07:00-15:30 UTC)
else if (hour >= 8 && hour < 16) {
updateSessionElement('asia', 'closed');
updateSessionElement('europe', 'active');
updateSessionElement('us', 'upcoming');
}
// US session (roughly 14:30-21:00 CET / 13:30-20:00 UTC)
else if (hour >= 16 && hour < 20) {
updateSessionElement('asia', 'upcoming');
updateSessionElement('europe', 'closed');
updateSessionElement('us', 'active');
}
// Overlap or non-active period
else {
updateSessionElement('asia', 'upcoming');
updateSessionElement('europe', 'closed');
updateSessionElement('us', 'closed');
}
} else {
// Weekend or markets closed - all markets closed
updateSessionElement('asia', 'closed');
updateSessionElement('europe', 'closed');
updateSessionElement('us', 'closed');
}
})
.catch(error => {
console.error('Error fetching market status:', error);
// Fallback to time-based logic on error
if (!isWeekend) {
if (hour >= 23 || hour < 8) {
updateSessionElement('asia', 'active');
updateSessionElement('europe', 'upcoming');
updateSessionElement('us', 'closed');
} else if (hour >= 8 && hour < 16) {
updateSessionElement('asia', 'closed');
updateSessionElement('europe', 'active');
updateSessionElement('us', 'upcoming');
} else if (hour >= 16 && hour < 20) {
updateSessionElement('asia', 'upcoming');
updateSessionElement('europe', 'closed');
updateSessionElement('us', 'active');
} else {
updateSessionElement('asia', 'upcoming');
updateSessionElement('europe', 'closed');
updateSessionElement('us', 'closed');
}
} else {
updateSessionElement('asia', 'closed');
updateSessionElement('europe', 'closed');
updateSessionElement('us', 'closed');
}
});
}
function updateSessionElement(session, status) {
// Find session elements by region
let sessionCard;
let statusElement;
if (session === 'asia') {
sessionCard = document.querySelector('#sessions .section:nth-child(1) .session-card');
statusElement = sessionCard ? sessionCard.querySelector('.session-status') : null;
} else if (session === 'europe') {
sessionCard = document.querySelector('#sessions .section:nth-child(2) .session-card');
statusElement = sessionCard ? sessionCard.querySelector('.session-status') : null;
} else if (session === 'us') {
sessionCard = document.querySelector('#sessions .section:nth-child(3) .session-card');
statusElement = sessionCard ? sessionCard.querySelector('.session-status') : null;
}
if (statusElement) {
// Remove existing classes
statusElement.classList.remove('bg-green-500', 'bg-yellow-500', 'bg-gray-500');
// Add class based on status
if (status === 'active') {
statusElement.classList.add('bg-green-500');
statusElement.textContent = 'Aktiv';
} else if (status === 'upcoming') {
statusElement.classList.add('bg-yellow-500');
statusElement.textContent = 'Beginnt bald';
} else if (status === 'closed') {
statusElement.classList.add('bg-gray-500');
statusElement.textContent = 'Geschlossen';
}
}
// Update session times and countdown info
if (sessionCard) {
const timeInfo = sessionCard.querySelector('.mt-4 p.text-sm');
if (timeInfo) {
const now = new Date();
const hour = now.getHours();
const minute = now.getMinutes();
if (status === 'active') {
// Calculate time until session ends
let hoursLeft = 0;
let minutesLeft = 0;
if (session === 'asia') {
hoursLeft = 9 - hour;
if (hoursLeft < 0) hoursLeft += 24;
} else if (session === 'europe') {
hoursLeft = 16 - hour;
} else if (session === 'us') {
hoursLeft = 21 - hour;
}
minutesLeft = 60 - minute;
if (minutesLeft === 60) {
minutesLeft = 0;
} else {
hoursLeft -= 1;
}
timeInfo.textContent = `Aktive Session läuft noch ${hoursLeft}h ${minutesLeft}min`;
} else if (status === 'upcoming') {
// Calculate time until session starts
let hoursLeft = 0;
let minutesLeft = 0;
if (session === 'asia') {
hoursLeft = 24 - hour;
} else if (session === 'europe') {
hoursLeft = 8 - hour;
if (hoursLeft < 0) hoursLeft += 24;
} else if (session === 'us') {
hoursLeft = 14 - hour;
if (hoursLeft < 0) hoursLeft += 24;
}
if (minute > 0) {
hoursLeft -= 1;
minutesLeft = 60 - minute;
}
timeInfo.textContent = `Session beginnt in ${hoursLeft}h ${minutesLeft}min`;
} else {
// Calculate time until next session
let hoursLeft = 0;
let minutesLeft = 0;
if (session === 'asia') {
hoursLeft = 24 - hour;
} else if (session === 'europe') {
hoursLeft = 8 - hour;
if (hoursLeft < 0) hoursLeft += 24;
} else if (session === 'us') {
hoursLeft = 14 - hour;
if (hoursLeft < 0) hoursLeft += 24;
}
if (minute > 0) {
hoursLeft -= 1;
minutesLeft = 60 - minute;
}
timeInfo.textContent = `Nächste Session beginnt in ${hoursLeft}h ${minutesLeft}min`;
}
}
}
}
function updateCountdowns(now) {
// Update any countdown timers in the UI
// This is a placeholder for actual countdown logic
}
// Fetch and update ticker from API
function fetchAndUpdateTicker() {
fetch('/api/ticker?symbols=AAPL,NVDA,ASML,BNBUSDT,INTC,BTCUSD,XAUUSD,USDJPY,GER40,EURUSD')
.then(response => response.json())
.then(data => {
updateTickerUI(data);
})
.catch(error => {
console.error('Error fetching ticker data:', error);
// Fallback to randomized data on error
updateTickerWithRandomData();
});
}
// Update ticker UI with real data
function updateTickerUI(data) {
const tickerContainer = document.querySelector('.ticker-content');
if (!tickerContainer) return;
// Clear current ticker items
tickerContainer.innerHTML = '';
// Add ticker items from API data
data.forEach(item => {
const tickerItem = document.createElement('div');
tickerItem.className = `ticker-item ${item.direction}`;
const symbolPrefix = getSymbolPrefix(item.symbol);
tickerItem.innerHTML = `${symbolPrefix}:${item.symbol} <span>${item.price.toFixed(2)}</span>
<i class="fas fa-caret-${item.direction}"></i> ${item.change_percent.toFixed(1)}%`;
tickerContainer.appendChild(tickerItem);
});
}
// Get symbol prefix for ticker display
function getSymbolPrefix(symbol) {
const prefixMap = {
'AAPL': 'NASDAQ',
'NVDA': 'NASDAQ',
'ASML': 'NASDAQ',
'INTC': 'NASDAQ',
'BNBUSDT': 'BINANCE',
'BTCUSD': 'CAPITALCOM',
'XAUUSD': 'PEPPERSTONE',
'USDJPY': 'FX',
'GER40': 'PEPPERSTONE',
'EURUSD': 'PEPPERSTONE'
};
return prefixMap[symbol] || 'SYMBOL';
}
// Fallback to randomized data if API fails
function updateTickerWithRandomData() {
const tickerItems = document.querySelectorAll('.ticker-item');
tickerItems.forEach(item => {
// Simulate price change
const randomChange = (Math.random() * 0.2 - 0.1).toFixed(2);
const currentValue = parseFloat(item.querySelector('span').textContent);
const newValue = (currentValue * (1 + randomChange / 100)).toFixed(2);
item.querySelector('span').textContent = newValue;
// Update direction indicator
if (randomChange > 0) {
item.classList.remove('down');
item.classList.add('up');
item.querySelector('i').className = 'fas fa-caret-up';
} else {
item.classList.remove('up');
item.classList.add('down');
item.querySelector('i').className = 'fas fa-caret-down';
}
// Update percentage
const percentEl = item.querySelector('i').nextSibling;
percentEl.textContent = ` ${Math.abs(randomChange)}%`;
});
}
// Affirmation functions
function updateAffirmation() {
const status = document.getElementById('traderStatus').value;
let affirmationText = '';
let categoryText = '';
switch (status) {
case 'preparing':
affirmationText = 'Ich bereite mich gründlich vor und analysiere den Markt mit Klarheit und Fokus. Ich warte geduldig auf hochwertige Setups und halte mich an meine Handelsstrategie.';
categoryText = 'Geduld und Vorbereitung';
break;
case 'active':
affirmationText = 'Ich bleibe ruhig und diszipliniert während mein Trade läuft. Ich halte mich an meinen Plan und lasse keine Emotionen meine Entscheidungen beeinflussen.';
categoryText = 'Emotionale Kontrolle';
break;
case 'developing':
affirmationText = 'Ich entwickle meine Strategie mit Klarheit und Weisheit. Ich ziehe Lehren aus vergangenen Trades und verbessere kontinuierlich meine Fähigkeiten.';
categoryText = 'Strategische Entwicklung';
break;
case 'break':
affirmationText = 'Ich nehme mir bewusst Zeit für Erholung und Reflexion. Diese Pause stärkt meine Handelsleistung und schärft meinen Fokus.';
categoryText = 'Erholung und Reflexion';
break;
}
document.getElementById('currentAffirmation').textContent = affirmationText;
document.getElementById('affirmationCategory').textContent = categoryText;
}
// Add the rest of your JavaScript functions here
// Remaining functions are from the original code: updateAffirmationTab, startAffirmationTimer, pauseAffirmationTimer,
// resetAffirmationTimer, saveCurrentAffirmation, generateOpportunity, etc.
// Chat functions
function toggleChat() {
const chatPopup = document.getElementById('chatPopup');
const chevron = document.getElementById('chatChevron');
if (chatPopup.classList.contains('minimized')) {
chatPopup.classList.remove('minimized');
chevron.className = 'fas fa-chevron-down';
} else {
chatPopup.classList.add('minimized');
chevron.className = 'fas fa-chevron-up';
}
}
function sendChatMessage() {
const chatInput = document.getElementById('chatInput');
const message = chatInput.value.trim();
if (!message) return;
// Add user message
addChatMessage('user', message);
// Clear input
chatInput.value = '';
// Check API connection
if (!apiConnected) {
addChatMessage('ai', 'Bitte verbinde zuerst die Gemini API, um mit dem Chat zu interagieren.');
return;
}
// Show typing indicator
showTypingIndicator();
// In a real implementation, you would make an API call to Gemini here
// For this demo, we'll simulate a response
setTimeout(() => {
// Remove typing indicator
removeTypingIndicator();
// Generate response
const response = generateChatResponse(message);
// Add AI message
addChatMessage('ai', response);
// Scroll to bottom
scrollChatToBottom();
}, 1500);
}
// Affirmation Timer functions
function startAffirmationTimer() {
if (affirmationTimerRunning) return;
document.getElementById('startTimerBtn').disabled = true;
document.getElementById('pauseTimerBtn').disabled = false;
affirmationTimerRunning = true;
affirmationTimerInterval = setInterval(() => {
affirmationTimeLeft--;
const minutes = Math.floor(affirmationTimeLeft / 60);
const seconds = affirmationTimeLeft % 60;
document.getElementById('affirmationTimer').textContent =
`${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
if (affirmationTimeLeft <= 0) {
clearInterval(affirmationTimerInterval);
affirmationTimerRunning = false;
document.getElementById('startTimerBtn').disabled = false;
document.getElementById('pauseTimerBtn').disabled = true;
document.getElementById('affirmationTimer').textContent = "00:00";
// Play sound or notification
// playTimerEndSound();
}
}, 1000);
}
function pauseAffirmationTimer() {
clearInterval(affirmationTimerInterval);
affirmationTimerRunning = false;
document.getElementById('startTimerBtn').disabled = false;
document.getElementById('pauseTimerBtn').disabled = true;
}
function resetAffirmationTimer() {
clearInterval(affirmationTimerInterval);
affirmationTimerRunning = false;
affirmationTimeLeft = 300; // Reset to 5 minutes
document.getElementById('affirmationTimer').textContent = "05:00";
document.getElementById('startTimerBtn').disabled = false;
document.getElementById('pauseTimerBtn').disabled = true;
}
function saveCurrentAffirmation() {
const affirmationText = document.getElementById('detailedAffirmation').querySelector('.affirmation-text').textContent;
const categoryText = document.getElementById('detailedAffirmation').querySelector('.affirmation-category').textContent;
// Create a shortened version
const shortAffirmation = affirmationText.substring(0, 60) + (affirmationText.length > 60 ? '...' : '');
// Create new element
const newSavedAffirmation = document.createElement('div');
newSavedAffirmation.className = 'event-item';
newSavedAffirmation.innerHTML = `
<div class="font-medium">${shortAffirmation}</div>
<div class="text-sm text-gray-600">Kategorie: ${categoryText}</div>
`;
// Add to saved affirmations
const savedAffirmationsContainer = document.getElementById('savedAffirmations');
savedAffirmationsContainer.prepend(newSavedAffirmation);
// Show success message
alert('Affirmation gespeichert!');
}
// Update Affirmation Tab
function updateAffirmationTab() {
const status = document.getElementById('affirmationTraderStatus').value;
const category = document.getElementById('affirmationCategory').value;
// Map of affirmations based on status and category
const affirmations = {
discipline: {
preparing: 'Ich bin ein disziplinierter und geduldiger Trader, der seinem Handelsplan mit unerschütterlichem Engagement folgt. Ich vertraue auf die Wirksamkeit meiner Strategien und warte geduldig auf Setups mit hoher Wahrscheinlichkeit. Ich habe die Selbstkontrolle, mich an meine etablierten Regeln zu halten und impulsive Handlungen zu vermeiden.',
active: 'Während mein Trade aktiv ist, bleibe ich diszipliniert und geduldig. Ich folge meinem Plan und erlaube keiner Emotion, meine Strategie zu untergraben. Ich bin ruhig und kontrolliert, selbst wenn der Markt volatil wird.',
developing: 'Beim Entwickeln meiner Strategie wende ich Disziplin und Geduld an. Ich nehme mir die Zeit, jedes Detail zu durchdenken und teste gründlich, bevor ich handele. Qualität geht vor Schnelligkeit.',
break: 'In dieser Pause pflege ich meine Disziplin und Geduld, indem ich reflektiere und lerne. Ich verstehe, dass Ruhezeiten wesentlich für nachhaltigen Trading-Erfolg sind.'
},
abundance: {
preparing: 'Ich ziehe reichlich Handelsmöglichkeiten an, die mit meiner Strategie übereinstimmen. Der Markt bietet einen endlosen Strom von Gelegenheiten, und ich bin bereit, sie zu nutzen.',
active: 'Mein aktueller Trade ist eine von vielen Gelegenheiten für Wohlstand. Ich denke in Fülle und weiß, dass unabhängig vom Ausgang dieses Trades weitere profitable Chancen folgen werden.',
developing: 'Ich entwickle meine Strategie mit einer Überfluss-Denkweise. Ich erkenne die unbegrenzten Möglichkeiten des Marktes an und erschaffe einen Ansatz, der diesen Reichtum anzieht.',
break: 'Während dieser Pause ziehe ich neue Erkenntnisse und Möglichkeiten an. Ich nutze diese Zeit, um meine Überfluss-Denkweise zu stärken und mich auf neue Handelschancen vorzubereiten.'
}
// Additional categories would be added here
};
// Get the appropriate affirmation or default
let affirmationText = 'Ich handle mit Klarheit, Disziplin und Vertrauen.';
if (affirmations[category] && affirmations[category][status]) {
affirmationText = affirmations[category][status];
}
// Update the display
document.getElementById('detailedAffirmation').querySelector('.affirmation-text').textContent = affirmationText;
// Update the category display
let categoryDisplayText = '';
switch (category) {
case 'discipline': categoryDisplayText = 'Disziplin und Geduld entwickeln'; break;
case 'abundance': categoryDisplayText = 'Überflussdenken fördern'; break;
case 'selection': categoryDisplayText = 'Handelsauswahl verbessern'; break;
case 'burnout': categoryDisplayText = 'Burnout und Erschöpfung überwinden'; break;
case 'bias': categoryDisplayText = 'Bestätigungsfehler überwinden'; break;
case 'paralysis': categoryDisplayText = 'Entscheidungslähmung überwinden'; break;
case 'fomo': categoryDisplayText = 'FOMO überwinden'; break;
case 'losses': categoryDisplayText = 'Verluste schnell akzeptieren'; break;
case 'emotional': categoryDisplayText = 'Emotionale Bindung an Trades lösen'; break;
case 'overtrading': categoryDisplayText = 'Überhandel widerstehen'; break;
case 'patience': categoryDisplayText = 'Geduld bei langsamen Märkten bewahren'; break;
default: categoryDisplayText = 'Allgemeine Trading-Affirmation';
}
document.getElementById('detailedAffirmation').querySelector('.affirmation-category').textContent = categoryDisplayText;
}
// Trading opportunity functions
function generateOpportunity() {
const symbol = document.getElementById('opportunitySymbol').value;
if (!symbol) {
alert('Bitte wähle ein Symbol aus.');
return;
}
if (!apiConnected) {
alert('Bitte verbinde zuerst die Gemini API.');
return;
}
// Get other parameters
const timeframe = document.getElementById('opportunityTimeframe').value;
const style = document.getElementById('opportunityStyle').value;
const instructions = document.getElementById('opportunityInstructions').value;
// Show loading state
document.getElementById('analyzeText').textContent = 'Analysiere...';
document.getElementById('opportunitySpinner').style.display = 'inline-block';
// Simulate API call (in a real implementation, you'd call the Gemini API)
setTimeout(() => {
// Reset button
document.getElementById('analyzeText').textContent = 'Trading Opportunity analysieren';
document.getElementById('opportunitySpinner').style.display = 'none';
// Generate result
const result = generateOpportunityResult(symbol, timeframe, style, instructions);
// Display result
document.getElementById('opportunityResults').innerHTML = result;
}, 3000);
}
function generateOpportunityResult(symbol, timeframe, style, instructions) {
// This is a simulation - in production this would come from the Gemini API
// Extract symbol name
const symbolName = symbol.split(':')[1];
// Determine direction (random for demo)
const isLong = Math.random() > 0.5;
// Generate fictional analysis
let analysis = '';
let technicalInsights = '';
let fundamentalInsights = '';
let tradeSetup = '';
// Technical insights
if (style === 'technical' || style === 'combined') {
const patterns = ['Double Bottom', 'Bull Flag', 'Cup and Handle', 'Descending Triangle', 'Head and Shoulders'];
const indicators = ['RSI', 'MACD', 'Moving Average', 'Bollinger Bands', 'Fibonacci Retracement'];
const pattern = patterns[Math.floor(Math.random() * patterns.length)];
const indicator1 = indicators[Math.floor(Math.random() * indicators.length)];
const indicator2 = indicators[Math.floor(Math.random() * indicators.length)];
technicalInsights = `<p class="mb-3"><strong>Technische Analyse:</strong> ${symbolName} zeigt ein ${pattern}-Muster, das auf eine potenzielle ${isLong ? 'Aufwärts' : 'Abwärts'}bewegung hindeutet. Der ${indicator1} ist ${isLong ? 'überverkauft' : 'überkauft'}, während der ${indicator2} ein ${isLong ? 'bullisches' : 'bärisches'} Signal gibt.</p>`;
}
// Fundamental insights
if (style === 'fundamental' || style === 'combined') {
fundamentalInsights = `<p class="mb-3"><strong>Fundamentale Analyse:</strong> ${symbolName} ${isLong ? 'profitiert von positiven Branchentrends und zeigt starkes Gewinnwachstum' : 'steht vor Herausforderungen durch Branchendruck und Margenschwäche'}. Bevorstehende Ereignisse könnten ${isLong ? 'positive' : 'negative'} Auswirkungen auf den Kurs haben.</p>`;
}
// Trade setup
const currentPrice = Math.random() * 1000;
const stopLoss = isLong ? currentPrice * 0.95 : currentPrice * 1.05;
const takeProfit = isLong ? currentPrice * 1.1 : currentPrice * 0.9;
tradeSetup = `
<div class="p-3 bg-gray-50 rounded-lg mt-4">
<h4 class="font-semibold mb-2">Trade Setup</h4>
<div class="grid grid-cols-2 gap-3 text-sm">
<div>
<div class="text-gray-600">Richtung:</div>
<div class="font-medium">${isLong ? 'Long (Kaufen)' : 'Short (Verkaufen)'}</div>
</div>
<div>
<div class="text-gray-600">Einstieg:</div>
<div class="font-medium">${currentPrice.toFixed(2)}</div>
</div>
<div>
<div class="text-gray-600">Stop-Loss:</div>
<div class="font-medium">${stopLoss.toFixed(2)}</div>
</div>
<div>
<div class="text-gray-600">Take-Profit:</div>
<div class="font-medium">${takeProfit.toFixed(2)}</div>
</div>
<div>
<div class="text-gray-600">Risk/Reward:</div>
<div class="font-medium">1:${isLong ? '2' : '3'}</div>
</div>
<div>
<div class="text-gray-600">Zeitrahmen:</div>
<div class="font-medium">${timeframe === 'shortTerm' ? 'Kurzfristig (1-3 Tage)' : timeframe === 'mediumTerm' ? 'Mittelfristig (1-2 Wochen)' : 'Langfristig (1+ Monate)'}</div>
</div>
</div>
</div>
`;
// Build the full analysis
analysis = `
<div>
<div class="mb-4 flex justify-between items-start">
<div>
<h3 class="font-semibold text-lg">${symbol}</h3>
<div class="text-sm text-gray-600">${new Date().toLocaleString()}</div>
</div>
<div class="badge ${isLong ? 'badge-success' : 'badge-danger'}">${isLong ? 'Long' : 'Short'}</div>
</div>
${technicalInsights}
${fundamentalInsights}
<p class="mb-4">
<strong>Analyse:</strong> Basierend auf ${style === 'technical' ? 'technischer Analyse' : style === 'fundamental' ? 'fundamentaler Analyse' : 'technischer und fundamentaler Analyse'}
erscheint ${symbolName} als ${isLong ? 'attraktive Long-Opportunity' : 'potentielle Short-Position'} für den ${timeframe === 'shortTerm' ? 'kurzfristigen' : timeframe === 'mediumTerm' ? 'mittelfristigen' : 'langfristigen'} Handel.
</p>
${tradeSetup}
<div class="mt-6 flex justify-end gap-3">
<button class="btn-primary text-sm" onclick="saveOpportunity()">Speichern</button>
<button class="btn-primary text-sm" onclick="createTradeFromOpportunity()">Trade erstellen</button>
</div>
</div>
`;
return analysis;
}
function saveOpportunity() {
alert('Trading Opportunity gespeichert!');
}
function createTradeFromOpportunity() {
alert('Trade aus dieser Opportunity wird erstellt. Bitte bestätige die Details im "Meine Trades" Bereich.');
// Switch to the My Trades tab
document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
document.querySelector('[data-tab="mytrades"]').classList.add('active');
document.getElementById('mytrades').classList.add('active');
}
// Chat helper functions
function handleChatKeyPress(event) {
if (event.key === 'Enter') {
sendChatMessage();
}
}
function addChatMessage(sender, text) {
const chatBody = document.getElementById('chatBody');
const messageDiv = document.createElement('div');
messageDiv.className = `chat-message ${sender}`;
messageDiv.innerHTML = `
<div class="message-content">${text}</div>
`;
chatBody.appendChild(messageDiv);
// Expand chat if minimized
if (document.getElementById('chatPopup').classList.contains('minimized')) {
toggleChat();
}
// Scroll to bottom
scrollChatToBottom();
}
function scrollChatToBottom() {
const chatBody = document.getElementById('chatBody');
chatBody.scrollTop = chatBody.scrollHeight;
}
function showTypingIndicator() {
const chatBody = document.getElementById('chatBody');
const typingDiv = document.createElement('div');
typingDiv.className = 'chat-message ai';
typingDiv.id = 'typingIndicator';
typingDiv.innerHTML = `
<div class="message-content">
<div class="typing-indicator">
<span></span>
<span></span>
<span></span>
</div>
</div>
`;
chatBody.appendChild(typingDiv);
scrollChatToBottom();
}
function removeTypingIndicator() {
const typingIndicator = document.getElementById('typingIndicator');
if (typingIndicator) {
typingIndicator.remove();
}
}
function generateChatResponse(message) {
// This is a simulation - in production this would come from the Gemini API
// Simple pattern matching for demo
if (message.toLowerCase().includes('hallo') || message.toLowerCase().includes('hi')) {
return 'Hallo! Wie kann ich dir bei deinem Trading heute helfen?';
} else if (message.toLowerCase().includes('market') || message.toLowerCase().includes('markt')) {
return 'Die Märkte zeigen heute gemischte Signale. US-Indizes sind leicht im Plus, während europäische Märkte sich seitwärts bewegen. Gold steigt aufgrund geopolitischer Spannungen.';
} else if (message.toLowerCase().includes('affirmation')) {
return 'Affirmationen können deine Trading-Psychologie stark verbessern. Ich empfehle dir, täglich 5 Minuten für Affirmationen einzuplanen, besonders vor Handelssessions oder nach Verlusten.';
} else if (message.toLowerCase().includes('verlust') || message.toLowerCase().includes('loss')) {
return 'Verluste sind ein normaler Teil des Tradings. Das Wichtigste ist, wie du darauf reagierst. Halte dich an dein Risikomanagement und betrachte jeden Verlust als Lernchance.';
} else if (message.toLowerCase().includes('strategie') || message.toLowerCase().includes('strategy')) {
return 'Eine erfolgreiche Trading-Strategie sollte klare Ein- und Ausstiegskriterien, Risikomanagement und ein positives Erwartungswert haben. Möchtest du Hilfe bei einem bestimmten Aspekt deiner Strategie?';
} else {
return 'Danke für deine Nachricht. Ich kann dir bei Trading-Analysen, Affirmationen, Marktinformationen und Handelsstrategien helfen. Was interessiert dich am meisten?';
}
}
// Trade management functions
function addNewTrade() {
const symbol = document.getElementById('newTradeSymbol').value;
if (!symbol) {
alert('Bitte wähle ein Symbol aus.');
return;
}
const entry = document.getElementById('newTradeEntry').value;
if (!entry) {
alert('Bitte gib einen Einstiegspreis ein.');
return;
}
const direction = document.getElementById('newTradeDirection').value;
const stop = document.getElementById('newTradeStop').value;
const target = document.getElementById('newTradeTarget').value;
const position = document.getElementById('newTradePosition').value;
const notes = document.getElementById('newTradeNotes').value;
// Create trade element
const tradeElement = document.createElement('div');
tradeElement.className = 'trade-item';
// Random P&L for demo
const pnl = ((Math.random() * 2) - 0.5).toFixed(2);
const isProfitable = parseFloat(pnl) > 0;
tradeElement.innerHTML = `
<div class="trade-symbol">${symbol}</div>
<div class="trade-details">${direction === 'long' ? 'Long' : 'Short'} @ ${entry} • Stop: ${stop} • Target: ${target}</div>
<div class="trade-pnl ${isProfitable ? 'profit' : 'loss'}">${pnl > 0 ? '+' : ''}${pnl}%</div>
<div class="text-sm text-gray-500 mt-2">Eröffnet: ${new Date().toLocaleString()}</div>
${notes ? `
<div class="mt-3 text-sm">
<div class="font-medium">Notizen:</div>
<p class="text-gray-600">${notes}</p>
</div>
` : ''}
<div class="trade-actions">
<button class="btn-primary text-xs py-1">Bearbeiten</button>
<button class="btn-danger text-xs py-1" onclick="removeTrade(this)">Entfernen</button>
</div>
`;
// Add to trades list
document.getElementById('tradesList').prepend(tradeElement);
// Clear form
document.getElementById('newTradeSymbol').value = '';
document.getElementById('newTradeEntry').value = '';
document.getElementById('newTradeStop').value = '';
document.getElementById('newTradeTarget').value = '';
document.getElementById('newTradePosition').value = '';
document.getElementById('newTradeNotes').value = '';
// Update trade count and statistics
updateTradeStatistics();
// Show notification
alert('Trade erfolgreich hinzugefügt!');
}
function removeTrade(button) {
// Find the parent trade item and remove it
const tradeItem = button.closest('.trade-item');
tradeItem.style.opacity = '0.5';
// Simulate a delay before removal
setTimeout(() => {
tradeItem.remove();
// Update statistics
updateTradeStatistics();
// Show notification
alert('Trade entfernt!');
}, 500);
}
function updateTradeStatistics() {
// This would calculate real statistics in production
// For demo, we'll just update the count
const tradeCount = document.querySelectorAll('.trade-item').length;
// Update the trade count in the statistics
// This assumes there's an element to update
}
function updateActiveTrades() {
// In a real implementation, this would fetch actual trade data
// For demo, we'll randomly update P&L
const tradeItems = document.querySelectorAll('.trade-item');
tradeItems.forEach(item => {
const pnlElement = item.querySelector('.trade-pnl');
if (pnlElement) {
// Get current value
const currentValue = parseFloat(pnlElement.textContent.replace('%', '').replace('+', ''));
// Small random change
const change = (Math.random() * 0.2) - 0.1;
const newValue = (currentValue + change).toFixed(2);
// Update display
const isProfit = parseFloat(newValue) > 0;
pnlElement.className = `trade-pnl ${isProfit ? 'profit' : 'loss'}`;
pnlElement.textContent = `${isProfit ? '+' : ''}${newValue}%`;
}
});
}
// Sort trades based on user selection
function sortTrades() {
const sortOption = document.getElementById('tradeSortOption').value;
const tradesList = document.getElementById('tradesList');
const trades = Array.from(tradesList.querySelectorAll('.trade-item'));
// Clear the container
tradesList.innerHTML = '';
// Sort trades based on option
switch (sortOption) {
case 'newest':
// Just reverse the current order for demo
trades.reverse();
break;
case 'oldest':
// Keep current order for demo
break;
case 'profit':
trades.sort((a, b) => {
const aPnl = parseFloat(a.querySelector('.trade-pnl').textContent.replace('%', '').replace('+', ''));
const bPnl = parseFloat(b.querySelector('.trade-pnl').textContent.replace('%', '').replace('+', ''));
return bPnl - aPnl; // Descending
});
break;
case 'loss':
trades.sort((a, b) => {
const aPnl = parseFloat(a.querySelector('.trade-pnl').textContent.replace('%', '').replace('+', ''));
const bPnl = parseFloat(b.querySelector('.trade-pnl').textContent.replace('%', '').replace('+', ''));
return aPnl - bPnl; // Ascending
});
break;
}
// Add sorted trades back to container
trades.forEach(trade => tradesList.appendChild(trade));
}
function refreshTrades() {
updateActiveTrades();
alert('Trades aktualisiert!');
}
// Update intermarket analysis
function updateIntermarketAnalysis() {
const stockIndex = document.getElementById('stockIndex').value;
const bondIndex = document.getElementById('bondIndex').value;
const commodityIndex = document.getElementById('commodityIndex').value;
const currencyIndex = document.getElementById('currencyIndex').value;
// In a real implementation, you would fetch data for these symbols
alert(`Intermarket-Analyse wird aktualisiert mit: ${stockIndex}, ${bondIndex}, ${commodityIndex}, ${currencyIndex}`);
// Simulate loading data
fetch('/api/intermarket')
.then(response => response.json())
.then(data => {
updateIntermarketDisplay(data);
})
.catch(error => {
console.error('Error updating intermarket analysis:', error);
});
} |