Spaces:
Sleeping
Sleeping
File size: 41,812 Bytes
80df99b 86abcb2 740fcec 86abcb2 740fcec 86abcb2 075133b 86abcb2 075133b abeb2e6 075133b abeb2e6 86abcb2 abeb2e6 86abcb2 075133b 86abcb2 075133b 86abcb2 cc3aa02 48f60d7 86abcb2 48f60d7 86abcb2 48f60d7 86abcb2 48f60d7 86abcb2 48f60d7 86abcb2 48f60d7 86abcb2 740fcec 86abcb2 740fcec 80df99b 740fcec 80df99b 075133b 80df99b 740fcec 48f60d7 740fcec 48f60d7 740fcec 48f60d7 740fcec 48f60d7 740fcec 80df99b 740fcec 075133b 740fcec 86abcb2 740fcec 86abcb2 740fcec 86abcb2 740fcec 86abcb2 740fcec 86abcb2 cc3aa02 48f60d7 cc3aa02 48f60d7 cc3aa02 86abcb2 48f60d7 cc3aa02 86abcb2 80df99b 86abcb2 80df99b 86abcb2 075133b 86abcb2 cc3aa02 48f60d7 cc3aa02 86abcb2 80df99b 86abcb2 48f60d7 abeb2e6 48f60d7 abeb2e6 48f60d7 abeb2e6 86abcb2 075133b cc3aa02 86abcb2 740fcec 86abcb2 80df99b 86abcb2 cc3aa02 86abcb2 740fcec 86abcb2 740fcec 86abcb2 740fcec 86abcb2 740fcec 86abcb2 740fcec 86abcb2 cc3aa02 86abcb2 cc3aa02 86abcb2 cc3aa02 48f60d7 cc3aa02 48f60d7 cc3aa02 48f60d7 cc3aa02 48f60d7 cc3aa02 48f60d7 cc3aa02 48f60d7 cc3aa02 86abcb2 cc3aa02 86abcb2 48f60d7 86abcb2 48f60d7 86abcb2 48f60d7 86abcb2 48f60d7 86abcb2 740fcec 86abcb2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 | 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>
);
}
|