Perps-Terminal / frontend /src /components /execution /ExecutionModal.tsx
Naufal Arhab
chore: full codebase audit fixes, L2/whale/calibration upgrades, and rebuild frontend dist
48f60d7
Raw History Blame Contribute Delete
41.8 kB
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<number>(5);
const [marginPctDraft, setMarginPctDraft] = useState<string>('5');
const [marginUsd, setMarginUsd] = useState<number>(50);
const [marginUsdDraft, setMarginUsdDraft] = useState<string>('50');
const [leverage, setLeverage] = useState<number>(defaultLev);
const [entryPrice, setEntryPrice] = useState<number>(rawEntry);
const [entryDraft, setEntryDraft] = useState<string>(rawEntry > 0 ? String(rawEntry) : '');
const [stopLoss, setStopLoss] = useState<number>(rawSL);
const [slDraft, setSlDraft] = useState<string>(rawSL > 0 ? String(rawSL) : '');
const [takeProfit1, setTakeProfit1] = useState<number>(rawTP1);
const [tp1Draft, setTp1Draft] = useState<string>(rawTP1 > 0 ? String(rawTP1) : '');
const [takeProfit2, setTakeProfit2] = useState<number | null>(rawTP2);
const [tp2Draft, setTp2Draft] = useState<string>(rawTP2 && rawTP2 > 0 ? String(rawTP2) : '');
const [tp1Percent, setTp1Percent] = useState<number>(50);
const [autoBreakeven, setAutoBreakeven] = useState<boolean>(true);
// Settings & Connection State
const [settings, setSettings] = useState<BybitSettings | null>(null);
const [balance, setBalance] = useState<BybitWalletBalance | null>(null);
const [isConfiguringKey, setIsConfiguringKey] = useState<boolean>(false);
const [apiKeyInput, setApiKeyInput] = useState<string>('');
const [apiSecretInput, setApiSecretInput] = useState<string>('');
const [modeInput, setModeInput] = useState<'demo' | 'testnet' | 'real'>('demo');
const [isSavingKey, setIsSavingKey] = useState<boolean>(false);
const [isSubmitting, setIsSubmitting] = useState<boolean>(false);
const [authErrorMsg, setAuthErrorMsg] = useState<string | null>(null);
const lastSyncedSessionRef = useRef<string | null>(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 (
<Modal isOpen={isOpen} onClose={onClose} title={`Eksekusi Order — ${symbol}`} size="lg">
<div className="space-y-4 text-xs">
{/* ── 1. Top Header: Bias Badge & Bybit Connection Status ─────────── */}
<div className="flex flex-wrap items-center justify-between gap-2 p-3 rounded-xl bg-bg-elevated/60 border border-border">
<div className="flex items-center gap-2">
<div
className={`px-2.5 py-1 rounded-lg text-xs font-bold font-mono flex items-center gap-1.5 border ${
isShort
? 'bg-rose-500/20 text-rose-300 border-rose-500/40'
: 'bg-emerald-500/20 text-emerald-300 border-emerald-500/40'
}`}
>
{isShort ? <TrendingDown size={14} /> : <TrendingUp size={14} />}
<span>{defaultSide.toUpperCase()} ({summary.bias})</span>
</div>
<span className="text-[11px] text-text-muted font-mono hidden sm:inline">
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'}
</span>
</div>
{/* Bybit Account Status Pill */}
<div className="flex items-center gap-2">
{settings?.configured ? (
<div className="flex items-center gap-1.5 px-2.5 py-1 rounded-lg bg-emerald-500/10 border border-emerald-500/30 text-[11px] text-emerald-300 font-mono">
<CheckCircle2 size={12} className="text-emerald-400" />
<span className="font-semibold uppercase">{settings.mode} Bybit</span>
{balance && (
<span className="text-emerald-400 font-bold ml-1">
${(balance.total_equity || balance.available_balance).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })} USDT
</span>
)}
</div>
) : (
<div className="flex items-center gap-1.5 px-2.5 py-1 rounded-lg bg-amber-500/15 border border-amber-500/30 text-[11px] text-amber-300 font-mono">
<AlertTriangle size={12} className="text-amber-400" />
<span>API Belum Terpasang</span>
</div>
)}
<button
type="button"
onClick={() => setIsConfiguringKey(!isConfiguringKey)}
className="p-1.5 rounded-lg bg-bg-card hover:bg-bg-elevated border border-border text-text-muted hover:text-text-primary transition-colors"
title="Konfigurasi API Key Bybit"
>
<Settings2 size={13} />
</button>
</div>
</div>
{/* ── 2. Auth Gate Alert OR Collapsible API Key Drawer ─────────────── */}
{authErrorMsg && (
<div className="p-3 rounded-xl bg-rose-500/15 border border-rose-500/40 text-rose-200 flex items-start gap-2.5 text-xs">
<AlertTriangle size={15} className="text-rose-400 shrink-0 mt-0.5" />
<div>
<p className="font-semibold">Autentikasi Server Dibutuhkan</p>
<p className="text-[11px] text-rose-200/80 mt-0.5">{authErrorMsg}</p>
</div>
</div>
)}
{isConfiguringKey && (
<div className="p-3.5 rounded-xl bg-purple-950/30 border border-purple-500/40 space-y-3 animate-fade-in">
<div className="flex flex-wrap items-center justify-between gap-2">
<span className="text-xs font-bold text-purple-200 flex items-center gap-1.5">
<Key size={14} className="text-purple-400" />
Kredensial API Bybit (Stateless Per-Sesi)
</span>
<span className="text-[10px] text-purple-300/80 flex items-center gap-1">
<Lock size={10} /> Disimpan hanya di sessionStorage & dikirim per-request
</span>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2.5">
<div>
<label className="text-[10px] uppercase font-bold text-text-muted block mb-1">
Bybit API Key
</label>
<input
type="text"
value={apiKeyInput}
onChange={(e) => 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"
/>
</div>
<div>
<label className="text-[10px] uppercase font-bold text-text-muted block mb-1">
Bybit API Secret
</label>
<input
type="password"
value={apiSecretInput}
onChange={(e) => 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"
/>
</div>
</div>
<div className="flex flex-wrap items-center justify-between gap-2 pt-1">
<div className="flex items-center gap-2">
<span className="text-[10px] font-bold text-text-muted uppercase">Lingkungan:</span>
<div className="flex items-center gap-1">
{[
{ id: 'demo', label: 'Bybit Demo (api-demo)' },
{ id: 'testnet', label: 'Testnet' },
{ id: 'real', label: 'Live Real' },
].map((m) => (
<button
key={m.id}
type="button"
onClick={() => setModeInput(m.id as any)}
className={`px-2 py-1 rounded text-[10px] font-mono font-semibold transition-all ${
modeInput === m.id
? 'bg-purple-600 text-white shadow-sm'
: 'bg-bg-card text-text-secondary hover:text-text-primary border border-border'
}`}
>
{m.label}
</button>
))}
</div>
</div>
<div className="flex items-center gap-1.5">
{getStoredBybitCredentials() && (
<Button
variant="ghost"
size="sm"
onClick={handleClearSessionCredentials}
icon={<Trash2 size={12} />}
className="text-rose-300 hover:text-rose-200"
>
Hapus Key Sesi
</Button>
)}
{settings?.configured && (
<Button variant="ghost" size="sm" onClick={() => setIsConfiguringKey(false)}>
Batal
</Button>
)}
<Button
variant="primary"
size="sm"
onClick={handleSaveCredentials}
loading={isSavingKey}
className="bg-purple-600 hover:bg-purple-500 text-white"
>
Simpan & Hubungkan
</Button>
</div>
</div>
</div>
)}
{/* ── 3. Position Sizing & Margin Allocation ──────────────────────── */}
<div className="p-3.5 rounded-xl bg-bg-elevated/40 border border-border space-y-3">
<div className="flex flex-wrap items-center justify-between gap-2">
<div className="flex items-center gap-2">
<span className="text-[11px] font-bold uppercase tracking-wider text-text-secondary flex items-center gap-1.5">
<Wallet size={13} className="text-purple-400" />
Alokasi Modal Margin
</span>
{/* Segmented Sizing Mode Switcher */}
<div className="flex items-center rounded-lg border border-border bg-bg-card p-0.5">
<button
type="button"
onClick={() => setSizingMode('percent')}
className={`px-2.5 py-0.5 rounded text-[10px] font-bold transition-all ${
sizingMode === 'percent'
? 'bg-purple-600 text-white shadow-sm'
: 'text-text-muted hover:text-text-primary'
}`}
>
% Equity
</button>
<button
type="button"
onClick={() => setSizingMode('usd')}
className={`px-2.5 py-0.5 rounded text-[10px] font-bold transition-all ${
sizingMode === 'usd'
? 'bg-purple-600 text-white shadow-sm'
: 'text-text-muted hover:text-text-primary'
}`}
>
$ USD
</button>
</div>
</div>
<span className="text-[11px] font-mono font-bold text-purple-300">
Notional Posisi: ${notionalUsd.toLocaleString(undefined, { minimumFractionDigits: 1, maximumFractionDigits: 1 })} USD
</span>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
{/* Left Column: Sizing Input according to active mode */}
<div className="space-y-1.5">
{sizingMode === 'percent' ? (
<>
<div className="flex items-center gap-2">
<div className="relative flex-1">
<input
type="number"
min="0.1"
max="100"
step="0.5"
value={marginPctDraft}
onChange={(e) => {
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"
/>
<span className="absolute right-3 top-2 text-text-muted font-mono text-xs font-bold">%</span>
</div>
{/* Quick % Pills */}
<div className="flex items-center gap-1">
{[1, 2, 5, 10, 20].map((pct) => (
<button
key={pct}
type="button"
onClick={() => {
setMarginPercent(pct);
setMarginPctDraft(String(pct));
}}
className={`px-2 py-1.5 rounded-lg text-[10px] font-mono font-semibold border transition-all ${
marginPercent === pct
? 'bg-purple-600/30 border-purple-500 text-purple-200'
: 'bg-bg-card border-border text-text-muted hover:text-text-primary'
}`}
>
{pct}%
</button>
))}
</div>
</div>
{/* Live Equity Calculation Conversion */}
<div className="text-[10.5px] font-mono">
{totalEquity > 0 ? (
<span className="text-purple-300">
⚡ <strong>{marginPercent}%</strong> = <strong className="text-emerald-400">${calculatedPercentMargin.toFixed(2)} USD</strong> (dari equity ${totalEquity.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })})
</span>
) : (
<span className="text-amber-400/90 flex items-center gap-1">
<AlertTriangle size={11} /> Saldo equity $0 / belum terhubung. Silakan gunakan tab "$ USD".
</span>
)}
</div>
</>
) : (
<>
<div className="flex items-center gap-2">
<div className="relative flex-1">
<span className="absolute left-3 top-2 text-text-muted font-mono text-xs">$</span>
<input
type="number"
min="0.1"
max="50000"
step="5"
value={marginUsdDraft}
onChange={(e) => {
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"
/>
</div>
{/* Quick USD Pills */}
<div className="flex items-center gap-1">
{[25, 50, 100, 200].map((amt) => (
<button
key={amt}
type="button"
onClick={() => {
setMarginUsd(amt);
setMarginUsdDraft(String(amt));
}}
className={`px-2 py-1.5 rounded-lg text-[10px] font-mono font-semibold border transition-all ${
marginUsd === amt
? 'bg-purple-600/30 border-purple-500 text-purple-200'
: 'bg-bg-card border-border text-text-muted hover:text-text-primary'
}`}
>
${amt}
</button>
))}
</div>
</div>
{/* USD to % Comparison */}
<div className="text-[10.5px] font-mono text-text-muted">
{totalEquity > 0 ? (
<span>
ℹ️ ${marginUsd.toFixed(2)} USD ≈ <strong className="text-purple-300">{((marginUsd / totalEquity) * 100).toFixed(1)}%</strong> dari total equity (${totalEquity.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })})
</span>
) : (
<span>ℹ️ Nominal margin tetap ${marginUsd.toFixed(2)} USD</span>
)}
</div>
</>
)}
</div>
{/* Right Column: Leverage & Order Type Selector */}
<div className="flex items-center gap-2">
<div className="flex-1">
<div className="flex items-center justify-between text-[10px] text-text-muted mb-1">
<span className="uppercase font-bold">Leverage:</span>
<span className="font-mono text-purple-300 font-bold">{leverage}x</span>
</div>
<input
type="range"
min="1"
max="25"
step="1"
value={leverage}
onChange={(e) => setLeverage(parseInt(e.target.value, 10))}
className="w-full accent-purple-500 cursor-pointer"
/>
</div>
<div className="flex items-center rounded-lg border border-border bg-bg-card p-0.5 shrink-0 self-end">
<button
type="button"
onClick={() => setOrderType('Limit')}
className={`px-2.5 py-1.5 rounded-md text-[10px] font-bold transition-all ${
orderType === 'Limit' ? 'bg-purple-600 text-white shadow-sm' : 'text-text-muted'
}`}
>
Limit
</button>
<button
type="button"
onClick={() => setOrderType('Market')}
className={`px-2.5 py-1.5 rounded-md text-[10px] font-bold transition-all ${
orderType === 'Market' ? 'bg-purple-600 text-white shadow-sm' : 'text-text-muted'
}`}
>
Market
</button>
</div>
</div>
</div>
</div>
{/* ── 4. Key Price Levels (Auto-filled from Damian) ───────────────── */}
<div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
{/* Entry */}
<div className="p-2.5 rounded-xl bg-bg-card border border-border space-y-1">
<span className="text-[9px] uppercase font-bold text-text-muted block">
{orderType === 'Limit' ? 'ENTRY PRICE (LIMIT)' : 'ENTRY MARKET'}
</span>
<input
type="number"
step="any"
disabled={orderType === 'Market'}
value={entryDraft}
onChange={(e) => {
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"
/>
</div>
{/* Stop Loss */}
<div className="p-2.5 rounded-xl bg-rose-500/10 border border-rose-500/25 space-y-1">
<span className="text-[9px] uppercase font-bold text-rose-300/80 flex items-center justify-between">
<span>STOP LOSS (SL)</span>
<ShieldAlert size={11} className="text-rose-400" />
</span>
<input
type="number"
step="any"
value={slDraft}
onChange={(e) => {
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"
/>
</div>
{/* Take Profit 1 */}
<div className="p-2.5 rounded-xl bg-emerald-500/10 border border-emerald-500/25 space-y-1">
<span className="text-[9px] uppercase font-bold text-emerald-300/80 flex items-center justify-between">
<span>TARGET TP1</span>
<Target size={11} className="text-emerald-400" />
</span>
<input
type="number"
step="any"
value={tp1Draft}
onChange={(e) => {
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"
/>
</div>
{/* Take Profit 2 (Optional) */}
<div className="p-2.5 rounded-xl bg-emerald-500/10 border border-emerald-500/25 space-y-1">
<span className="text-[9px] uppercase font-bold text-emerald-300/80 flex items-center justify-between">
<span>TARGET TP2</span>
<Target size={11} className="text-emerald-400" />
</span>
<input
type="number"
step="any"
value={tp2Draft}
onChange={(e) => {
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"
/>
</div>
</div>
{/* ── 5. Custom Split Take Profit (TP1 %) Slider ──────────────────── */}
<div className="p-3.5 rounded-xl bg-purple-950/20 border border-purple-500/30 space-y-2.5">
<div className="flex items-center justify-between">
<span className="text-[11px] font-bold uppercase tracking-wider text-purple-200 flex items-center gap-1.5">
<Zap size={13} className="text-purple-400" />
Porsi Ambil Cuan TP1 (Custom Split)
</span>
<div className="flex items-center gap-1">
{[25, 50, 75, 100].map((pct) => (
<button
key={pct}
type="button"
onClick={() => setTp1Percent(pct)}
className={`px-2 py-0.5 rounded text-[10px] font-mono font-bold transition-all ${
tp1Percent === pct
? 'bg-purple-600 text-white shadow-sm'
: 'bg-bg-card border border-border text-text-muted hover:text-text-primary'
}`}
>
{pct}%
</button>
))}
</div>
</div>
<div className="space-y-1">
<input
type="range"
min="10"
max="100"
step="5"
value={tp1Percent}
onChange={(e) => setTp1Percent(parseInt(e.target.value, 10))}
className="w-full accent-purple-500 cursor-pointer"
/>
<div className="flex items-center justify-between text-[10px] font-mono text-purple-300/90">
<span>TP1: {tp1Percent}%</span>
<span>{tp1Percent < 100 ? `TP2: ${100 - tp1Percent}%` : 'TP2: Dinonaktifkan'}</span>
</div>
</div>
{/* Explanation Text */}
<p className="text-[11px] text-purple-200/90 leading-tight">
{tp1Percent >= 100 ? (
<span>🎯 100% posisi akan ditutup penuh di <strong>TP1</strong> saat harga tercapai.</span>
) : (
<span>
🎯 <strong>{tp1Percent}%</strong> posisi akan ditutup di <strong>TP1</strong> (${takeProfit1}), dan sisa <strong>{100 - tp1Percent}%</strong> dibiarkan berlari ke <strong>TP2</strong> (${takeProfit2 || 'Runner'}).
</span>
)}
</p>
{/* Auto-Breakeven SL after TP1 Toggle */}
{tp1Percent < 100 && Boolean(takeProfit2) && (
<div className="pt-2 border-t border-purple-500/20 flex items-start justify-between gap-3">
<label className="flex items-start gap-2 cursor-pointer select-none">
<input
type="checkbox"
checked={autoBreakeven}
onChange={(e) => setAutoBreakeven(e.target.checked)}
className="mt-0.5 accent-emerald-500 rounded cursor-pointer"
/>
<div className="space-y-0.5">
<span className="text-[11px] font-bold text-emerald-300 block">
🛡️ Auto-Breakeven SL setelah TP1 (+6 bps Fee Buffer)
</span>
<span className="text-[10px] text-text-muted block leading-snug">
Saat TP1 tercapai, SL sisa runner otomatis digeser ke Harga Entry ±6 bps (aktif 12 jam di server persistent; manual di mode serverless).
</span>
</div>
</label>
</div>
)}
</div>
{/* ── 6. Live Risk & Reward Preview Summary ────────────────────────── */}
<div className="p-3 rounded-xl bg-bg-elevated/40 border border-border flex flex-wrap items-center justify-between gap-3 text-xs">
<div>
<span className="text-[10px] text-text-muted uppercase font-bold block">POTENSI CUAN TOTAL</span>
<span className="text-sm font-bold font-mono text-emerald-400">
+${totalEstGain.toFixed(2)} USD
</span>
</div>
<div>
<span className="text-[10px] text-text-muted uppercase font-bold block">MAKSIMAL RISIKO (SL)</span>
<span className="text-sm font-bold font-mono text-rose-400">
-${Math.abs(estLossUsd).toFixed(2)} USD
</span>
</div>
<div>
<span className="text-[10px] text-text-muted uppercase font-bold block">RISK / REWARD RIIL</span>
<span className="text-sm font-bold font-mono text-purple-300">
1 : {estimatedRR}
</span>
</div>
</div>
{/* ── 7. Action Button ────────────────────────────────────────────── */}
<div className="flex items-center justify-end gap-2 pt-2 border-t border-border/50">
<Button variant="ghost" size="md" onClick={onClose} disabled={isSubmitting}>
Batal
</Button>
<Button
variant="primary"
size="md"
onClick={handleExecute}
loading={isSubmitting}
icon={<Zap size={15} />}
className="bg-purple-600 hover:bg-purple-500 text-white font-bold px-5 shadow-lg shadow-purple-600/30"
>
Eksekusi Order ke Bybit
</Button>
</div>
</div>
</Modal>
);
}