Spaces:
Sleeping
Sleeping
Naufal Arhab commited on
Commit ·
cc3aa02
1
Parent(s): abeb2e6
feat(execution): add % equity portfolio sizing mode with live conversion and quick pills
Browse files
backend/engine/execution/bybit_executor.py
CHANGED
|
@@ -104,16 +104,14 @@ class BybitExecutor:
|
|
| 104 |
# -------------------------------------------------------------------------
|
| 105 |
|
| 106 |
async def get_wallet_balance(self) -> dict[str, Any]:
|
| 107 |
-
"""Fetch Unified/Futures USDT available balance."""
|
| 108 |
data = await self._request("GET", "/v5/account/wallet-balance", {"accountType": "UNIFIED"})
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
.get("list", [{}])[0]
|
| 112 |
-
.get("coin", [])
|
| 113 |
-
)
|
| 114 |
usdt_info = next((c for c in coins if c.get("coin") == "USDT"), {})
|
|
|
|
| 115 |
available_balance = float(usdt_info.get("availableToWithdraw") or usdt_info.get("walletBalance") or 0.0)
|
| 116 |
-
total_equity = float(usdt_info.get("equity") or usdt_info.get("walletBalance") or 0.0)
|
| 117 |
|
| 118 |
return {
|
| 119 |
"coin": "USDT",
|
|
|
|
| 104 |
# -------------------------------------------------------------------------
|
| 105 |
|
| 106 |
async def get_wallet_balance(self) -> dict[str, Any]:
|
| 107 |
+
"""Fetch Unified/Futures USDT available balance and total equity."""
|
| 108 |
data = await self._request("GET", "/v5/account/wallet-balance", {"accountType": "UNIFIED"})
|
| 109 |
+
acct_item = data.get("result", {}).get("list", [{}])[0]
|
| 110 |
+
coins = acct_item.get("coin", [])
|
|
|
|
|
|
|
|
|
|
| 111 |
usdt_info = next((c for c in coins if c.get("coin") == "USDT"), {})
|
| 112 |
+
acct_equity = float(acct_item.get("totalEquity") or 0.0)
|
| 113 |
available_balance = float(usdt_info.get("availableToWithdraw") or usdt_info.get("walletBalance") or 0.0)
|
| 114 |
+
total_equity = float(usdt_info.get("equity") or acct_equity or usdt_info.get("walletBalance") or 0.0)
|
| 115 |
|
| 116 |
return {
|
| 117 |
"coin": "USDT",
|
backend/routers/execution.py
CHANGED
|
@@ -56,7 +56,8 @@ class ExecuteBybitOrderRequest(BaseModel):
|
|
| 56 |
symbol: str
|
| 57 |
side: str # "Buy" | "Sell" | "Long" | "Short"
|
| 58 |
order_type: str = "Market" # "Market" | "Limit"
|
| 59 |
-
margin_usd: float = Field(.
|
|
|
|
| 60 |
leverage: int = Field(..., ge=1, le=50, description="Rekomendasi leverage")
|
| 61 |
stop_loss: float = Field(..., gt=0, description="Harga Stop Loss")
|
| 62 |
take_profit_1: float = Field(..., gt=0, description="Harga Take Profit 1")
|
|
@@ -140,6 +141,27 @@ async def execute_bybit_order(body: ExecuteBybitOrderRequest):
|
|
| 140 |
req_mode=body.mode,
|
| 141 |
)
|
| 142 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
try:
|
| 144 |
exec_result = await executor.execute_trade_setup(
|
| 145 |
symbol=body.symbol,
|
|
@@ -166,13 +188,19 @@ async def execute_bybit_order(body: ExecuteBybitOrderRequest):
|
|
| 166 |
|
| 167 |
entry_str = f"${body.entry_price:,.4f}" if body.entry_price else "MARKET ORDER"
|
| 168 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
journal_entry = await async_create_journal_entry({
|
| 170 |
"symbol": body.symbol.upper(),
|
| 171 |
"bias": bias_label,
|
| 172 |
"entry_zone": entry_str,
|
| 173 |
"stop_loss": f"${body.stop_loss:,.4f}",
|
| 174 |
"take_profit": tp_str,
|
| 175 |
-
"risk_reward":
|
| 176 |
"leverage": f"{body.leverage}x",
|
| 177 |
"invalidation": f"Bybit Order ID: {exec_result.get('entry_order_id', 'N/A')}",
|
| 178 |
"summary_tldr": body.summary_tldr or f"Order dieksekusi otomatis ke Bybit ({exec_result.get('mode', 'DEMO').upper()})",
|
|
@@ -181,6 +209,7 @@ async def execute_bybit_order(body: ExecuteBybitOrderRequest):
|
|
| 181 |
"execution_result": exec_result,
|
| 182 |
"mode": exec_result.get("mode"),
|
| 183 |
"margin_usd": body.margin_usd,
|
|
|
|
| 184 |
"tp1_percent": body.tp1_percent,
|
| 185 |
},
|
| 186 |
"status": "PENDING",
|
|
|
|
| 56 |
symbol: str
|
| 57 |
side: str # "Buy" | "Sell" | "Long" | "Short"
|
| 58 |
order_type: str = "Market" # "Market" | "Limit"
|
| 59 |
+
margin_usd: float = Field(default=0.0, ge=0, description="Nominal modal margin dalam USD")
|
| 60 |
+
margin_percent: float | None = Field(default=None, ge=0.1, le=100.0, description="Persentase alokasi equity (opsional)")
|
| 61 |
leverage: int = Field(..., ge=1, le=50, description="Rekomendasi leverage")
|
| 62 |
stop_loss: float = Field(..., gt=0, description="Harga Stop Loss")
|
| 63 |
take_profit_1: float = Field(..., gt=0, description="Harga Take Profit 1")
|
|
|
|
| 141 |
req_mode=body.mode,
|
| 142 |
)
|
| 143 |
|
| 144 |
+
# If margin_usd not explicitly provided or is 0, but margin_percent is given, calculate from equity
|
| 145 |
+
if (body.margin_usd <= 0) and body.margin_percent:
|
| 146 |
+
bal = await executor.get_wallet_balance()
|
| 147 |
+
equity = float(bal.get("total_equity") or bal.get("available_balance") or 0.0)
|
| 148 |
+
if equity <= 0:
|
| 149 |
+
raise HTTPException(
|
| 150 |
+
status_code=400,
|
| 151 |
+
detail="Total equity Bybit terdeteksi $0, tidak dapat menghitung alokasi margin persen.",
|
| 152 |
+
)
|
| 153 |
+
body.margin_usd = round(equity * (body.margin_percent / 100.0), 2)
|
| 154 |
+
if body.margin_usd <= 0:
|
| 155 |
+
raise HTTPException(
|
| 156 |
+
status_code=400,
|
| 157 |
+
detail="Hasil perhitungan margin terlalu kecil (< $0.01).",
|
| 158 |
+
)
|
| 159 |
+
elif body.margin_usd <= 0:
|
| 160 |
+
raise HTTPException(
|
| 161 |
+
status_code=400,
|
| 162 |
+
detail="Margin USD harus lebih besar dari 0 atau tentukan persentase alokasi equity.",
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
try:
|
| 166 |
exec_result = await executor.execute_trade_setup(
|
| 167 |
symbol=body.symbol,
|
|
|
|
| 188 |
|
| 189 |
entry_str = f"${body.entry_price:,.4f}" if body.entry_price else "MARKET ORDER"
|
| 190 |
|
| 191 |
+
margin_label = (
|
| 192 |
+
f"Margin: ${body.margin_usd:.1f} ({body.margin_percent:.1f}% eq) | Lev: {body.leverage}x"
|
| 193 |
+
if body.margin_percent
|
| 194 |
+
else f"Margin: ${body.margin_usd:.1f} | Lev: {body.leverage}x"
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
journal_entry = await async_create_journal_entry({
|
| 198 |
"symbol": body.symbol.upper(),
|
| 199 |
"bias": bias_label,
|
| 200 |
"entry_zone": entry_str,
|
| 201 |
"stop_loss": f"${body.stop_loss:,.4f}",
|
| 202 |
"take_profit": tp_str,
|
| 203 |
+
"risk_reward": margin_label,
|
| 204 |
"leverage": f"{body.leverage}x",
|
| 205 |
"invalidation": f"Bybit Order ID: {exec_result.get('entry_order_id', 'N/A')}",
|
| 206 |
"summary_tldr": body.summary_tldr or f"Order dieksekusi otomatis ke Bybit ({exec_result.get('mode', 'DEMO').upper()})",
|
|
|
|
| 209 |
"execution_result": exec_result,
|
| 210 |
"mode": exec_result.get("mode"),
|
| 211 |
"margin_usd": body.margin_usd,
|
| 212 |
+
"margin_percent": body.margin_percent,
|
| 213 |
"tp1_percent": body.tp1_percent,
|
| 214 |
},
|
| 215 |
"status": "PENDING",
|
frontend/src/api/execution.ts
CHANGED
|
@@ -19,6 +19,7 @@ export interface ExecuteOrderPayload {
|
|
| 19 |
side: 'Buy' | 'Sell' | 'Long' | 'Short';
|
| 20 |
order_type: 'Market' | 'Limit';
|
| 21 |
margin_usd: number;
|
|
|
|
| 22 |
leverage: number;
|
| 23 |
stop_loss: number;
|
| 24 |
take_profit_1: number;
|
|
|
|
| 19 |
side: 'Buy' | 'Sell' | 'Long' | 'Short';
|
| 20 |
order_type: 'Market' | 'Limit';
|
| 21 |
margin_usd: number;
|
| 22 |
+
margin_percent?: number | null;
|
| 23 |
leverage: number;
|
| 24 |
stop_loss: number;
|
| 25 |
take_profit_1: number;
|
frontend/src/components/execution/ExecutionModal.tsx
CHANGED
|
@@ -78,6 +78,8 @@ export function ExecutionModal({
|
|
| 78 |
|
| 79 |
// Form State
|
| 80 |
const [orderType, setOrderType] = useState<'Market' | 'Limit'>('Limit');
|
|
|
|
|
|
|
| 81 |
const [marginUsd, setMarginUsd] = useState<number>(50);
|
| 82 |
const [leverage, setLeverage] = useState<number>(defaultLev);
|
| 83 |
const [entryPrice, setEntryPrice] = useState<number>(rawEntry);
|
|
@@ -157,9 +159,22 @@ export function ExecutionModal({
|
|
| 157 |
}
|
| 158 |
};
|
| 159 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
// Calculations for preview
|
| 161 |
const refPrice = orderType === 'Limit' && entryPrice > 0 ? entryPrice : (markPrice || entryPrice || 1.0);
|
| 162 |
-
const notionalUsd =
|
| 163 |
|
| 164 |
const estLossUsd = refPrice > 0
|
| 165 |
? (isShort ? (stopLoss - refPrice) / refPrice : (refPrice - stopLoss) / refPrice) * notionalUsd
|
|
@@ -186,8 +201,24 @@ export function ExecutionModal({
|
|
| 186 |
return;
|
| 187 |
}
|
| 188 |
|
| 189 |
-
if (
|
| 190 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
return;
|
| 192 |
}
|
| 193 |
|
|
@@ -231,7 +262,8 @@ export function ExecutionModal({
|
|
| 231 |
symbol,
|
| 232 |
side: defaultSide,
|
| 233 |
order_type: orderType,
|
| 234 |
-
margin_usd:
|
|
|
|
| 235 |
leverage,
|
| 236 |
stop_loss: stopLoss,
|
| 237 |
take_profit_1: takeProfit1,
|
|
@@ -283,7 +315,7 @@ export function ExecutionModal({
|
|
| 283 |
<span className="font-semibold uppercase">{settings.mode} Bybit</span>
|
| 284 |
{balance && (
|
| 285 |
<span className="text-emerald-400 font-bold ml-1">
|
| 286 |
-
${balance.available_balance.toLocaleString(undefined, { maximumFractionDigits:
|
| 287 |
</span>
|
| 288 |
)}
|
| 289 |
</div>
|
|
@@ -393,51 +425,146 @@ export function ExecutionModal({
|
|
| 393 |
|
| 394 |
{/* ── 3. Position Sizing & Margin Allocation ──────────────────────── */}
|
| 395 |
<div className="p-3.5 rounded-xl bg-bg-elevated/40 border border-border space-y-3">
|
| 396 |
-
<div className="flex items-center justify-between">
|
| 397 |
-
<
|
| 398 |
-
<
|
| 399 |
-
|
| 400 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 401 |
<span className="text-[11px] font-mono font-bold text-purple-300">
|
| 402 |
-
Notional Posisi: ${
|
| 403 |
</span>
|
| 404 |
</div>
|
| 405 |
|
| 406 |
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
| 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 |
</div>
|
| 439 |
|
| 440 |
-
{/* Leverage & Order Type Selector */}
|
| 441 |
<div className="flex items-center gap-2">
|
| 442 |
<div className="flex-1">
|
| 443 |
<div className="flex items-center justify-between text-[10px] text-text-muted mb-1">
|
|
|
|
| 78 |
|
| 79 |
// Form State
|
| 80 |
const [orderType, setOrderType] = useState<'Market' | 'Limit'>('Limit');
|
| 81 |
+
const [sizingMode, setSizingMode] = useState<'percent' | 'usd'>('percent');
|
| 82 |
+
const [marginPercent, setMarginPercent] = useState<number>(5);
|
| 83 |
const [marginUsd, setMarginUsd] = useState<number>(50);
|
| 84 |
const [leverage, setLeverage] = useState<number>(defaultLev);
|
| 85 |
const [entryPrice, setEntryPrice] = useState<number>(rawEntry);
|
|
|
|
| 159 |
}
|
| 160 |
};
|
| 161 |
|
| 162 |
+
// Total Equity resolution & Effective Margin Calculation
|
| 163 |
+
const totalEquity = (balance?.total_equity && balance.total_equity > 0)
|
| 164 |
+
? balance.total_equity
|
| 165 |
+
: (balance?.available_balance && balance.available_balance > 0 ? balance.available_balance : 0);
|
| 166 |
+
|
| 167 |
+
const calculatedPercentMargin = totalEquity > 0
|
| 168 |
+
? Math.max(1, Math.round((totalEquity * (marginPercent / 100)) * 100) / 100)
|
| 169 |
+
: 0;
|
| 170 |
+
|
| 171 |
+
const effectiveMargin = sizingMode === 'percent' && totalEquity > 0
|
| 172 |
+
? calculatedPercentMargin
|
| 173 |
+
: marginUsd;
|
| 174 |
+
|
| 175 |
// Calculations for preview
|
| 176 |
const refPrice = orderType === 'Limit' && entryPrice > 0 ? entryPrice : (markPrice || entryPrice || 1.0);
|
| 177 |
+
const notionalUsd = effectiveMargin * leverage;
|
| 178 |
|
| 179 |
const estLossUsd = refPrice > 0
|
| 180 |
? (isShort ? (stopLoss - refPrice) / refPrice : (refPrice - stopLoss) / refPrice) * notionalUsd
|
|
|
|
| 201 |
return;
|
| 202 |
}
|
| 203 |
|
| 204 |
+
if (sizingMode === 'percent') {
|
| 205 |
+
if (totalEquity <= 0) {
|
| 206 |
+
toast('Total equity Bybit terdeteksi $0 atau API belum terhubung. Silakan beralih ke tab "$ USD Tetap" atau hubungkan API Bybit.', 'error');
|
| 207 |
+
return;
|
| 208 |
+
}
|
| 209 |
+
if (marginPercent <= 0 || marginPercent > 100) {
|
| 210 |
+
toast('Persentase alokasi equity harus antara 0.1% hingga 100%.', 'error');
|
| 211 |
+
return;
|
| 212 |
+
}
|
| 213 |
+
} else {
|
| 214 |
+
if (marginUsd <= 0) {
|
| 215 |
+
toast('Masukkan margin yang valid (> $0).', 'error');
|
| 216 |
+
return;
|
| 217 |
+
}
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
+
if (effectiveMargin <= 0) {
|
| 221 |
+
toast('Margin efektif tidak valid atau $0.', 'error');
|
| 222 |
return;
|
| 223 |
}
|
| 224 |
|
|
|
|
| 262 |
symbol,
|
| 263 |
side: defaultSide,
|
| 264 |
order_type: orderType,
|
| 265 |
+
margin_usd: effectiveMargin,
|
| 266 |
+
margin_percent: sizingMode === 'percent' ? marginPercent : null,
|
| 267 |
leverage,
|
| 268 |
stop_loss: stopLoss,
|
| 269 |
take_profit_1: takeProfit1,
|
|
|
|
| 315 |
<span className="font-semibold uppercase">{settings.mode} Bybit</span>
|
| 316 |
{balance && (
|
| 317 |
<span className="text-emerald-400 font-bold ml-1">
|
| 318 |
+
${(balance.total_equity || balance.available_balance).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })} USDT
|
| 319 |
</span>
|
| 320 |
)}
|
| 321 |
</div>
|
|
|
|
| 425 |
|
| 426 |
{/* ── 3. Position Sizing & Margin Allocation ──────────────────────── */}
|
| 427 |
<div className="p-3.5 rounded-xl bg-bg-elevated/40 border border-border space-y-3">
|
| 428 |
+
<div className="flex flex-wrap items-center justify-between gap-2">
|
| 429 |
+
<div className="flex items-center gap-2">
|
| 430 |
+
<span className="text-[11px] font-bold uppercase tracking-wider text-text-secondary flex items-center gap-1.5">
|
| 431 |
+
<Wallet size={13} className="text-purple-400" />
|
| 432 |
+
Alokasi Modal Margin
|
| 433 |
+
</span>
|
| 434 |
+
|
| 435 |
+
{/* Segmented Sizing Mode Switcher */}
|
| 436 |
+
<div className="flex items-center rounded-lg border border-border bg-bg-card p-0.5">
|
| 437 |
+
<button
|
| 438 |
+
type="button"
|
| 439 |
+
onClick={() => setSizingMode('percent')}
|
| 440 |
+
className={`px-2.5 py-0.5 rounded text-[10px] font-bold transition-all ${
|
| 441 |
+
sizingMode === 'percent'
|
| 442 |
+
? 'bg-purple-600 text-white shadow-sm'
|
| 443 |
+
: 'text-text-muted hover:text-text-primary'
|
| 444 |
+
}`}
|
| 445 |
+
>
|
| 446 |
+
% Equity
|
| 447 |
+
</button>
|
| 448 |
+
<button
|
| 449 |
+
type="button"
|
| 450 |
+
onClick={() => setSizingMode('usd')}
|
| 451 |
+
className={`px-2.5 py-0.5 rounded text-[10px] font-bold transition-all ${
|
| 452 |
+
sizingMode === 'usd'
|
| 453 |
+
? 'bg-purple-600 text-white shadow-sm'
|
| 454 |
+
: 'text-text-muted hover:text-text-primary'
|
| 455 |
+
}`}
|
| 456 |
+
>
|
| 457 |
+
$ USD
|
| 458 |
+
</button>
|
| 459 |
+
</div>
|
| 460 |
+
</div>
|
| 461 |
+
|
| 462 |
<span className="text-[11px] font-mono font-bold text-purple-300">
|
| 463 |
+
Notional Posisi: ${notionalUsd.toLocaleString(undefined, { minimumFractionDigits: 1, maximumFractionDigits: 1 })} USD
|
| 464 |
</span>
|
| 465 |
</div>
|
| 466 |
|
| 467 |
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
| 468 |
+
{/* Left Column: Sizing Input according to active mode */}
|
| 469 |
+
<div className="space-y-1.5">
|
| 470 |
+
{sizingMode === 'percent' ? (
|
| 471 |
+
<>
|
| 472 |
+
<div className="flex items-center gap-2">
|
| 473 |
+
<div className="relative flex-1">
|
| 474 |
+
<input
|
| 475 |
+
type="number"
|
| 476 |
+
min="0.5"
|
| 477 |
+
max="100"
|
| 478 |
+
step="0.5"
|
| 479 |
+
value={marginPercent}
|
| 480 |
+
onChange={(e) => setMarginPercent(Math.max(0.1, parseFloat(e.target.value) || 0))}
|
| 481 |
+
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"
|
| 482 |
+
/>
|
| 483 |
+
<span className="absolute right-3 top-2 text-text-muted font-mono text-xs font-bold">%</span>
|
| 484 |
+
</div>
|
| 485 |
+
|
| 486 |
+
{/* Quick % Pills */}
|
| 487 |
+
<div className="flex items-center gap-1">
|
| 488 |
+
{[1, 2, 5, 10, 20].map((pct) => (
|
| 489 |
+
<button
|
| 490 |
+
key={pct}
|
| 491 |
+
type="button"
|
| 492 |
+
onClick={() => setMarginPercent(pct)}
|
| 493 |
+
className={`px-2 py-1.5 rounded-lg text-[10px] font-mono font-semibold border transition-all ${
|
| 494 |
+
marginPercent === pct
|
| 495 |
+
? 'bg-purple-600/30 border-purple-500 text-purple-200'
|
| 496 |
+
: 'bg-bg-card border-border text-text-muted hover:text-text-primary'
|
| 497 |
+
}`}
|
| 498 |
+
>
|
| 499 |
+
{pct}%
|
| 500 |
+
</button>
|
| 501 |
+
))}
|
| 502 |
+
</div>
|
| 503 |
+
</div>
|
| 504 |
+
|
| 505 |
+
{/* Live Equity Calculation Conversion */}
|
| 506 |
+
<div className="text-[10.5px] font-mono">
|
| 507 |
+
{totalEquity > 0 ? (
|
| 508 |
+
<span className="text-purple-300">
|
| 509 |
+
⚡ <strong>{marginPercent}%</strong> = <strong className="text-emerald-400">${calculatedPercentMargin.toFixed(2)} USD</strong> (dari equity ${totalEquity.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })})
|
| 510 |
+
</span>
|
| 511 |
+
) : (
|
| 512 |
+
<span className="text-amber-400/90 flex items-center gap-1">
|
| 513 |
+
<AlertTriangle size={11} /> Saldo equity $0 / belum terhubung. Silakan gunakan tab "$ USD".
|
| 514 |
+
</span>
|
| 515 |
+
)}
|
| 516 |
+
</div>
|
| 517 |
+
</>
|
| 518 |
+
) : (
|
| 519 |
+
<>
|
| 520 |
+
<div className="flex items-center gap-2">
|
| 521 |
+
<div className="relative flex-1">
|
| 522 |
+
<span className="absolute left-3 top-2 text-text-muted font-mono text-xs">$</span>
|
| 523 |
+
<input
|
| 524 |
+
type="number"
|
| 525 |
+
min="5"
|
| 526 |
+
max="50000"
|
| 527 |
+
step="5"
|
| 528 |
+
value={marginUsd}
|
| 529 |
+
onChange={(e) => setMarginUsd(Math.max(1, parseFloat(e.target.value) || 0))}
|
| 530 |
+
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"
|
| 531 |
+
/>
|
| 532 |
+
</div>
|
| 533 |
+
|
| 534 |
+
{/* Quick USD Pills */}
|
| 535 |
+
<div className="flex items-center gap-1">
|
| 536 |
+
{[25, 50, 100, 200].map((amt) => (
|
| 537 |
+
<button
|
| 538 |
+
key={amt}
|
| 539 |
+
type="button"
|
| 540 |
+
onClick={() => setMarginUsd(amt)}
|
| 541 |
+
className={`px-2 py-1.5 rounded-lg text-[10px] font-mono font-semibold border transition-all ${
|
| 542 |
+
marginUsd === amt
|
| 543 |
+
? 'bg-purple-600/30 border-purple-500 text-purple-200'
|
| 544 |
+
: 'bg-bg-card border-border text-text-muted hover:text-text-primary'
|
| 545 |
+
}`}
|
| 546 |
+
>
|
| 547 |
+
${amt}
|
| 548 |
+
</button>
|
| 549 |
+
))}
|
| 550 |
+
</div>
|
| 551 |
+
</div>
|
| 552 |
+
|
| 553 |
+
{/* USD to % Comparison */}
|
| 554 |
+
<div className="text-[10.5px] font-mono text-text-muted">
|
| 555 |
+
{totalEquity > 0 ? (
|
| 556 |
+
<span>
|
| 557 |
+
ℹ️ ${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 })})
|
| 558 |
+
</span>
|
| 559 |
+
) : (
|
| 560 |
+
<span>ℹ️ Nominal margin tetap ${marginUsd.toFixed(2)} USD</span>
|
| 561 |
+
)}
|
| 562 |
+
</div>
|
| 563 |
+
</>
|
| 564 |
+
)}
|
| 565 |
</div>
|
| 566 |
|
| 567 |
+
{/* Right Column: Leverage & Order Type Selector */}
|
| 568 |
<div className="flex items-center gap-2">
|
| 569 |
<div className="flex-1">
|
| 570 |
<div className="flex items-center justify-between text-[10px] text-text-muted mb-1">
|
tests/test_execution.py
CHANGED
|
@@ -184,3 +184,49 @@ def test_execution_settings_endpoint():
|
|
| 184 |
data = resp.json()
|
| 185 |
assert "configured" in data
|
| 186 |
assert "mode" in data
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 184 |
data = resp.json()
|
| 185 |
assert "configured" in data
|
| 186 |
assert "mode" in data
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
@pytest.mark.anyio
|
| 190 |
+
async def test_execution_order_with_equity_percentage():
|
| 191 |
+
"""Verify backend calculates margin_usd from margin_percent and account equity."""
|
| 192 |
+
with patch("routers.execution._RUNTIME_CREDENTIALS", {"api_key": "dummy_key", "api_secret": "dummy_sec", "mode": "demo"}), \
|
| 193 |
+
patch.object(BybitExecutor, "get_wallet_balance", new_callable=AsyncMock) as mock_bal, \
|
| 194 |
+
patch.object(BybitExecutor, "execute_trade_setup", new_callable=AsyncMock) as mock_exec, \
|
| 195 |
+
patch("routers.execution.async_create_journal_entry", new_callable=AsyncMock) as mock_j:
|
| 196 |
+
|
| 197 |
+
mock_bal.return_value = {
|
| 198 |
+
"coin": "USDT",
|
| 199 |
+
"available_balance": 1500.0,
|
| 200 |
+
"total_equity": 2000.0,
|
| 201 |
+
"mode": "demo",
|
| 202 |
+
}
|
| 203 |
+
mock_exec.return_value = {
|
| 204 |
+
"success": True,
|
| 205 |
+
"symbol": "BTCUSDT",
|
| 206 |
+
"mode": "demo",
|
| 207 |
+
"entry_order_id": "test_order_999",
|
| 208 |
+
"margin_usd": 100.0,
|
| 209 |
+
}
|
| 210 |
+
mock_j.return_value = {"id": "j_123"}
|
| 211 |
+
|
| 212 |
+
# Call endpoint with margin_percent=5.0 (5% of 2000 = 100.0 USD)
|
| 213 |
+
payload = {
|
| 214 |
+
"symbol": "BTCUSDT",
|
| 215 |
+
"side": "Buy",
|
| 216 |
+
"order_type": "Market",
|
| 217 |
+
"margin_usd": 0.0,
|
| 218 |
+
"margin_percent": 5.0,
|
| 219 |
+
"leverage": 3,
|
| 220 |
+
"stop_loss": 58000.0,
|
| 221 |
+
"take_profit_1": 65000.0,
|
| 222 |
+
"mark_price": 60000.0,
|
| 223 |
+
}
|
| 224 |
+
resp = client.post("/api/execution/bybit/order", json=payload)
|
| 225 |
+
assert resp.status_code == 200
|
| 226 |
+
res_data = resp.json()
|
| 227 |
+
assert res_data["success"] is True
|
| 228 |
+
|
| 229 |
+
# Verify executor was called with calculated 100.0 USD
|
| 230 |
+
mock_exec.assert_called_once()
|
| 231 |
+
call_kwargs = mock_exec.call_args.kwargs
|
| 232 |
+
assert call_kwargs["margin_usd"] == 100.0
|