import React, { useState } from 'react'; import { motion } from 'framer-motion'; import { Bot, Power, Activity, Settings2, Link, Zap, Shield, BarChart2, TrendingUp, DollarSign, Send, Globe2, AlertTriangle, Fingerprint, ChevronRight, Server, Cpu, Radio, Network, CheckCircle2, ShieldCheck } from 'lucide-react'; import { DerivDiagnosticPanel } from './DerivDiagnosticPanel'; import { AITradingDashboard } from './AITradingDashboard'; import { cn } from '../lib/utils'; export const AutoTradingView: React.FC<{ userData?: any, onUpdate?: (data: any) => void, onNavigate?: (tab: string) => void, isAdmin?: boolean }> = ({ userData, onUpdate, onNavigate, isAdmin }) => { const [robotActive, setRobotActive] = useState(userData?.tradingSettings?.engineRunning ?? false); const [mtPlatform, setMtPlatform] = useState(userData?.mtPlatform || 'mt5'); const [mtLogin, setMtLogin] = useState(userData?.mtLogin || ''); const [mtPassword, setMtPassword] = useState( userData?.mtPlatform === 'deriv_api' ? (userData?.mtPassword || userData?.savedDerivToken || '') : (userData?.mtPassword || '') ); const [mtServer, setMtServer] = useState(userData?.mtServer || ''); const [isSaving, setIsSaving] = useState(false); const [saveSuccess, setSaveSuccess] = useState(false); const [testResult, setTestResult] = useState<{message: string, isError: boolean} | null>(null); const [isTesting, setIsTesting] = useState(false); const [autoTrades, setAutoTrades] = useState([]); React.useEffect(() => { let unsubscribe = () => {}; if (userData?.uid) { (async () => { const { collection, query, orderBy, limit, onSnapshot } = await import('firebase/firestore'); const { db } = await import('../lib/firebase'); const q = query( collection(db, "users", userData.uid, "auto_trades"), orderBy("timestamp", "desc"), limit(10) ); unsubscribe = onSnapshot(q, (snap) => { const trades = snap.docs.map(d => ({ id: d.id, ...d.data() })); setAutoTrades(trades); }, (error) => { console.warn("Notice: Firestore rules not updated for auto_trades yet.", error.message); }); })(); } return () => unsubscribe(); }, [userData?.uid]); // Bot Settings State const [tradingSettings, setTradingSettings] = useState([ { key: 'smartEntry', label: "Smart Entry AI", desc: "Usa rede neural para entradas precisas", active: userData?.tradingSettings?.smartEntry ?? true }, { key: 'copyTrades', label: "Copy Institutional Trades", desc: "Copia movimentos de Baleias e Bancos", active: userData?.tradingSettings?.copyTrades ?? true }, { key: 'newsFilter', label: "News Filter (Alta Volatilidade)", desc: "Pausa o robô durante notícias vermelhas", active: userData?.tradingSettings?.newsFilter ?? false }, { key: 'autoTp', label: "Auto Take Profit (Dinâmico)", desc: "Ajusta alvo baseado em liquidez", active: userData?.tradingSettings?.autoTp ?? true }, { key: 'autoSl', label: "Auto Stop Loss (Trailing)", desc: "Acompanha o preço para garantir lucro", active: userData?.tradingSettings?.autoSl ?? true }, ]); const [riskPerTrade, setRiskPerTrade] = useState(userData?.tradingSettings?.riskPerTrade?.toString() || "1.5"); const [maxPositions, setMaxPositions] = useState(userData?.tradingSettings?.maxPositions?.toString() || "3"); const [selectedAsset, setSelectedAsset] = useState(userData?.tradingSettings?.selectedAsset || 'XAU/USD'); const [symbolSuffix, setSymbolSuffix] = useState(userData?.tradingSettings?.symbolSuffix || ''); const [lotType, setLotType] = useState(userData?.tradingSettings?.lotType || 'risk'); const [fixedLot, setFixedLot] = useState(userData?.tradingSettings?.fixedLot?.toString() || "0.01"); const [breakEvenEnabled, setBreakEvenEnabled] = useState(userData?.tradingSettings?.breakEvenEnabled ?? true); const [tradingHoursStart, setTradingHoursStart] = useState(userData?.tradingSettings?.tradingHoursStart || "00:00"); const [tradingHoursEnd, setTradingHoursEnd] = useState(userData?.tradingSettings?.tradingHoursEnd || "23:59"); const [minConfidence, setMinConfidence] = useState(userData?.tradingSettings?.minConfidence?.toString() || "80"); const [dailyLossLimit, setDailyLossLimit] = useState(userData?.tradingSettings?.dailyLossLimit?.toString() || "100"); const [dailyProfitTarget, setDailyProfitTarget] = useState(userData?.tradingSettings?.dailyProfitTarget?.toString() || "200"); const [cooldownMinutes, setCooldownMinutes] = useState(userData?.tradingSettings?.cooldownMinutes?.toString() || "5"); const [takeProfit, setTakeProfit] = useState(userData?.tradingSettings?.takeProfit?.toString() || "10"); const [stopLoss, setStopLoss] = useState(userData?.tradingSettings?.stopLoss?.toString() || "10"); const [trailingStop, setTrailingStop] = useState(userData?.tradingSettings?.trailingStop ?? true); const [autoCloseMinutes, setAutoCloseMinutes] = useState(userData?.tradingSettings?.autoCloseMinutes?.toString() || "10"); const saveSettingsToFirebase = async ( newSettings: any[], newRisk: string, newMax: string, newAsset?: string, newSuffix?: string, newRobotActive?: boolean, newLotType?: string, newFixedLot?: string, newBeEnabled?: boolean, newHoursStart?: string, newHoursEnd?: string ) => { if (!userData?.uid) return; const { doc, updateDoc } = await import('firebase/firestore'); const { db } = await import('../lib/firebase'); const userRef = doc(db, 'users', userData.uid); const assetToSave = newAsset ?? selectedAsset; const suffixToSave = newSuffix ?? symbolSuffix; const engineToSave = newRobotActive ?? robotActive; const updatedSettingsObj = { smartEntry: newSettings[0].active, copyTrades: newSettings[1].active, newsFilter: newSettings[2].active, autoTp: newSettings[3].active, autoSl: newSettings[4].active, // used as Trailing Stop toggle riskPerTrade: parseFloat(newRisk) || 1.5, maxPositions: parseInt(newMax) || 3, selectedAsset: assetToSave, symbolSuffix: suffixToSave, engineRunning: engineToSave, lotType: newLotType ?? lotType, fixedLot: parseFloat(newFixedLot ?? fixedLot) || 0.01, breakEvenEnabled: newBeEnabled ?? breakEvenEnabled, tradingHoursStart: newHoursStart ?? tradingHoursStart, tradingHoursEnd: newHoursEnd ?? tradingHoursEnd, minConfidence: parseFloat(minConfidence) || 80, dailyLossLimit: parseFloat(dailyLossLimit) || 100, dailyProfitTarget: parseFloat(dailyProfitTarget) || 200, cooldownMinutes: parseInt(cooldownMinutes) || 5, takeProfit: parseFloat(takeProfit) || 10, stopLoss: parseFloat(stopLoss) || 10, trailingStop: trailingStop, autoCloseMinutes: parseFloat(autoCloseMinutes) || 10 }; try { await updateDoc(userRef, { tradingSettings: updatedSettingsObj }); if (onUpdate) { onUpdate({ ...userData, tradingSettings: updatedSettingsObj }); } } catch (e) { console.error("Error saving settings:", e); } }; const handleToggleSetting = (index: number) => { const newSettings = [...tradingSettings]; newSettings[index].active = !newSettings[index].active; setTradingSettings(newSettings); saveSettingsToFirebase(newSettings, riskPerTrade, maxPositions); }; const handleRiskBlur = () => { saveSettingsToFirebase(tradingSettings, riskPerTrade, maxPositions); }; const handleFixedLotBlur = () => { saveSettingsToFirebase(tradingSettings, riskPerTrade, maxPositions); }; const handleMaxBlur = () => { saveSettingsToFirebase(tradingSettings, riskPerTrade, maxPositions); }; const handleAssetBlur = () => { saveSettingsToFirebase(tradingSettings, riskPerTrade, maxPositions); }; const handleSuffixBlur = () => { saveSettingsToFirebase(tradingSettings, riskPerTrade, maxPositions); }; const handleHoursBlur = () => { saveSettingsToFirebase(tradingSettings, riskPerTrade, maxPositions); }; const handleDisconnectBroker = async () => { if (!userData?.uid) return; setIsSaving(true); try { const { doc, updateDoc } = await import('firebase/firestore'); const { db } = await import('../lib/firebase'); const userRef = doc(db, 'users', userData.uid); await updateDoc(userRef, { mtPlatform: '', mtLogin: '', mtPassword: '', mtServer: '', metaApiAccountId: null, metaApiState: null, derivName: null, derivEmail: null, derivCurrency: null, derivAccountList: null, derivMt5AccountList: null }); if (onUpdate) { onUpdate({ ...userData, mtPlatform: '', mtLogin: '', mtPassword: '', mtServer: '', metaApiAccountId: null, metaApiState: null, derivName: null, derivEmail: null, derivCurrency: null, derivAccountList: null, derivMt5AccountList: null }); } if (userData?.mtPlatform === 'deriv_api') { setMtPlatform('deriv_api'); setMtLogin(''); setMtPassword(userData.savedDerivToken || userData.mtPassword || ''); setMtServer(''); } else { setMtPlatform('mt5'); setMtLogin(''); setMtPassword(''); setMtServer(''); } } catch (e: any) { console.error("Error disconnecting broker:", e); alert(e.message || "Failed to disconnect"); } finally { setIsSaving(false); } }; const handleConnectBroker = async () => { if (!userData?.uid) return; setIsSaving(true); try { let extAccountId = null; let extState = null; let finalLogin = mtLogin; let finalServer = mtServer; let derivData: any = null; if (mtPlatform === 'deriv_api') { const cleanToken = mtPassword.trim(); if (!/^[\w\-]{1,128}$/.test(cleanToken)) { throw new Error("Token Deriv inválido. Verifique se copiou corretamente (sem espaços ou caracteres especiais)."); } const res = await fetch('/api/deriv/authorize', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token: cleanToken }) }); const data = await res.json(); if (!res.ok) throw new Error(data.error || 'Failed to connect to Deriv API'); const derivAccount = data.account; finalLogin = derivAccount.loginid; finalServer = 'Deriv ' + derivAccount.landing_company_name?.toUpperCase(); extState = 'DEPLOYED'; derivData = { derivName: derivAccount.fullname, derivEmail: derivAccount.email, derivCurrency: derivAccount.currency, derivAccountList: derivAccount.account_list, derivMt5AccountList: data.mt5_login_list || [] }; } else { // First try to provision through our backend proxy for MT4/MT5 const res = await fetch('/api/metaapi/provision', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ platform: mtPlatform, login: mtLogin, password: mtPassword, serverName: mtServer }) }); const data = await res.json(); if (!res.ok) { throw new Error(data.error || 'Failed to connect to MetaAPI'); } extAccountId = data.accountId; extState = data.state; } // Save to Firebase const { doc, updateDoc } = await import('firebase/firestore'); const { db } = await import('../lib/firebase'); const userRef = doc(db, 'users', userData.uid); const payload: any = { mtPlatform, mtLogin: finalLogin, mtPassword, mtServer: finalServer, metaApiAccountId: extAccountId, metaApiState: extState }; if (mtPlatform === 'deriv_api') { payload.savedDerivToken = mtPassword; } if (derivData) { Object.assign(payload, derivData); } await updateDoc(userRef, payload); if (onUpdate) { onUpdate({ ...userData, ...payload }); } setSaveSuccess(true); setTimeout(() => setSaveSuccess(false), 3000); } catch (e: any) { console.error("Error saving Broker config:", e); alert(e.message || "Failed to connect to Terminal"); } finally { setIsSaving(false); } }; const marketData = [ { pair: 'EUR/USD', signal: 'BUY', score: 98, momentum: 'High', liquidity: 'Optimal', trend: 'Bullish' }, { pair: 'GBP/USD', signal: 'SELL', score: 92, momentum: 'Medium', liquidity: 'High', trend: 'Bearish' }, { pair: 'XAU/USD', signal: 'BUY', score: 99, momentum: 'Extreme', liquidity: 'Optimal', trend: 'Bullish' }, { pair: 'BTC/USD', signal: 'SELL', score: 85, momentum: 'Low', liquidity: 'Medium', trend: 'Ranging' }, ]; return (
{/* HEADER PRINCIPAL - CYBERPUNK / HIGH-TECH */}
{/* TECH BACKGROUND */}
{/* GLOWING GRID */}
Background
Neural Link v4.2 Active

QUANTSCAN IA AUTOTRADING SYNAPSE

{/* METRICS HEADER */}
Core Load
{(Math.random() * 20 + 10).toFixed(1)}%
Latency
{Math.floor(Math.random() * 20 + 5)}ms
Engine Status {robotActive ? "ONLINE" : "OFFLINE"}
{/* DASHBOARD GRID */}
{/* LEFT COLUMN: STATUS & BUTTONS */}
{userData?.mtPlatform === 'deriv_api' && ( <> )} {/* MAIN BUTTONS */}
{testResult && (
{testResult.message}
)}

ACTIVE SUBSYSTEMS

QuantScan IA PRO
Institutional HFR
{isAdmin && ( )}
{/* MIDDLE COLUMN: SETTINGS */}

PARAMETERS & PROTOCOLS

{tradingSettings.map((setting, i) => (
{setting.label} {setting.desc}
))}
setSymbolSuffix(e.target.value)} onBlur={handleSuffixBlur} className="w-full bg-black border border-white/10 rounded-lg p-3 text-sm text-white font-mono focus:border-brand-red outline-none transition-colors" />
setRiskPerTrade(e.target.value)} onBlur={handleRiskBlur} step="0.1" className="w-full bg-black border border-white/10 rounded-lg p-3 text-sm text-white font-mono focus:border-brand-red outline-none transition-colors" />
setMaxPositions(e.target.value)} onBlur={handleMaxBlur} className="w-full bg-black border border-white/10 rounded-lg p-3 text-sm text-white font-mono focus:border-brand-red outline-none transition-colors" />
{/* ADVANCED SETTINGS ROW */}
{lotType === 'risk' ? ( setRiskPerTrade(e.target.value)} onBlur={handleRiskBlur} step="0.1" className="w-full bg-black border border-white/10 rounded-lg p-3 text-sm text-white font-mono focus:border-brand-red outline-none transition-colors" /> ) : ( setFixedLot(e.target.value)} onBlur={handleFixedLotBlur} step="0.01" className="w-full bg-black border border-white/10 rounded-lg p-3 text-sm text-white font-mono focus:border-brand-red outline-none transition-colors" /> )}
{/* BREAK EVEN & TIMES */}
Mover Stop pro ponto de entrada
setTradingHoursStart(e.target.value)} onBlur={handleHoursBlur} className="w-full bg-black border border-white/10 rounded-lg p-3 text-sm text-white font-mono focus:border-brand-red outline-none transition-colors" />
setTradingHoursEnd(e.target.value)} onBlur={handleHoursBlur} className="w-full bg-black border border-white/10 rounded-lg p-3 text-sm text-white font-mono focus:border-brand-red outline-none transition-colors" />
{/* RISK MANAGEMENT PANEL */}

RISK MANAGEMENT

setMinConfidence(e.target.value)} onBlur={() => saveSettingsToFirebase(tradingSettings, riskPerTrade, maxPositions)} className="w-full bg-black border border-white/10 rounded-lg p-3 text-sm text-white font-mono focus:border-brand-red outline-none transition-colors" />
setCooldownMinutes(e.target.value)} onBlur={() => saveSettingsToFirebase(tradingSettings, riskPerTrade, maxPositions)} className="w-full bg-black border border-white/10 rounded-lg p-3 text-sm text-white font-mono focus:border-brand-red outline-none transition-colors" />
setDailyLossLimit(e.target.value)} onBlur={() => saveSettingsToFirebase(tradingSettings, riskPerTrade, maxPositions)} className="w-full bg-black border border-red-500/30 rounded-lg p-3 text-sm text-red-400 font-mono focus:border-red-500 outline-none transition-colors" />
setDailyProfitTarget(e.target.value)} onBlur={() => saveSettingsToFirebase(tradingSettings, riskPerTrade, maxPositions)} className="w-full bg-black border border-green-500/30 rounded-lg p-3 text-sm text-green-400 font-mono focus:border-green-500 outline-none transition-colors" />
setTakeProfit(e.target.value)} onBlur={() => saveSettingsToFirebase(tradingSettings, riskPerTrade, maxPositions)} className="w-full bg-black border border-green-500/30 rounded-lg p-3 text-sm text-green-400 font-mono focus:border-green-500 outline-none transition-colors" />
setStopLoss(e.target.value)} onBlur={() => saveSettingsToFirebase(tradingSettings, riskPerTrade, maxPositions)} className="w-full bg-black border border-red-500/30 rounded-lg p-3 text-sm text-red-400 font-mono focus:border-red-500 outline-none transition-colors" />
setAutoCloseMinutes(e.target.value)} onBlur={() => saveSettingsToFirebase(tradingSettings, riskPerTrade, maxPositions)} className="w-full bg-black border border-white/10 rounded-lg p-3 text-sm text-white font-mono focus:border-brand-red outline-none transition-colors" />
Trailing Stop
{/* RIGHT COLUMN: BROKERS & LIVE MARKET */}
{/* BROKER INTEGRATION (MT4/MT5) */}
{/* HOLOGRAPHIC SCAN LINES */}

EXTERNAL UPLINK (BROKER)

{userData?.mtPlatform === 'deriv_api' && userData?.mtLogin ? (

Deriv API Connected

Titular: {userData.derivName || "Desconhecido"}

Padrão: {userData.mtLogin}

Servidor: {userData.mtServer}

{userData.derivAccountList && userData.derivAccountList.length > 0 && (

Usado para negociar opções/multiplicadores nativos da corretora.

)} {userData.derivMt5AccountList && userData.derivMt5AccountList.length > 0 && (
{userData.derivMt5AccountList.map((mtAcc: any) => (

{mtAcc.login} {mtAcc.account_type === 'demo' ? ( DEMO ) : ( REAL )}

{mtAcc.server_info?.environment || mtAcc.server}

{mtAcc.display_balance} {mtAcc.currency}

{mtAcc.market_type}

))}

* Para operar nas contas MT5, utilize a opção "MetaTrader 5" e a senha individual do MT5 correspondente na configuração.

)}
) : userData?.metaApiAccountId ? (

Terminal Conectado

Conta: {mtLogin} ({mtPlatform.toUpperCase()})

Servidor: {mtServer}

) : ( <>
{mtPlatform === 'deriv_api' ? (
setMtPassword(e.target.value)} className="w-full bg-black border border-white/10 rounded-lg p-3 text-sm text-white font-mono focus:border-brand-red outline-none transition-colors" />

Gere um token na Deriv com permissões de 'Read' e 'Trade'. Recomendado para Volatility/Boom/Crash.

) : ( <>
setMtLogin(e.target.value)} className="w-full bg-black border border-white/10 rounded-lg p-3 text-sm text-white font-mono focus:border-brand-red outline-none transition-colors" />
)}
{mtPlatform !== 'deriv_api' && (
setMtPassword(e.target.value)} className="w-full bg-black border border-white/10 rounded-lg p-3 text-sm text-white font-mono focus:border-brand-red outline-none transition-colors" />
setMtServer(e.target.value)} className="w-full bg-black border border-white/10 rounded-lg p-3 text-sm text-white font-mono focus:border-brand-red outline-none transition-colors" />
)}

Este comentário será enviado obrigatoriamente a cada trade executado, provando a autenticidade das operações na sua corretora.

)}
{/* TELEGRAM SETTINGS WIDGET */}

Alertas no Telegram

Receba notificações de entradas e saídas do robô instantaneamente no seu celular.

{/* ACTIVITY LOGS WIDGET */}

Activity Logs (Auto Trading)

{autoTrades.length === 0 ? (

Nenhum trade executado ainda.

) : ( autoTrades.map((t) => (
= 0 ? 'text-green-500' : 'text-red-500')}> {(t.profit || 0) >= 0 ? 'PROFIT' : 'LOSS'} {t.symbol || t.pair || 'TRADE'}
ID: {t.contract_id || t.id} {t.close_reason ? `• ${t.close_reason}` : ''}
{new Date(t.timestamp).toLocaleTimeString()}
= 0 ? "text-green-500" : "text-red-500")}> {(t.profit || 0) >= 0 ? '+' : ''}{t.profit?.toFixed(2)} USD
)) )}
); };