import { useState, useEffect, useRef } from 'react'; import { Zap, TrendingUp, TrendingDown, ShieldAlert, Target, Key, Wallet, Settings2, AlertTriangle, CheckCircle2, Lock, Trash2, } from 'lucide-react'; import { Modal } from '../ui/Modal'; import { Button } from '../ui/Button'; import { useToast } from '../ui/Toast'; import { executionApi, BybitSettings, BybitWalletBalance, getStoredBybitCredentials, clearStoredBybitCredentials, } from '../../api/execution'; import type { AIExecutiveSummary } from '../signals/AIExecutiveSummaryCard'; interface ExecutionModalProps { isOpen: boolean; onClose: () => void; symbol: string; summary: AIExecutiveSummary; markPrice?: number; onExecutionSuccess?: (result: any) => void; } function parsePrice(str?: string, pickEdge?: 'first' | 'high'): number | null { if (!str) return null; // 1. Look for explicit dollar amount(s): e.g. "$99.9500 - $100.3500" const dollarMatches = Array.from(str.matchAll(/\$\s*([0-9]+(?:,[0-9]{3})*(?:\.[0-9]+)?|[0-9]+(?:\.[0-9]+)?)/g)) .map((m) => parseFloat(m[1].replace(/,/g, ''))) .filter((v) => !isNaN(v) && v > 0); if (dollarMatches.length > 0) { return pickEdge === 'high' ? Math.max(...dollarMatches) : dollarMatches[0]; } // 2. Strip known timeframe or indicator label prefixes like TP1:, TP2:, 1H, 4H, 15M, 5M, 24H, 1D const cleanedStr = str.replace(/\b(TP[12]|1[Hh]|4[Hh]|15[Mm]|5[Mm]|24[Hh]|1[Dd])\b[:\s-]*/gi, ''); // 3. Match decimal or comma-formatted float numbers const numMatches = Array.from(cleanedStr.matchAll(/([0-9]+(?:,[0-9]{3})*(?:\.[0-9]+)?|[0-9]+(?:\.[0-9]+)?)/g)) .map((m) => parseFloat(m[1].replace(/,/g, ''))) .filter((v) => !isNaN(v) && v > 0); if (numMatches.length > 0) { return pickEdge === 'high' ? Math.max(...numMatches) : numMatches[0]; } return null; } function parseLeverage(str?: string): number { if (!str) return 3; // Match number directly attached to 'x' or 'X' (e.g. "3x", "2-3x") const match = str.match(/([0-9]+)\s*x/i); if (match && match[1]) { const val = parseInt(match[1], 10); if (!isNaN(val) && val > 0) return Math.min(Math.max(val, 1), 50); } return 3; } export function ExecutionModal({ isOpen, onClose, symbol, summary, markPrice, onExecutionSuccess, }: ExecutionModalProps) { const { toast } = useToast(); const upperBias = summary.bias.toUpperCase(); const isShort = upperBias.includes('SHORT') || upperBias.includes('SELL'); const isLong = upperBias.includes('LONG') || upperBias.includes('BUY'); const isNeutralBias = upperBias.includes('NEUTRAL') || upperBias.includes('WAIT') || (!isShort && !isLong); const defaultSide: 'Buy' | 'Sell' = isShort ? 'Sell' : 'Buy'; const rawEntry = (summary.entryPrice && summary.entryPrice > 0 ? summary.entryPrice : null) || parsePrice(summary.entryZone, isShort ? 'high' : 'first') || markPrice || 0; const rawSL = parsePrice(summary.stopLoss) || (isShort ? rawEntry * 1.03 : rawEntry * 0.97); const rawTP1 = parsePrice(summary.takeProfit1) || (isShort ? rawEntry * 0.95 : rawEntry * 1.05); const rawTP2 = parsePrice(summary.takeProfit2); const defaultLev = parseLeverage(summary.leverage); // Form State const [orderType, setOrderType] = useState<'Market' | 'Limit'>('Limit'); const [sizingMode, setSizingMode] = useState<'percent' | 'usd'>('percent'); const [marginPercent, setMarginPercent] = useState(5); const [marginPctDraft, setMarginPctDraft] = useState('5'); const [marginUsd, setMarginUsd] = useState(50); const [marginUsdDraft, setMarginUsdDraft] = useState('50'); const [leverage, setLeverage] = useState(defaultLev); const [entryPrice, setEntryPrice] = useState(rawEntry); const [entryDraft, setEntryDraft] = useState(rawEntry > 0 ? String(rawEntry) : ''); const [stopLoss, setStopLoss] = useState(rawSL); const [slDraft, setSlDraft] = useState(rawSL > 0 ? String(rawSL) : ''); const [takeProfit1, setTakeProfit1] = useState(rawTP1); const [tp1Draft, setTp1Draft] = useState(rawTP1 > 0 ? String(rawTP1) : ''); const [takeProfit2, setTakeProfit2] = useState(rawTP2); const [tp2Draft, setTp2Draft] = useState(rawTP2 && rawTP2 > 0 ? String(rawTP2) : ''); const [tp1Percent, setTp1Percent] = useState(50); const [autoBreakeven, setAutoBreakeven] = useState(true); // Settings & Connection State const [settings, setSettings] = useState(null); const [balance, setBalance] = useState(null); const [isConfiguringKey, setIsConfiguringKey] = useState(false); const [apiKeyInput, setApiKeyInput] = useState(''); const [apiSecretInput, setApiSecretInput] = useState(''); const [modeInput, setModeInput] = useState<'demo' | 'testnet' | 'real'>('demo'); const [isSavingKey, setIsSavingKey] = useState(false); const [isSubmitting, setIsSubmitting] = useState(false); const [authErrorMsg, setAuthErrorMsg] = useState(null); const lastSyncedSessionRef = useRef(null); // Sync form levels only when opening the modal or changing symbol/bias (never wipe manual edits on live markPrice ticks) useEffect(() => { if (!isOpen) { lastSyncedSessionRef.current = null; return; } const sessionKey = `${symbol}:${isShort ? 'SHORT' : 'LONG'}`; if (lastSyncedSessionRef.current === sessionKey) { return; } const nextEntry = (summary.entryPrice && summary.entryPrice > 0 ? summary.entryPrice : null) || parsePrice(summary.entryZone, isShort ? 'high' : 'first') || markPrice || 0; if (nextEntry > 0) { lastSyncedSessionRef.current = sessionKey; } const nextSL = parsePrice(summary.stopLoss) || (isShort ? nextEntry * 1.03 : nextEntry * 0.97); const nextTP1 = parsePrice(summary.takeProfit1) || (isShort ? nextEntry * 0.95 : nextEntry * 1.05); const nextTP2 = parsePrice(summary.takeProfit2); const nextLev = parseLeverage(summary.leverage); setEntryPrice(nextEntry); setEntryDraft(nextEntry > 0 ? String(nextEntry) : ''); setStopLoss(nextSL); setSlDraft(nextSL > 0 ? String(nextSL) : ''); setTakeProfit1(nextTP1); setTp1Draft(nextTP1 > 0 ? String(nextTP1) : ''); setTakeProfit2(nextTP2); setTp2Draft(nextTP2 && nextTP2 > 0 ? String(nextTP2) : ''); setLeverage(nextLev); }, [ isOpen, symbol, isShort, summary.entryPrice, summary.entryZone, summary.stopLoss, summary.takeProfit1, summary.takeProfit2, summary.leverage, markPrice, ]); // Load Bybit Settings on open useEffect(() => { if (isOpen) { const stored = getStoredBybitCredentials(); if (stored) { setModeInput(stored.mode); } loadSettings(); } }, [isOpen]); const loadSettings = async () => { setAuthErrorMsg(null); try { const s = await executionApi.getSettings(); setSettings(s); setModeInput(s.mode || 'demo'); if (s.configured) { setIsConfiguringKey(false); fetchBalance(s.mode); } else { setIsConfiguringKey(true); } } catch (err: any) { const st = err?.status; if (st === 401 || st === 503) { setAuthErrorMsg( err?.message || 'API Bearer Token belum diset / tidak cocok. Buka ikon status server di header untuk mengisi PERPS_API_TOKEN.' ); setIsConfiguringKey(false); } else { setIsConfiguringKey(true); } } }; const handleClearSessionCredentials = () => { clearStoredBybitCredentials(); setApiKeyInput(''); setApiSecretInput(''); setBalance(null); toast('Kredensial Bybit sesi browser telah dihapus dari memori lokal.', 'success'); loadSettings(); }; const fetchBalance = async (mode?: string) => { try { const b = await executionApi.getBalance(mode); setBalance(b); } catch { // Ignored if keys aren't active yet } }; const handleSaveCredentials = async () => { if (!apiKeyInput.trim() || !apiSecretInput.trim()) { toast('Masukkan API Key dan API Secret Bybit Anda.', 'error'); return; } setIsSavingKey(true); try { const res = await executionApi.saveSettings({ api_key: apiKeyInput.trim(), api_secret: apiSecretInput.trim(), mode: modeInput, }); toast(res.message, 'success'); setSettings({ configured: true, masked_key: `${apiKeyInput.slice(0, 4)}***`, mode: modeInput, }); if (res.balance) { setBalance(res.balance); } setIsConfiguringKey(false); } catch (err: any) { toast(err.message || 'Kredensial Bybit gagal divalidasi.', 'error'); } finally { setIsSavingKey(false); } }; // Total Equity resolution & Effective Margin Calculation const totalEquity = (balance?.total_equity && balance.total_equity > 0) ? balance.total_equity : (balance?.available_balance && balance.available_balance > 0 ? balance.available_balance : 0); const calculatedPercentMargin = totalEquity > 0 ? Math.round((totalEquity * (marginPercent / 100)) * 100) / 100 : 0; const effectiveMargin = sizingMode === 'percent' ? calculatedPercentMargin : marginUsd; // Calculations for preview const refPrice = orderType === 'Limit' && entryPrice > 0 ? entryPrice : (markPrice || entryPrice || 0); const notionalUsd = effectiveMargin * leverage; const estLossUsd = refPrice > 0 ? (isShort ? (stopLoss - refPrice) / refPrice : (refPrice - stopLoss) / refPrice) * notionalUsd : 0; const hasSplitTp2 = Boolean(takeProfit2 && takeProfit2 > 0 && tp1Percent < 100); const tp1Ratio = hasSplitTp2 ? tp1Percent / 100 : 1; const tp2Ratio = hasSplitTp2 ? (100 - tp1Percent) / 100 : 0; const estTp1Gain = refPrice > 0 && takeProfit1 > 0 ? (isShort ? (refPrice - takeProfit1) / refPrice : (takeProfit1 - refPrice) / refPrice) * (notionalUsd * tp1Ratio) : 0; const estTp2Gain = refPrice > 0 && hasSplitTp2 && takeProfit2 ? (isShort ? (refPrice - takeProfit2) / refPrice : (takeProfit2 - refPrice) / refPrice) * (notionalUsd * tp2Ratio) : 0; const totalEstGain = estTp1Gain + estTp2Gain; const estimatedRR = estLossUsd > 0 ? (totalEstGain / estLossUsd).toFixed(2) : 'N/A'; const handleExecute = async () => { if (isNeutralBias) { toast('Sinyal berstatus NEUTRAL/WAIT — eksekusi order dibatalkan untuk mencegah salah arah.', 'error'); return; } if (!settings?.configured) { setIsConfiguringKey(true); toast('Harap masukkan API Key Bybit sebelum eksekusi.', 'info'); return; } if (sizingMode === 'percent') { if (totalEquity <= 0) { toast('Total equity Bybit terdeteksi $0 atau API belum terhubung. Silakan beralih ke tab "$ USD Tetap" atau hubungkan API Bybit.', 'error'); return; } if (marginPercent < 0.1 || marginPercent > 100) { toast('Persentase alokasi equity harus antara 0.1% hingga 100%.', 'error'); return; } } else { if (marginUsd <= 0) { toast('Masukkan margin yang valid (> $0).', 'error'); return; } } if (effectiveMargin <= 0) { toast('Margin efektif tidak valid atau $0.', 'error'); return; } if (orderType === 'Limit' && entryPrice <= 0) { toast('Harga Entry Limit wajib lebih besar dari $0.', 'error'); return; } if (stopLoss <= 0 || takeProfit1 <= 0) { toast('Stop Loss dan Target TP1 wajib diisi.', 'error'); return; } if (takeProfit2 !== null && takeProfit2 <= 0 && tp1Percent < 100) { toast('Target TP2 harus lebih besar dari $0 (atau kosongkan jika hanya TP1).', 'error'); return; } // Directional validation to prevent inverted SL/TP orders if (defaultSide === 'Buy') { if (refPrice > 0) { if (stopLoss >= refPrice) { toast(`Stop Loss ($${stopLoss}) harus lebih rendah dari Entry ($${refPrice}) untuk posisi Long.`, 'error'); return; } if (takeProfit1 <= refPrice) { toast(`Target TP1 ($${takeProfit1}) harus lebih tinggi dari Entry ($${refPrice}) untuk posisi Long.`, 'error'); return; } } else if (stopLoss >= takeProfit1) { toast(`Stop Loss ($${stopLoss}) harus lebih rendah dari Target TP1 ($${takeProfit1}) untuk posisi Long.`, 'error'); return; } if (takeProfit2 && tp1Percent < 100 && takeProfit2 <= takeProfit1) { toast(`Target TP2 ($${takeProfit2}) harus lebih tinggi dari TP1 ($${takeProfit1}).`, 'error'); return; } } else { if (refPrice > 0) { if (stopLoss <= refPrice) { toast(`Stop Loss ($${stopLoss}) harus lebih tinggi dari Entry ($${refPrice}) untuk posisi Short.`, 'error'); return; } if (takeProfit1 >= refPrice) { toast(`Target TP1 ($${takeProfit1}) harus lebih rendah dari Entry ($${refPrice}) untuk posisi Short.`, 'error'); return; } } else if (stopLoss <= takeProfit1) { toast(`Stop Loss ($${stopLoss}) harus lebih tinggi dari Target TP1 ($${takeProfit1}) untuk posisi Short.`, 'error'); return; } if (takeProfit2 && tp1Percent < 100 && takeProfit2 >= takeProfit1) { toast(`Target TP2 ($${takeProfit2}) harus lebih rendah dari TP1 ($${takeProfit1}).`, 'error'); return; } } setIsSubmitting(true); try { const res = await executionApi.executeOrder({ symbol, side: defaultSide, order_type: orderType, margin_usd: sizingMode === 'percent' ? 0 : effectiveMargin, margin_percent: sizingMode === 'percent' ? marginPercent : null, leverage, stop_loss: stopLoss, take_profit_1: takeProfit1, take_profit_2: tp1Percent < 100 ? takeProfit2 : null, tp1_percent: tp1Percent, auto_breakeven: tp1Percent < 100 && Boolean(takeProfit2) ? autoBreakeven : false, entry_price: orderType === 'Limit' ? entryPrice : undefined, mark_price: markPrice, summary_tldr: summary.verdictSummary, }); toast(`🚀 ${res.message}`, 'success'); if (onExecutionSuccess) { onExecutionSuccess(res); } onClose(); } catch (err: any) { toast(err.message || 'Eksekusi order gagal.', 'error'); } finally { setIsSubmitting(false); } }; return (
{/* ── 1. Top Header: Bias Badge & Bybit Connection Status ─────────── */}
{isShort ? : } {defaultSide.toUpperCase()} ({summary.bias})
Mark: {markPrice != null && markPrice > 0 ? markPrice >= 1000 ? `$${markPrice.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}` : markPrice >= 1 ? `$${markPrice.toFixed(4)}` : markPrice >= 0.01 ? `$${markPrice.toFixed(6)}` : `$${markPrice.toFixed(8)}` : 'N/A'}
{/* Bybit Account Status Pill */}
{settings?.configured ? (
{settings.mode} Bybit {balance && ( ${(balance.total_equity || balance.available_balance).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })} USDT )}
) : (
API Belum Terpasang
)}
{/* ── 2. Auth Gate Alert OR Collapsible API Key Drawer ─────────────── */} {authErrorMsg && (

Autentikasi Server Dibutuhkan

{authErrorMsg}

)} {isConfiguringKey && (
Kredensial API Bybit (Stateless Per-Sesi) Disimpan hanya di sessionStorage & dikirim per-request
setApiKeyInput(e.target.value)} placeholder="Masukkan API Key Bybit" className="w-full px-2.5 py-1.5 rounded-lg bg-bg-card border border-border text-xs text-text-primary font-mono focus:border-purple-500 focus:outline-none" />
setApiSecretInput(e.target.value)} placeholder="Masukkan API Secret Bybit" className="w-full px-2.5 py-1.5 rounded-lg bg-bg-card border border-border text-xs text-text-primary font-mono focus:border-purple-500 focus:outline-none" />
Lingkungan:
{[ { id: 'demo', label: 'Bybit Demo (api-demo)' }, { id: 'testnet', label: 'Testnet' }, { id: 'real', label: 'Live Real' }, ].map((m) => ( ))}
{getStoredBybitCredentials() && ( )} {settings?.configured && ( )}
)} {/* ── 3. Position Sizing & Margin Allocation ──────────────────────── */}
Alokasi Modal Margin {/* Segmented Sizing Mode Switcher */}
Notional Posisi: ${notionalUsd.toLocaleString(undefined, { minimumFractionDigits: 1, maximumFractionDigits: 1 })} USD
{/* Left Column: Sizing Input according to active mode */}
{sizingMode === 'percent' ? ( <>
{ const raw = e.target.value; setMarginPctDraft(raw); const parsed = parseFloat(raw); setMarginPercent(raw.trim() === '' || isNaN(parsed) ? 0 : Math.max(0, parsed)); }} className="w-full pl-3 pr-8 py-1.5 rounded-lg bg-bg-card border border-border text-sm font-bold font-mono text-text-primary focus:border-purple-500 focus:outline-none" /> %
{/* Quick % Pills */}
{[1, 2, 5, 10, 20].map((pct) => ( ))}
{/* Live Equity Calculation Conversion */}
{totalEquity > 0 ? ( ⚡ {marginPercent}% = ${calculatedPercentMargin.toFixed(2)} USD (dari equity ${totalEquity.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}) ) : ( Saldo equity $0 / belum terhubung. Silakan gunakan tab "$ USD". )}
) : ( <>
$ { const raw = e.target.value; setMarginUsdDraft(raw); const parsed = parseFloat(raw); setMarginUsd(raw.trim() === '' || isNaN(parsed) ? 0 : Math.max(0, parsed)); }} className="w-full pl-7 pr-3 py-1.5 rounded-lg bg-bg-card border border-border text-sm font-bold font-mono text-text-primary focus:border-purple-500 focus:outline-none" />
{/* Quick USD Pills */}
{[25, 50, 100, 200].map((amt) => ( ))}
{/* USD to % Comparison */}
{totalEquity > 0 ? ( â„šī¸ ${marginUsd.toFixed(2)} USD ≈ {((marginUsd / totalEquity) * 100).toFixed(1)}% dari total equity (${totalEquity.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}) ) : ( â„šī¸ Nominal margin tetap ${marginUsd.toFixed(2)} USD )}
)}
{/* Right Column: Leverage & Order Type Selector */}
Leverage: {leverage}x
setLeverage(parseInt(e.target.value, 10))} className="w-full accent-purple-500 cursor-pointer" />
{/* ── 4. Key Price Levels (Auto-filled from Damian) ───────────────── */}
{/* Entry */}
{orderType === 'Limit' ? 'ENTRY PRICE (LIMIT)' : 'ENTRY MARKET'} { const raw = e.target.value; setEntryDraft(raw); const parsed = parseFloat(raw); setEntryPrice(raw.trim() === '' || isNaN(parsed) ? 0 : parsed); }} className="w-full px-2 py-1 rounded bg-bg-elevated border border-border text-xs font-mono font-bold text-text-primary focus:border-purple-500 focus:outline-none disabled:opacity-50" />
{/* Stop Loss */}
STOP LOSS (SL) { const raw = e.target.value; setSlDraft(raw); const parsed = parseFloat(raw); setStopLoss(raw.trim() === '' || isNaN(parsed) ? 0 : parsed); }} className="w-full px-2 py-1 rounded bg-bg-elevated border border-rose-500/40 text-xs font-mono font-bold text-rose-400 focus:border-rose-400 focus:outline-none" />
{/* Take Profit 1 */}
TARGET TP1 { const raw = e.target.value; setTp1Draft(raw); const parsed = parseFloat(raw); setTakeProfit1(raw.trim() === '' || isNaN(parsed) ? 0 : parsed); }} className="w-full px-2 py-1 rounded bg-bg-elevated border border-emerald-500/40 text-xs font-mono font-bold text-emerald-400 focus:border-emerald-400 focus:outline-none" />
{/* Take Profit 2 (Optional) */}
TARGET TP2 { const raw = e.target.value; setTp2Draft(raw); const parsed = parseFloat(raw); setTakeProfit2(raw.trim() === '' || isNaN(parsed) ? null : parsed); }} placeholder="Opsional" className="w-full px-2 py-1 rounded bg-bg-elevated border border-emerald-500/40 text-xs font-mono font-bold text-emerald-300 focus:border-emerald-400 focus:outline-none" />
{/* ── 5. Custom Split Take Profit (TP1 %) Slider ──────────────────── */}
Porsi Ambil Cuan TP1 (Custom Split)
{[25, 50, 75, 100].map((pct) => ( ))}
setTp1Percent(parseInt(e.target.value, 10))} className="w-full accent-purple-500 cursor-pointer" />
TP1: {tp1Percent}% {tp1Percent < 100 ? `TP2: ${100 - tp1Percent}%` : 'TP2: Dinonaktifkan'}
{/* Explanation Text */}

{tp1Percent >= 100 ? ( đŸŽ¯ 100% posisi akan ditutup penuh di TP1 saat harga tercapai. ) : ( đŸŽ¯ {tp1Percent}% posisi akan ditutup di TP1 (${takeProfit1}), dan sisa {100 - tp1Percent}% dibiarkan berlari ke TP2 (${takeProfit2 || 'Runner'}). )}

{/* Auto-Breakeven SL after TP1 Toggle */} {tp1Percent < 100 && Boolean(takeProfit2) && (
)}
{/* ── 6. Live Risk & Reward Preview Summary ────────────────────────── */}
POTENSI CUAN TOTAL +${totalEstGain.toFixed(2)} USD
MAKSIMAL RISIKO (SL) -${Math.abs(estLossUsd).toFixed(2)} USD
RISK / REWARD RIIL 1 : {estimatedRR}
{/* ── 7. Action Button ────────────────────────────────────────────── */}
); }