// ==========================================
// BINARYTRADE PRO - PLATAFORMA COMPLETA
// ==========================================
// Configurações globais
const CONFIG = {
DEMO_BALANCE: 10000,
MIN_TRADE: 1,
MAX_TRADE: 50000,
DEFAULT_RETURN: 0.87, // 87% de retorno
UPDATE_INTERVAL: 1000, // 1 segundo
CHART_POINTS: 100
};
// Estado da aplicação
const state = {
user: null,
balance: CONFIG.DEMO_BALANCE,
totalProfit: 0,
isDemo: true,
currentAsset: 'BTCUSD',
currentPrice: 43250.50,
activeTrades: [],
tradeHistory: [],
chartType: 'candlestick',
timeframe: '1m',
assets: {},
candles: [],
lastUpdate: Date.now()
};
// Dados dos ativos
const ASSETS_DATA = {
// Criptomoedas
BTCUSD: { name: 'Bitcoin', category: 'crypto', basePrice: 43250.50, volatility: 0.002, icon: 'bitcoin' },
ETHUSD: { name: 'Ethereum', category: 'crypto', basePrice: 2280.30, volatility: 0.0025, icon: 'coins' },
LTCUSD: { name: 'Litecoin', category: 'crypto', basePrice: 72.45, volatility: 0.003, icon: 'coins' },
XRPUSD: { name: 'Ripple', category: 'crypto', basePrice: 0.62, volatility: 0.004, icon: 'coins' },
ADAUSD: { name: 'Cardano', category: 'crypto', basePrice: 0.58, volatility: 0.0035, icon: 'coins' },
DOTUSD: { name: 'Polkadot', category: 'crypto', basePrice: 7.25, volatility: 0.003, icon: 'coins' },
// Forex
EURUSD: { name: 'EUR/USD', category: 'forex', basePrice: 1.0850, volatility: 0.0003, icon: 'banknote' },
GBPUSD: { name: 'GBP/USD', category: 'forex', basePrice: 1.2650, volatility: 0.0004, icon: 'banknote' },
USDJPY: { name: 'USD/JPY', category: 'forex', basePrice: 148.50, volatility: 0.00035, icon: 'banknote' },
AUDUSD: { name: 'AUD/USD', category: 'forex', basePrice: 0.6580, volatility: 0.0005, icon: 'banknote' },
USDCAD: { name: 'USD/CAD', category: 'forex', basePrice: 1.3520, volatility: 0.0004, icon: 'banknote' },
USDCHF: { name: 'USD/CHF', category: 'forex', basePrice: 0.8840, volatility: 0.00045, icon: 'banknote' },
// Ações
AAPL: { name: 'Apple Inc.', category: 'stocks', basePrice: 195.50, volatility: 0.0015, icon: 'smartphone' },
GOOGL: { name: 'Alphabet Inc.', category: 'stocks', basePrice: 142.30, volatility: 0.0018, icon: 'search' },
TSLA: { name: 'Tesla Inc.', category: 'stocks', basePrice: 248.50, volatility: 0.0025, icon: 'car' },
AMZN: { name: 'Amazon.com', category: 'stocks', basePrice: 155.20, volatility: 0.0016, icon: 'package' },
MSFT: { name: 'Microsoft', category: 'stocks', basePrice: 378.90, volatility: 0.0012, icon: 'monitor' },
META: { name: 'Meta Platforms', category: 'stocks', basePrice: 505.30, volatility: 0.002, icon: 'facebook' },
NVDA: { name: 'NVIDIA', category: 'stocks', basePrice: 875.30, volatility: 0.0022, icon: 'cpu' },
// Commodities
XAUUSD: { name: 'Ouro', category: 'commodities', basePrice: 2035.50, volatility: 0.0008, icon: 'gem' },
XAGUSD: { name: 'Prata', category: 'commodities', basePrice: 22.85, volatility: 0.0012, icon: 'gem' },
USOIL: { name: 'Petróleo WTI', category: 'commodities', basePrice: 76.50, volatility: 0.0015, icon: 'fuel' },
BRENT: { name: 'Petróleo Brent', category: 'commodities', basePrice: 81.20, volatility: 0.0014, icon: 'fuel' },
NATGAS: { name: 'Gás Natural', category: 'commodities', basePrice: 2.85, volatility: 0.003, icon: 'flame' }
};
// ==========================================
// AUTENTICAÇÃO
// ==========================================
const auth = {
init() {
// Verificar sessão salva
const saved = localStorage.getItem('binarytrade_user');
if (saved) {
const user = JSON.parse(saved);
this.loginUser(user);
}
},
showLogin() {
document.getElementById('login-form').classList.remove('hidden');
document.getElementById('register-form').classList.add('hidden');
},
showRegister() {
document.getElementById('login-form').classList.add('hidden');
document.getElementById('register-form').classList.remove('hidden');
},
login() {
const email = document.getElementById('login-email').value;
const password = document.getElementById('login-password').value;
if (!email || !password) {
app.showToast('Preencha todos os campos', 'error');
return;
}
// Simular login
const user = {
id: Date.now(),
email: email,
name: email.split('@')[0],
isDemo: false
};
this.loginUser(user);
},
demoLogin() {
const user = {
id: Date.now(),
email: 'demo@binarytrade.pro',
name: 'Demo User',
isDemo: true
};
state.isDemo = true;
state.balance = CONFIG.DEMO_BALANCE;
this.loginUser(user);
},
register() {
const name = document.getElementById('register-name').value;
const email = document.getElementById('register-email').value;
const password = document.getElementById('register-password').value;
if (!name || !email || !password) {
app.showToast('Preencha todos os campos', 'error');
return;
}
const user = {
id: Date.now(),
email: email,
name: name,
isDemo: false
};
state.isDemo = false;
state.balance = 0;
this.loginUser(user);
},
loginUser(user) {
state.user = user;
localStorage.setItem('binarytrade_user', JSON.stringify(user));
document.getElementById('auth-screen').classList.add('hidden');
document.getElementById('trading-platform').classList.remove('hidden');
app.init();
app.showToast(`Bem-vindo, ${user.name}!`, 'success');
},
logout() {
state.user = null;
localStorage.removeItem('binarytrade_user');
location.reload();
}
};
// ==========================================
// GERENCIAMENTO DE ATIVOS
// ==========================================
const assets = {
currentCategory: 'all',
init() {
// Inicializar preços dos ativos
Object.keys(ASSETS_DATA).forEach(symbol => {
state.assets[symbol] = {
...ASSETS_DATA[symbol],
price: ASSETS_DATA[symbol].basePrice,
change: 0,
changePercent: 0
};
});
this.renderList();
this.renderMobileSelect();
},
filter(search) {
const term = search.toLowerCase();
const items = document.querySelectorAll('.asset-item');
items.forEach(item => {
const name = item.dataset.name.toLowerCase();
const symbol = item.dataset.symbol.toLowerCase();
const match = name.includes(term) || symbol.includes(term);
item.style.display = match ? 'block' : 'none';
});
},
setCategory(category) {
this.currentCategory = category;
// Atualizar UI
document.querySelectorAll('.sidebar-item').forEach(el => {
el.classList.remove('active');
});
event.target.closest('.sidebar-item').classList.add('active');
this.renderList();
},
renderList() {
const container = document.getElementById('assets-list');
container.innerHTML = '';
Object.entries(state.assets).forEach(([symbol, data]) => {
if (this.currentCategory !== 'all' && data.category !== this.currentCategory) {
return;
}
const changeClass = data.change >= 0 ? 'text-green-400' : 'text-red-400';
const changeIcon = data.change >= 0 ? 'trending-up' : 'trending-down';
const item = document.createElement('button');
item.className = `asset-item w-full text-left p-3 rounded-lg hover:bg-white/10 transition flex items-center justify-between ${symbol === state.currentAsset ? 'bg-white/10 border-l-2 border-green-400' : ''}`;
item.dataset.symbol = symbol;
item.dataset.name = data.name;
item.onclick = () => this.select(symbol);
item.innerHTML = `
${this.formatPrice(data.price)}
${data.changePercent >= 0 ? '+' : ''}${data.changePercent.toFixed(2)}%
`;
container.appendChild(item);
});
lucide.createIcons();
},
renderMobileSelect() {
const select = document.getElementById('mobile-asset-select');
select.innerHTML = '';
Object.entries(state.assets).forEach(([symbol, data]) => {
const option = document.createElement('option');
option.value = symbol;
option.textContent = `${symbol} - ${data.name}`;
select.appendChild(option);
});
select.value = state.currentAsset;
},
select(symbol) {
state.currentAsset = symbol;
const data = state.assets[symbol];
// Atualizar UI
document.getElementById('current-asset-name').textContent = `${symbol}`;
document.getElementById('current-asset-price').textContent = this.formatPrice(data.price);
const changeEl = document.getElementById('price-change');
changeEl.textContent = `${data.change >= 0 ? '+' : ''}${data.changePercent.toFixed(2)}%`;
changeEl.className = data.change >= 0 ? 'text-green-400 text-xs' : 'text-red-400 text-xs';
// Atualizar lista
this.renderList();
document.getElementById('mobile-asset-select').value = symbol;
// Resetar gráfico
chart.reset();
},
formatPrice(price) {
if (price >= 1000) {
return price.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
} else if (price >= 1) {
return price.toFixed(4);
} else {
return price.toFixed(6);
}
},
updatePrices() {
Object.keys(state.assets).forEach(symbol => {
const asset = state.assets[symbol];
const volatility = asset.volatility;
// Simular movimento de preço com random walk
const change = (Math.random() - 0.5) * 2 * volatility * asset.price;
const newPrice = asset.price + change;
asset.change = change;
asset.changePercent = (change / asset.price) * 100;
asset.price = Math.max(newPrice, 0.000001);
// Atualizar último preço se for o ativo atual
if (symbol === state.currentAsset) {
state.currentPrice = asset.price;
const priceEl = document.getElementById('current-asset-price');
priceEl.textContent = this.formatPrice(asset.price);
priceEl.classList.remove('price-up', 'price-down');
priceEl.classList.add(change >= 0 ? 'price-up' : 'price-down');
const changeEl = document.getElementById('price-change');
changeEl.textContent = `${asset.change >= 0 ? '+' : ''}${asset.changePercent.toFixed(2)}%`;
changeEl.className = asset.change >= 0 ? 'text-green-400 text-xs' : 'text-red-400 text-xs';
}
});
// Atualizar lista periodicamente
if (Date.now() - state.lastUpdate > 5000) {
this.renderList();
state.lastUpdate = Date.now();
}
}
};
// ==========================================
// GRÁFICOS
// ==========================================
const chart = {
instance: null,
candles: [],
init() {
const ctx = document.getElementById('trading-chart').getContext('2d');
// Gerar candles iniciais
this.generateCandles();
this.instance = new Chart(ctx, {
type: 'candlestick',
data: {
datasets: [{
label: state.currentAsset,
data: this.candles
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
animation: false,
interaction: {
intersect: false,
mode: 'index'
},
plugins: {
legend: { display: false },
tooltip: {
backgroundColor: 'rgba(0,0,0,0.8)',
titleColor: '#fff',
bodyColor: '#fff',
borderColor: 'rgba(255,255,255,0.1)',
borderWidth: 1
}
},
scales: {
x: {
type: 'time',
time: {
unit: 'minute'
},
grid: {
color: 'rgba(255,255,255,0.05)'
},
ticks: {
color: 'rgba(255,255,255,0.5)'
}
},
y: {
position: 'right',
grid: {
color: 'rgba(255,255,255,0.05)'
},
ticks: {
color: 'rgba(255,255,255,0.5)',
callback: (value) => assets.formatPrice(value)
}
}
}
}
});
// Atualizar em tempo real
setInterval(() => this.update(), CONFIG.UPDATE_INTERVAL);
},
generateCandles() {
const now = Date.now();
const asset = state.assets[state.currentAsset];
let price = asset.basePrice;
this.candles = [];
for (let i = CONFIG.CHART_POINTS; i >= 0; i--) {
const time = now - (i * 60000);
const volatility = asset.volatility * price;
const open = price;
const high = open + Math.random() * volatility;
const low = open - Math.random() * volatility;
const close = low + Math.random() * (high - low);
this.candles.push({
x: time,
o: open,
h: high,
l: low,
c: close
});
price = close;
}
state.currentPrice = price;
state.assets[state.currentAsset].price = price;
},
update() {
// Adicionar novo candle se necessário
const lastCandle = this.candles[this.candles.length - 1];
const now = Date.now();
const timeframe = this.getTimeframeMs();
if (now - lastCandle.x >= timeframe) {
// Novo candle
this.candles.push({
x: now,
o: state.currentPrice,
h: state.currentPrice,
l: state.currentPrice,
c: state.currentPrice
});
// Manter limite de candles
if (this.candles.length > CONFIG.CHART_POINTS) {
this.candles.shift();
}
} else {
// Atualizar candle atual
lastCandle.h = Math.max(lastCandle.h, state.currentPrice);
lastCandle.l = Math.min(lastCandle.l, state.currentPrice);
lastCandle.c = state.currentPrice;
}
// Atualizar gráfico
this.instance.data.datasets[0].data = this.candles;
this.instance.update('none');
},
getTimeframeMs() {
const map = {
'1m': 60000,
'5m': 300000,
'15m': 900000,
'1h': 3600000,
'4h': 14400000,
'1d': 86400000
};
return map[state.timeframe] || 60000;
},
setTimeframe(tf) {
state.timeframe = tf;
// Atualizar botões
document.querySelectorAll('.timeframe-btn').forEach(btn => {
btn.classList.remove('bg-green-500/20', 'text-green-400');
btn.classList.add('text-gray-400');
});
event.target.classList.add('bg-green-500/20', 'text-green-400');
event.target.classList.remove('text-gray-400');
this.reset();
},
setType(type) {
state.chartType = type;
// Destruir e recriar gráfico
this.instance.destroy();
const ctx = document.getElementById('trading-chart').getContext('2d');
let chartType = 'line';
let datasetConfig = {
label: state.currentAsset,
data: this.candles.map(c => ({ x: c.x, y: c.c })),
borderColor: '#00d084',
backgroundColor: type === 'area' ? 'rgba(0, 208, 132, 0.1)' : 'transparent',
fill: type === 'area',
tension: 0.1,
pointRadius: 0
};
if (type === 'candlestick') {
chartType = 'candlestick';
datasetConfig = {
label: state.currentAsset,
data: this.candles
};
}
this.instance = new Chart(ctx, {
type: chartType,
data: { datasets: [datasetConfig] },
options: {
responsive: true,
maintainAspectRatio: false,
animation: false,
interaction: {
intersect: false,
mode: 'index'
},
plugins: {
legend: { display: false }
},
scales: {
x: {
type: 'time',
grid: { color: 'rgba(255,255,255,0.05)' },
ticks: { color: 'rgba(255,255,255,0.5)' }
},
y: {
position: 'right',
grid: { color: 'rgba(255,255,255,0.05)' },
ticks: {
color: 'rgba(255,255,255,0.5)',
callback: (value) => assets.formatPrice(value)
}
}
}
}
});
},
reset() {
this.generateCandles();
this.setType(state.chartType);
}
};
// ==========================================
// NEGOCIAÇÃO
// ==========================================
const trading = {
updateProfit() {
const amount = parseFloat(document.getElementById('trade-amount').value) || 0;
const profit = amount * CONFIG.DEFAULT_RETURN;
const profitEl = document.getElementById('potential-profit');
profitEl.textContent = `+$${profit.toFixed(2)}`;
},
adjustAmount(delta) {
const input = document.getElementById('trade-amount');
let value = parseFloat(input.value) || 0;
value = Math.max(CONFIG.MIN_TRADE, value + delta);
input.value = value;
this.updateProfit();
},
placeTrade(direction) {
const amount = parseFloat(document.getElementById('trade-amount').value);
const duration = parseInt(document.getElementById('trade-duration').value);
// Validações
if (amount < CONFIG.MIN_TRADE) {
app.showToast(`Valor mínimo é $${CONFIG.MIN_TRADE}`, 'error');
return;
}
if (amount > CONFIG.MAX_TRADE) {
app.showToast(`Valor máximo é $${CONFIG.MAX_TRADE}`, 'error');
return;
}
if (amount > state.balance) {
app.showToast('Saldo insuficiente', 'error');
return;
}
// Verificar trades ativos no mesmo ativo
const activeOnAsset = state.activeTrades.filter(t => t.asset === state.currentAsset);
if (activeOnAsset.length >= 3) {
app.showToast('Limite de 3 operações simultâneas neste ativo', 'error');
return;
}
// Criar trade
const trade = {
id: Date.now(),
asset: state.currentAsset,
assetName: state.assets[state.currentAsset].name,
direction: direction,
amount: amount,
entryPrice: state.currentPrice,
duration: duration,
startTime: Date.now(),
endTime: Date.now() + (duration * 1000),
potentialProfit: amount * CONFIG.DEFAULT_RETURN,
status: 'active'
};
// Deduzir do saldo
state.balance -= amount;
app.updateBalance();
// Adicionar à lista
state.activeTrades.push(trade);
this.renderActiveTrades();
// Mostrar overlay
this.showTradeOverlay(trade);
// Agendar finalização
setTimeout(() => this.closeTrade(trade.id), duration * 1000);
app.showToast('Operação iniciada!', 'success');
},
showTradeOverlay(trade) {
const overlay = document.getElementById('active-trade-overlay');
overlay.classList.remove('hidden');
// Atualizar countdown
this.updateCountdown(trade);
},
updateCountdown(trade) {
const update = () => {
const now = Date.now();
const remaining = Math.max(0, trade.endTime - now);
const total = trade.duration * 1000;
const elapsed = total - remaining;
const progress = elapsed / total;
// Atualizar texto
const seconds = Math.ceil(remaining / 1000);
const mins = Math.floor(seconds / 60);
const secs = seconds % 60;
document.getElementById('countdown-time').textContent =
`${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
// Atualizar círculo
const circle = document.getElementById('countdown-circle');
const circumference = 2 * Math.PI * 14;
circle.style.strokeDashoffset = circumference * progress;
// Mudar cor quando perto de expirar
if (remaining < 10000) {
circle.style.stroke = '#ff4757';
}
if (remaining > 0 && state.activeTrades.find(t => t.id === trade.id)) {
requestAnimationFrame(update);
} else {
overlay.classList.add('hidden');
}
};
const overlay = document.getElementById('active-trade-overlay');
update();
},
closeTrade(tradeId) {
const tradeIndex = state.activeTrades.findIndex(t => t.id === tradeId);
if (tradeIndex === -1) return;
const trade = state.activeTrades[tradeIndex];
const exitPrice = state.currentPrice;
// Determinar resultado
let won = false;
if (trade.direction === 'call') {
won = exitPrice > trade.entryPrice;
} else {
won = exitPrice < trade.entryPrice;
}
// Calcular lucro/perda
let profit = 0;
if (won) {
profit = trade.amount + trade.potentialProfit;
state.balance += profit;
state.totalProfit += trade.potentialProfit;
}
// Atualizar trade
trade.status = won ? 'won' : 'lost';
trade.exitPrice = exitPrice;
trade.profit = won ? trade.potentialProfit : -trade.amount;
trade.closedAt = Date.now();
// Mover para histórico
state.activeTrades.splice(tradeIndex, 1);
state.tradeHistory.unshift(trade);
// Atualizar UI
app.updateBalance();
this.renderActiveTrades();
this.renderHistory();
// Mostrar resultado
this.showResult(trade, won, profit);
// Esconder overlay se não houver mais trades
if (state.activeTrades.length === 0) {
document.getElementById('active-trade-overlay').classList.add('hidden');
}
},
showResult(trade, won, profit) {
const modal = document.getElementById('result-modal');
const icon = document.getElementById('result-icon');
const title = document.getElementById('result-title');
const message = document.getElementById('result-message');
const amount = document.getElementById('result-amount');
if (won) {
icon.className = 'w-20 h-20 mx-auto mb-4 rounded-full flex items-center justify-center bg-green-500/20';
icon.innerHTML = '';
title.textContent = 'Lucro!';
title.className = 'text-2xl font-bold mb-2 text-green-400';
message.textContent = 'Sua operação foi bem-sucedida';
amount.textContent = `+$${profit.toFixed(2)}`;
amount.className = 'text-3xl font-bold text-green-400';
} else {
icon.className = 'w-20 h-20 mx-auto mb-4 rounded-full flex items-center justify-center bg-red-500/20';
icon.innerHTML = '';
title.textContent = 'Perda';
title.className = 'text-2xl font-bold mb-2 text-red-400';
message.textContent = 'Sua operação não foi bem-sucedida';
amount.textContent = `-$${trade.amount.toFixed(2)}`;
amount.className = 'text-3xl font-bold text-red-400';
}
lucide.createIcons();
modal.classList.remove('hidden');
},
renderActiveTrades() {
const container = document.getElementById('active-trades-list');
if (state.activeTrades.length === 0) {
container.innerHTML = `
Nenhuma operação ativa
Inicie uma negociação para começar
`;
lucide.createIcons();
return;
}
container.innerHTML = state.activeTrades.map(trade => {
const remaining = Math.max(0, trade.endTime - Date.now());
const seconds = Math.ceil(remaining / 1000);
const progress = ((trade.duration * 1000 - remaining) / (trade.duration * 1000)) * 100;
const directionColor = trade.direction === 'call' ? 'text-green-400' : 'text-red-400';
const directionIcon = trade.direction === 'call' ? 'arrow-up' : 'arrow-down';
const directionText = trade.direction === 'call' ? 'ALTA' : 'BAIXA';
return `
${trade.asset}
${trade.assetName}
${directionText}
Investimento
$${trade.amount.toFixed(2)}
Lucro Potencial
+$${trade.potentialProfit.toFixed(2)}
Entrada: ${assets.formatPrice(trade.entryPrice)}
Atual: ${assets.formatPrice(state.assets[trade.asset].price)}
`;
}).join('');
lucide.createIcons();
},
renderHistory() {
const container = document.getElementById('trade-history-list');
if (state.tradeHistory.length === 0) {
container.innerHTML = `
Sem histórico de operações
`;
lucide.createIcons();
return;
}
container.innerHTML = state.tradeHistory.slice(0, 20).map(trade => {
const won = trade.status === 'won';
const profitClass = won ? 'text-green-400' : 'text-red-400';
const profitSign = won ? '+' : '';
const directionColor = trade.direction === 'call' ? 'text-green-400' : 'text-red-400';
const directionIcon = trade.direction === 'call' ? 'arrow-up' : 'arrow-down';
const time = new Date(trade.closedAt).toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' });
return `
$${trade.amount.toFixed(2)} • ${trade.duration >= 60 ? (trade.duration/60) + 'm' : trade.duration + 's'}
${profitSign}$${Math.abs(trade.profit).toFixed(2)}
`;
}).join('');
lucide.createIcons();
}
};
// ==========================================
// APLICAÇÃO PRINCIPAL
// ==========================================
const app = {
init() {
// Inicializar módulos
assets.init();
chart.init();
trading.updateProfit();
// Atualizar preços em tempo real
setInterval(() => assets.updatePrices(), 1000);
// Atualizar trades ativos
setInterval(() => trading.renderActiveTrades(), 1000);
// Criar ícones
lucide.createIcons();
},
updateBalance() {
document.getElementById('balance-display').textContent =
'$' + state.balance.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
const profitEl = document.getElementById('total-profit');
profitEl.textContent = (state.totalProfit >= 0 ? '+' : '') + '$' + Math.abs(state.totalProfit).toFixed(2);
profitEl.className = 'font-bold text-lg ' + (state.totalProfit >= 0 ? 'profit-positive' : 'profit-negative');
},
setSidebarTab(tab) {
// Atualizar botões
document.getElementById('tab-trades').className = tab === 'trades' ? 'flex-1 py-3 text-sm font-medium tab-active' : 'flex-1 py-3 text-sm font-medium text-gray-400 hover:text-white transition';
document.getElementById('tab-history').className = tab === 'history' ? 'flex-1 py-3 text-sm font-medium tab-active' : 'flex-1 py-3 text-sm font-medium text-gray-400 hover:text-white transition';
// Mostrar conteúdo
document.getElementById('sidebar-trades').classList.toggle('hidden', tab !== 'trades');
document.getElementById('sidebar-history').classList.toggle('hidden', tab !== 'history');
if (tab === 'history') {
trading.renderHistory();
}
},
toggleProfileMenu() {
document.getElementById('profile-menu').classList.toggle('hidden');
},
showDeposit() {
document.getElementById('deposit-modal').classList.remove('hidden');
},
setDepositAmount(amount) {
document.getElementById('deposit-amount').value = amount;
},
processDeposit() {
const amount = parseFloat(document.getElementById('deposit-amount').value);
if (!amount || amount < 10) {
this.showToast('Valor mínimo de depósito: $10', 'error');
return;
}
// Simular processamento
state.balance += amount;
this.updateBalance();
this.closeModal('deposit-modal');
this.showToast(`Depósito de $${amount.toFixed(2)} processado!`, 'success');
},
showProfile() {
this.showToast('Perfil em desenvolvimento', 'info');
document.getElementById('profile-menu').classList.add('hidden');
},
showHistory() {
this.setSidebarTab('history');
document.getElementById('profile-menu').classList.add('hidden');
},
showSettings() {
this.showToast('Configurações em desenvolvimento', 'info');
document.getElementById('profile-menu').classList.add('hidden');
},
closeModal(modalId) {
document.getElementById(modalId).classList.add('hidden');
},
showToast(message, type = 'info') {
const container = document.getElementById('toast-container');
const toast = document.createElement('div');
const colors = {
success: 'bg-green-500',
error: 'bg-red-500',
info: 'bg-blue-500'
};
const icons = {
success: 'check-circle',
error: 'x-circle',
info: 'info'
};
toast.className = `${colors[type]} text-white px-4 py-3 rounded-lg shadow-lg flex items-center gap-2 slide-up`;
toast.innerHTML = `
${message}
`;
container.appendChild(toast);
lucide.createIcons();
setTimeout(() => {
toast.style.opacity = '0';
toast.style.transform = 'translateX(100%)';
toast.style.transition = 'all 0.3s ease';
setTimeout(() => toast.remove(), 300);
}, 3000);
}
};
// ==========================================
// INICIALIZAÇÃO
// ==========================================
// Registrar plugin de candlestick
Chart.defaults.color = '#fff';
Chart.defaults.borderColor = 'rgba(255,255,255,0.1)';
// Plugin de candlestick simplificado
Chart.register({
id: 'candlestick',
beforeInit(chart) {
if (chart.config.type === 'candlestick') {
chart.config.type = 'bar';
chart.config.data.datasets[0].barPercentage = 0.8;
chart.config.data.datasets[0].categoryPercentage = 0.8;
}
}
});
// Iniciar quando DOM estiver pronto
document.addEventListener('DOMContentLoaded', () => {
auth.init();
});
// Fechar menus ao clicar fora
document.addEventListener('click', (e) => {
const profileMenu = document.getElementById('profile-menu');
const profileBtn = e.target.closest('[onclick="app.toggleProfileMenu()"]');
if (!profileBtn && !profileMenu.classList.contains('hidden')) {
profileMenu.classList.add('hidden');
}
});