Spaces:
Sleeping
Sleeping
Naufal Arhab commited on
Commit ·
86abcb2
1
Parent(s): 6600dec
feat(execution): implement Bybit V5 1-click execution engine with custom split TP1/TP2 slider and auto-journal tracking
Browse files- backend/engine/execution/bybit_executor.py +378 -0
- backend/main.py +2 -0
- backend/routers/execution.py +204 -0
- frontend/src/api/execution.ts +92 -0
- frontend/src/components/execution/ExecutionModal.tsx +600 -0
- frontend/src/components/signals/AIExecutiveSummaryCard.tsx +25 -1
- tests/test_execution.py +108 -0
backend/engine/execution/bybit_executor.py
ADDED
|
@@ -0,0 +1,378 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Bybit V5 Execution Engine — Institutional-Grade Order Placement
|
| 3 |
+
Handles HMAC-SHA256 authentication, instrument step-size rounding,
|
| 4 |
+
dynamic leverage configuration, and custom split TP1/TP2 bracket orders.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import time
|
| 8 |
+
import json
|
| 9 |
+
import hmac
|
| 10 |
+
import hashlib
|
| 11 |
+
import logging
|
| 12 |
+
import math
|
| 13 |
+
from typing import Any
|
| 14 |
+
from urllib.parse import urlencode
|
| 15 |
+
|
| 16 |
+
import httpx
|
| 17 |
+
from engine.doh_resolver import enable_doh_bypass
|
| 18 |
+
|
| 19 |
+
enable_doh_bypass()
|
| 20 |
+
logger = logging.getLogger(__name__)
|
| 21 |
+
|
| 22 |
+
# Official Bybit V5 URLs
|
| 23 |
+
BYBIT_URLS = {
|
| 24 |
+
"demo": "https://api-demo.bybit.com", # Bybit Official Demo Trading
|
| 25 |
+
"testnet": "https://api-testnet.bybit.com", # Bybit Testnet Platform
|
| 26 |
+
"real": "https://api.bybit.com", # Bybit Production Mainnet
|
| 27 |
+
"real_alt": "https://api.bybit.biz", # Bybit Production Alternative (Bypass)
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class BybitExecutor:
|
| 32 |
+
def __init__(
|
| 33 |
+
self,
|
| 34 |
+
api_key: str,
|
| 35 |
+
api_secret: str,
|
| 36 |
+
mode: str = "demo", # "demo" | "testnet" | "real"
|
| 37 |
+
proxy_url: str | None = None,
|
| 38 |
+
) -> None:
|
| 39 |
+
self.api_key = api_key.strip()
|
| 40 |
+
self.api_secret = api_secret.strip()
|
| 41 |
+
self.mode = mode.lower().strip()
|
| 42 |
+
self.base_url = BYBIT_URLS.get(self.mode, BYBIT_URLS["demo"])
|
| 43 |
+
self.recv_window = "5000"
|
| 44 |
+
|
| 45 |
+
client_kwargs = {
|
| 46 |
+
"base_url": self.base_url,
|
| 47 |
+
"timeout": httpx.Timeout(connect=5.0, read=15.0, write=5.0, pool=10.0),
|
| 48 |
+
"verify": False,
|
| 49 |
+
}
|
| 50 |
+
if proxy_url:
|
| 51 |
+
client_kwargs["proxy"] = proxy_url
|
| 52 |
+
self._client = httpx.AsyncClient(**client_kwargs)
|
| 53 |
+
|
| 54 |
+
async def close(self) -> None:
|
| 55 |
+
await self._client.aclose()
|
| 56 |
+
|
| 57 |
+
def _generate_signature(self, timestamp: str, payload_str: str) -> str:
|
| 58 |
+
"""Bybit V5 HMAC-SHA256 signature generator."""
|
| 59 |
+
param_str = f"{timestamp}{self.api_key}{self.recv_window}{payload_str}"
|
| 60 |
+
return hmac.new(
|
| 61 |
+
self.api_secret.encode("utf-8"),
|
| 62 |
+
param_str.encode("utf-8"),
|
| 63 |
+
hashlib.sha256,
|
| 64 |
+
).hexdigest()
|
| 65 |
+
|
| 66 |
+
async def _request(self, method: str, path: str, params: dict | None = None, json_body: dict | None = None) -> dict[str, Any]:
|
| 67 |
+
"""Send authenticated Bybit V5 request."""
|
| 68 |
+
timestamp = str(int(time.time() * 1000))
|
| 69 |
+
headers = {
|
| 70 |
+
"X-BAPI-API-KEY": self.api_key,
|
| 71 |
+
"X-BAPI-TIMESTAMP": timestamp,
|
| 72 |
+
"X-BAPI-RECV-WINDOW": self.recv_window,
|
| 73 |
+
"Content-Type": "application/json",
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
if method.upper() == "GET":
|
| 77 |
+
query_str = urlencode(sorted((params or {}).items())) if params else ""
|
| 78 |
+
sign = self._generate_signature(timestamp, query_str)
|
| 79 |
+
headers["X-BAPI-SIGN"] = sign
|
| 80 |
+
resp = await self._client.get(path, params=params, headers=headers)
|
| 81 |
+
else:
|
| 82 |
+
body_str = json.dumps(json_body, separators=(",", ":")) if json_body else ""
|
| 83 |
+
sign = self._generate_signature(timestamp, body_str)
|
| 84 |
+
headers["X-BAPI-SIGN"] = sign
|
| 85 |
+
resp = await self._client.post(path, content=body_str, headers=headers)
|
| 86 |
+
|
| 87 |
+
if resp.status_code != 200:
|
| 88 |
+
logger.error("Bybit HTTP %d error on %s: %s", resp.status_code, path, resp.text[:300])
|
| 89 |
+
raise RuntimeError(f"Bybit HTTP {resp.status_code}: {resp.text[:200]}")
|
| 90 |
+
|
| 91 |
+
data = resp.json()
|
| 92 |
+
ret_code = data.get("retCode", -1)
|
| 93 |
+
ret_msg = data.get("retMsg", "Unknown")
|
| 94 |
+
|
| 95 |
+
# retCode 0 is success; 110043 is "Set leverage not modified" which is fine
|
| 96 |
+
if ret_code != 0 and ret_code != 110043:
|
| 97 |
+
logger.warning("Bybit API error code %d: %s", ret_code, ret_msg)
|
| 98 |
+
raise RuntimeError(f"Bybit API Error ({ret_code}): {ret_msg}")
|
| 99 |
+
|
| 100 |
+
return data
|
| 101 |
+
|
| 102 |
+
# -------------------------------------------------------------------------
|
| 103 |
+
# Account & Instrument Information
|
| 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 |
+
coins = (
|
| 110 |
+
data.get("result", {})
|
| 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",
|
| 120 |
+
"available_balance": available_balance,
|
| 121 |
+
"total_equity": total_equity,
|
| 122 |
+
"mode": self.mode,
|
| 123 |
+
"raw": data.get("result", {}),
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
async def get_instrument_info(self, symbol: str) -> dict[str, Any]:
|
| 127 |
+
"""Fetch contract precision, tickSize, and lotSize."""
|
| 128 |
+
sym = symbol.upper().strip()
|
| 129 |
+
data = await self._request("GET", "/v5/market/instruments-info", {
|
| 130 |
+
"category": "linear",
|
| 131 |
+
"symbol": sym,
|
| 132 |
+
})
|
| 133 |
+
items = data.get("result", {}).get("list", [])
|
| 134 |
+
if not items:
|
| 135 |
+
raise ValueError(f"Symbol {sym} tidak ditemukan di Bybit Linear instruments.")
|
| 136 |
+
|
| 137 |
+
info = items[0]
|
| 138 |
+
lot_filter = info.get("lotSizeFilter", {})
|
| 139 |
+
price_filter = info.get("priceFilter", {})
|
| 140 |
+
|
| 141 |
+
return {
|
| 142 |
+
"symbol": sym,
|
| 143 |
+
"base_coin": info.get("baseCoin", ""),
|
| 144 |
+
"quote_coin": info.get("quoteCoin", "USDT"),
|
| 145 |
+
"qty_step": float(lot_filter.get("qtyStep", 0.001)),
|
| 146 |
+
"min_order_qty": float(lot_filter.get("minOrderQty", 0.001)),
|
| 147 |
+
"max_order_qty": float(lot_filter.get("maxOrderQty", 1000000.0)),
|
| 148 |
+
"tick_size": float(price_filter.get("tickSize", 0.0001)),
|
| 149 |
+
"min_price": float(price_filter.get("minPrice", 0.0001)),
|
| 150 |
+
"max_price": float(price_filter.get("maxPrice", 1000000.0)),
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
async def set_leverage(self, symbol: str, leverage: int) -> bool:
|
| 154 |
+
"""Set cross/isolated leverage for linear contract."""
|
| 155 |
+
sym = symbol.upper().strip()
|
| 156 |
+
lev_str = str(max(1, min(leverage, 100)))
|
| 157 |
+
try:
|
| 158 |
+
await self._request("POST", "/v5/position/set-leverage", json_body={
|
| 159 |
+
"category": "linear",
|
| 160 |
+
"symbol": sym,
|
| 161 |
+
"buyLeverage": lev_str,
|
| 162 |
+
"sellLeverage": lev_str,
|
| 163 |
+
})
|
| 164 |
+
return True
|
| 165 |
+
except RuntimeError as exc:
|
| 166 |
+
# 110043 = "Set leverage not modified", already correct
|
| 167 |
+
if "110043" in str(exc) or "not modified" in str(exc).lower():
|
| 168 |
+
return True
|
| 169 |
+
raise
|
| 170 |
+
|
| 171 |
+
# -------------------------------------------------------------------------
|
| 172 |
+
# Execution Helpers: Rounding
|
| 173 |
+
# -------------------------------------------------------------------------
|
| 174 |
+
|
| 175 |
+
@staticmethod
|
| 176 |
+
def _get_precision(num: float) -> int:
|
| 177 |
+
"""Determine decimal precision of a step or tick."""
|
| 178 |
+
s = f"{num:.10f}".rstrip("0")
|
| 179 |
+
if "." in s:
|
| 180 |
+
return len(s.split(".")[1])
|
| 181 |
+
return 0
|
| 182 |
+
|
| 183 |
+
@classmethod
|
| 184 |
+
def _round_step(cls, value: float, step: float) -> float:
|
| 185 |
+
"""Round down value to the nearest step to satisfy exchange filters."""
|
| 186 |
+
if step <= 0:
|
| 187 |
+
return value
|
| 188 |
+
precision = cls._get_precision(step)
|
| 189 |
+
return round(math.floor(value / step) * step, precision)
|
| 190 |
+
|
| 191 |
+
@classmethod
|
| 192 |
+
def _round_tick(cls, value: float, tick: float) -> float:
|
| 193 |
+
"""Round price to the nearest tick."""
|
| 194 |
+
if tick <= 0:
|
| 195 |
+
return value
|
| 196 |
+
precision = cls._get_precision(tick)
|
| 197 |
+
return round(round(value / tick) * tick, precision)
|
| 198 |
+
|
| 199 |
+
# -------------------------------------------------------------------------
|
| 200 |
+
# Core Setup Execution
|
| 201 |
+
# -------------------------------------------------------------------------
|
| 202 |
+
|
| 203 |
+
async def execute_trade_setup(
|
| 204 |
+
self,
|
| 205 |
+
symbol: str,
|
| 206 |
+
side: str, # "Buy" (Long) | "Sell" (Short)
|
| 207 |
+
order_type: str, # "Market" | "Limit"
|
| 208 |
+
margin_usd: float, # Nominal margin to risk, e.g. 50.0 USD
|
| 209 |
+
leverage: int, # Leverage, e.g. 3
|
| 210 |
+
stop_loss: float, # Mandatory Stop Loss price
|
| 211 |
+
take_profit_1: float, # TP1 price
|
| 212 |
+
take_profit_2: float | None = None, # Optional TP2 price
|
| 213 |
+
tp1_percent: float = 50.0, # Custom % of position qty for TP1 (10.0 to 100.0)
|
| 214 |
+
entry_price: float | None = None, # Price if Limit order
|
| 215 |
+
mark_price: float | None = None, # Reference price for qty calculation
|
| 216 |
+
) -> dict[str, Any]:
|
| 217 |
+
"""
|
| 218 |
+
Execute trade setup on Bybit V5 with bracket Stop Loss and custom split TP1/TP2.
|
| 219 |
+
"""
|
| 220 |
+
sym = symbol.upper().strip()
|
| 221 |
+
side_norm = "Buy" if side.upper() in ("BUY", "LONG") else "Sell"
|
| 222 |
+
opposite_side = "Sell" if side_norm == "Buy" else "Buy"
|
| 223 |
+
|
| 224 |
+
# 1. Fetch instrument precision filters
|
| 225 |
+
inst = await self.get_instrument_info(sym)
|
| 226 |
+
qty_step = inst["qty_step"]
|
| 227 |
+
min_qty = inst["min_order_qty"]
|
| 228 |
+
tick_size = inst["tick_size"]
|
| 229 |
+
|
| 230 |
+
# 2. Configure leverage on exchange
|
| 231 |
+
lev = max(1, min(int(leverage), 50))
|
| 232 |
+
await self.set_leverage(sym, lev)
|
| 233 |
+
|
| 234 |
+
# 3. Determine base calculation price
|
| 235 |
+
calc_price = entry_price if (order_type.upper() == "LIMIT" and entry_price and entry_price > 0) else mark_price
|
| 236 |
+
if not calc_price or calc_price <= 0:
|
| 237 |
+
# Fallback: fetch current ticker price
|
| 238 |
+
ticker_data = await self._request("GET", "/v5/market/tickers", {"category": "linear", "symbol": sym})
|
| 239 |
+
calc_price = float(ticker_data.get("result", {}).get("list", [{}])[0].get("lastPrice", 0.0))
|
| 240 |
+
if calc_price <= 0:
|
| 241 |
+
raise ValueError(f"Tidak dapat menentukan harga acuan untuk {sym}.")
|
| 242 |
+
|
| 243 |
+
# 4. Calculate total contract quantity
|
| 244 |
+
notional_usd = margin_usd * lev
|
| 245 |
+
raw_total_qty = notional_usd / calc_price
|
| 246 |
+
total_qty = self._round_step(raw_total_qty, qty_step)
|
| 247 |
+
|
| 248 |
+
if total_qty < min_qty:
|
| 249 |
+
raise ValueError(
|
| 250 |
+
f"Ukuran order terlalu kecil ({total_qty} {inst['base_coin']}). "
|
| 251 |
+
f"Minimal order untuk {sym} adalah {min_qty} {inst['base_coin']} "
|
| 252 |
+
f"(Naikkan margin atau leverage minimal ~${(min_qty * calc_price) / lev:.1f} USD)."
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
# 5. Format prices according to tickSize
|
| 256 |
+
rounded_sl = self._round_tick(stop_loss, tick_size)
|
| 257 |
+
rounded_tp1 = self._round_tick(take_profit_1, tick_size)
|
| 258 |
+
rounded_tp2 = self._round_tick(take_profit_2, tick_size) if (take_profit_2 and take_profit_2 > 0) else None
|
| 259 |
+
|
| 260 |
+
# 6. Build and submit primary entry order
|
| 261 |
+
order_payload: dict[str, Any] = {
|
| 262 |
+
"category": "linear",
|
| 263 |
+
"symbol": sym,
|
| 264 |
+
"side": side_norm,
|
| 265 |
+
"orderType": "Market" if order_type.upper() == "MARKET" else "Limit",
|
| 266 |
+
"qty": str(total_qty),
|
| 267 |
+
"timeInForce": "GTC",
|
| 268 |
+
"positionIdx": 0, # One-way mode
|
| 269 |
+
"stopLoss": str(rounded_sl),
|
| 270 |
+
"slTriggerBy": "MarkPrice",
|
| 271 |
+
}
|
| 272 |
+
|
| 273 |
+
if order_type.upper() == "LIMIT" and entry_price:
|
| 274 |
+
order_payload["price"] = str(self._round_tick(entry_price, tick_size))
|
| 275 |
+
|
| 276 |
+
logger.info("[%s] Sending Bybit Entry order: %s", sym, order_payload)
|
| 277 |
+
entry_resp = await self._request("POST", "/v5/order/create", json_body=order_payload)
|
| 278 |
+
entry_order_id = entry_resp.get("result", {}).get("orderId", "")
|
| 279 |
+
|
| 280 |
+
# 7. Split Take Profit Orders (Reduce-Only Limit Close)
|
| 281 |
+
tp1_pct = max(10.0, min(float(tp1_percent), 100.0))
|
| 282 |
+
tp1_orders_info = []
|
| 283 |
+
|
| 284 |
+
if tp1_pct >= 99.0 or not rounded_tp2:
|
| 285 |
+
# 100% full position to TP1
|
| 286 |
+
tp1_qty = total_qty
|
| 287 |
+
tp1_payload = {
|
| 288 |
+
"category": "linear",
|
| 289 |
+
"symbol": sym,
|
| 290 |
+
"side": opposite_side,
|
| 291 |
+
"orderType": "Limit",
|
| 292 |
+
"qty": str(tp1_qty),
|
| 293 |
+
"price": str(rounded_tp1),
|
| 294 |
+
"timeInForce": "GTC",
|
| 295 |
+
"reduceOnly": True,
|
| 296 |
+
"positionIdx": 0,
|
| 297 |
+
}
|
| 298 |
+
try:
|
| 299 |
+
tp1_resp = await self._request("POST", "/v5/order/create", json_body=tp1_payload)
|
| 300 |
+
tp1_orders_info.append({
|
| 301 |
+
"tp_level": "TP1",
|
| 302 |
+
"percent": 100.0,
|
| 303 |
+
"order_id": tp1_resp.get("result", {}).get("orderId"),
|
| 304 |
+
"price": rounded_tp1,
|
| 305 |
+
"qty": tp1_qty,
|
| 306 |
+
})
|
| 307 |
+
except Exception as exc:
|
| 308 |
+
logger.warning("[%s] Failed to place TP1 limit order: %s", sym, exc)
|
| 309 |
+
else:
|
| 310 |
+
# Split: TP1 gets tp1_pct, TP2 gets remaining
|
| 311 |
+
raw_tp1_qty = total_qty * (tp1_pct / 100.0)
|
| 312 |
+
tp1_qty = self._round_step(raw_tp1_qty, qty_step)
|
| 313 |
+
tp2_qty = self._round_step(total_qty - tp1_qty, qty_step)
|
| 314 |
+
|
| 315 |
+
# Ensure both meet minimum qty
|
| 316 |
+
if tp1_qty >= min_qty:
|
| 317 |
+
tp1_payload = {
|
| 318 |
+
"category": "linear",
|
| 319 |
+
"symbol": sym,
|
| 320 |
+
"side": opposite_side,
|
| 321 |
+
"orderType": "Limit",
|
| 322 |
+
"qty": str(tp1_qty),
|
| 323 |
+
"price": str(rounded_tp1),
|
| 324 |
+
"timeInForce": "GTC",
|
| 325 |
+
"reduceOnly": True,
|
| 326 |
+
"positionIdx": 0,
|
| 327 |
+
}
|
| 328 |
+
try:
|
| 329 |
+
tp1_resp = await self._request("POST", "/v5/order/create", json_body=tp1_payload)
|
| 330 |
+
tp1_orders_info.append({
|
| 331 |
+
"tp_level": "TP1",
|
| 332 |
+
"percent": tp1_pct,
|
| 333 |
+
"order_id": tp1_resp.get("result", {}).get("orderId"),
|
| 334 |
+
"price": rounded_tp1,
|
| 335 |
+
"qty": tp1_qty,
|
| 336 |
+
})
|
| 337 |
+
except Exception as exc:
|
| 338 |
+
logger.warning("[%s] Failed to place TP1 limit order: %s", sym, exc)
|
| 339 |
+
|
| 340 |
+
if tp2_qty >= min_qty and rounded_tp2:
|
| 341 |
+
tp2_payload = {
|
| 342 |
+
"category": "linear",
|
| 343 |
+
"symbol": sym,
|
| 344 |
+
"side": opposite_side,
|
| 345 |
+
"orderType": "Limit",
|
| 346 |
+
"qty": str(tp2_qty),
|
| 347 |
+
"price": str(rounded_tp2),
|
| 348 |
+
"timeInForce": "GTC",
|
| 349 |
+
"reduceOnly": True,
|
| 350 |
+
"positionIdx": 0,
|
| 351 |
+
}
|
| 352 |
+
try:
|
| 353 |
+
tp2_resp = await self._request("POST", "/v5/order/create", json_body=tp2_payload)
|
| 354 |
+
tp1_orders_info.append({
|
| 355 |
+
"tp_level": "TP2",
|
| 356 |
+
"percent": round(100.0 - tp1_pct, 1),
|
| 357 |
+
"order_id": tp2_resp.get("result", {}).get("orderId"),
|
| 358 |
+
"price": rounded_tp2,
|
| 359 |
+
"qty": tp2_qty,
|
| 360 |
+
})
|
| 361 |
+
except Exception as exc:
|
| 362 |
+
logger.warning("[%s] Failed to place TP2 limit order: %s", sym, exc)
|
| 363 |
+
|
| 364 |
+
return {
|
| 365 |
+
"success": True,
|
| 366 |
+
"symbol": sym,
|
| 367 |
+
"side": side_norm,
|
| 368 |
+
"order_type": order_type.upper(),
|
| 369 |
+
"margin_usd": margin_usd,
|
| 370 |
+
"leverage": lev,
|
| 371 |
+
"notional_usd": notional_usd,
|
| 372 |
+
"total_qty": total_qty,
|
| 373 |
+
"entry_order_id": entry_order_id,
|
| 374 |
+
"stop_loss": rounded_sl,
|
| 375 |
+
"tp_orders": tp1_orders_info,
|
| 376 |
+
"mode": self.mode,
|
| 377 |
+
"timestamp": time.time(),
|
| 378 |
+
}
|
backend/main.py
CHANGED
|
@@ -51,6 +51,7 @@ from routers import ws as ws_router
|
|
| 51 |
from routers import market as market_router
|
| 52 |
from routers import ai as ai_router
|
| 53 |
from routers import journal as journal_router
|
|
|
|
| 54 |
from routers.ws import broadcast
|
| 55 |
|
| 56 |
logging.basicConfig(
|
|
@@ -474,6 +475,7 @@ app.include_router(signals_router.router)
|
|
| 474 |
app.include_router(market_router.router)
|
| 475 |
app.include_router(ai_router.router)
|
| 476 |
app.include_router(journal_router.router)
|
|
|
|
| 477 |
app.include_router(ws_router.router)
|
| 478 |
|
| 479 |
|
|
|
|
| 51 |
from routers import market as market_router
|
| 52 |
from routers import ai as ai_router
|
| 53 |
from routers import journal as journal_router
|
| 54 |
+
from routers import execution as execution_router
|
| 55 |
from routers.ws import broadcast
|
| 56 |
|
| 57 |
logging.basicConfig(
|
|
|
|
| 475 |
app.include_router(market_router.router)
|
| 476 |
app.include_router(ai_router.router)
|
| 477 |
app.include_router(journal_router.router)
|
| 478 |
+
app.include_router(execution_router.router)
|
| 479 |
app.include_router(ws_router.router)
|
| 480 |
|
| 481 |
|
backend/routers/execution.py
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
/api/execution endpoints — Bybit V5 Live/Demo Order Execution Router
|
| 3 |
+
Connects Damian trade setups directly to Bybit Linear Futures with bracket SL and split TP.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
import re
|
| 8 |
+
import logging
|
| 9 |
+
from typing import Any
|
| 10 |
+
|
| 11 |
+
from fastapi import APIRouter, HTTPException, Request
|
| 12 |
+
from pydantic import BaseModel, Field
|
| 13 |
+
|
| 14 |
+
from config import BYBIT_API_KEY, BYBIT_SECRET
|
| 15 |
+
from engine.execution.bybit_executor import BybitExecutor
|
| 16 |
+
from database.db import async_create_journal_entry
|
| 17 |
+
|
| 18 |
+
logger = logging.getLogger(__name__)
|
| 19 |
+
|
| 20 |
+
router = APIRouter(prefix="/api/execution", tags=["execution"])
|
| 21 |
+
|
| 22 |
+
# Runtime credential cache in memory (can be overwritten via settings modal)
|
| 23 |
+
_RUNTIME_CREDENTIALS: dict[str, str] = {
|
| 24 |
+
"api_key": BYBIT_API_KEY,
|
| 25 |
+
"api_secret": BYBIT_SECRET,
|
| 26 |
+
"mode": os.getenv("BYBIT_MODE", "demo"), # "demo" | "testnet" | "real"
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _get_active_executor(
|
| 31 |
+
req_key: str | None = None,
|
| 32 |
+
req_secret: str | None = None,
|
| 33 |
+
req_mode: str | None = None,
|
| 34 |
+
) -> BybitExecutor:
|
| 35 |
+
"""Instantiate BybitExecutor using provided or cached credentials."""
|
| 36 |
+
api_key = (req_key or _RUNTIME_CREDENTIALS.get("api_key") or os.getenv("BYBIT_API_KEY", "")).strip()
|
| 37 |
+
api_secret = (req_secret or _RUNTIME_CREDENTIALS.get("api_secret") or os.getenv("BYBIT_SECRET", "")).strip()
|
| 38 |
+
mode = (req_mode or _RUNTIME_CREDENTIALS.get("mode") or "demo").lower().strip()
|
| 39 |
+
|
| 40 |
+
if not api_key or not api_secret:
|
| 41 |
+
raise HTTPException(
|
| 42 |
+
status_code=400,
|
| 43 |
+
detail="API Key atau API Secret Bybit belum dikonfigurasi. Silakan masukkan kredensial Bybit Anda.",
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
return BybitExecutor(api_key=api_key, api_secret=api_secret, mode=mode)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class BybitSettingsRequest(BaseModel):
|
| 50 |
+
api_key: str | None = None
|
| 51 |
+
api_secret: str | None = None
|
| 52 |
+
mode: str = "demo" # "demo" | "testnet" | "real"
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
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(..., gt=0, description="Nominal modal margin dalam USD")
|
| 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")
|
| 63 |
+
take_profit_2: float | None = None
|
| 64 |
+
tp1_percent: float = Field(default=50.0, ge=10.0, le=100.0, description="Persentase porsi TP1")
|
| 65 |
+
entry_price: float | None = None
|
| 66 |
+
mark_price: float | None = None
|
| 67 |
+
api_key: str | None = None
|
| 68 |
+
api_secret: str | None = None
|
| 69 |
+
mode: str | None = None
|
| 70 |
+
log_to_journal: bool = True
|
| 71 |
+
summary_tldr: str | None = None
|
| 72 |
+
model_used: str | None = None
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
@router.get("/bybit/settings")
|
| 76 |
+
async def get_bybit_settings():
|
| 77 |
+
"""Check Bybit API connection status and active environment mode."""
|
| 78 |
+
key = _RUNTIME_CREDENTIALS.get("api_key") or ""
|
| 79 |
+
masked_key = f"{key[:4]}***{key[-4:]}" if len(key) >= 8 else ("Sudah terpasang" if key else "")
|
| 80 |
+
return {
|
| 81 |
+
"configured": bool(key and _RUNTIME_CREDENTIALS.get("api_secret")),
|
| 82 |
+
"masked_key": masked_key,
|
| 83 |
+
"mode": _RUNTIME_CREDENTIALS.get("mode", "demo"),
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
@router.post("/bybit/settings")
|
| 88 |
+
async def save_bybit_settings(body: BybitSettingsRequest):
|
| 89 |
+
"""Save or update Bybit API credentials and environment mode."""
|
| 90 |
+
if body.api_key:
|
| 91 |
+
_RUNTIME_CREDENTIALS["api_key"] = body.api_key.strip()
|
| 92 |
+
if body.api_secret:
|
| 93 |
+
_RUNTIME_CREDENTIALS["api_secret"] = body.api_secret.strip()
|
| 94 |
+
if body.mode:
|
| 95 |
+
_RUNTIME_CREDENTIALS["mode"] = body.mode.lower().strip()
|
| 96 |
+
|
| 97 |
+
# Test credentials by checking wallet balance
|
| 98 |
+
executor = _get_active_executor()
|
| 99 |
+
try:
|
| 100 |
+
balance = await executor.get_wallet_balance()
|
| 101 |
+
return {
|
| 102 |
+
"success": True,
|
| 103 |
+
"message": f"Koneksi ke Bybit ({executor.mode.upper()}) berhasil terhubung!",
|
| 104 |
+
"balance": balance,
|
| 105 |
+
"mode": executor.mode,
|
| 106 |
+
}
|
| 107 |
+
except Exception as exc:
|
| 108 |
+
logger.warning("Bybit credential test failed: %s", exc)
|
| 109 |
+
raise HTTPException(
|
| 110 |
+
status_code=400,
|
| 111 |
+
detail=f"Kredensial Bybit gagal divalidasi: {str(exc)}",
|
| 112 |
+
)
|
| 113 |
+
finally:
|
| 114 |
+
await executor.close()
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
@router.get("/bybit/balance")
|
| 118 |
+
async def get_bybit_balance(mode: str | None = None):
|
| 119 |
+
"""Fetch live available USDT balance from Bybit Unified account."""
|
| 120 |
+
executor = _get_active_executor(req_mode=mode)
|
| 121 |
+
try:
|
| 122 |
+
balance = await executor.get_wallet_balance()
|
| 123 |
+
return balance
|
| 124 |
+
except Exception as exc:
|
| 125 |
+
logger.error("Failed to fetch Bybit balance: %s", exc)
|
| 126 |
+
raise HTTPException(status_code=500, detail=f"Gagal mengambil saldo Bybit: {str(exc)}")
|
| 127 |
+
finally:
|
| 128 |
+
await executor.close()
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
@router.post("/bybit/order")
|
| 132 |
+
async def execute_bybit_order(body: ExecuteBybitOrderRequest):
|
| 133 |
+
"""
|
| 134 |
+
Execute institutional trade setup directly on Bybit V5.
|
| 135 |
+
Sets leverage, executes entry, attaches position Stop Loss, and places custom split TP1/TP2 limit orders.
|
| 136 |
+
"""
|
| 137 |
+
executor = _get_active_executor(
|
| 138 |
+
req_key=body.api_key,
|
| 139 |
+
req_secret=body.api_secret,
|
| 140 |
+
req_mode=body.mode,
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
try:
|
| 144 |
+
exec_result = await executor.execute_trade_setup(
|
| 145 |
+
symbol=body.symbol,
|
| 146 |
+
side=body.side,
|
| 147 |
+
order_type=body.order_type,
|
| 148 |
+
margin_usd=body.margin_usd,
|
| 149 |
+
leverage=body.leverage,
|
| 150 |
+
stop_loss=body.stop_loss,
|
| 151 |
+
take_profit_1=body.take_profit_1,
|
| 152 |
+
take_profit_2=body.take_profit_2,
|
| 153 |
+
tp1_percent=body.tp1_percent,
|
| 154 |
+
entry_price=body.entry_price,
|
| 155 |
+
mark_price=body.mark_price,
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
# Automatically log to Trade Journal if requested
|
| 159 |
+
journal_entry = None
|
| 160 |
+
if body.log_to_journal:
|
| 161 |
+
try:
|
| 162 |
+
bias_label = "STRONG LONG" if body.side.upper() in ("BUY", "LONG") else "STRONG SHORT"
|
| 163 |
+
tp_str = f"TP1: ${body.take_profit_1:,.4f} ({body.tp1_percent:.0f}%)"
|
| 164 |
+
if body.take_profit_2:
|
| 165 |
+
tp_str += f" | TP2: ${body.take_profit_2:,.4f} ({100 - body.tp1_percent:.0f}%)"
|
| 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": f"Margin: ${body.margin_usd:.1f} | Lev: {body.leverage}x",
|
| 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()})",
|
| 179 |
+
"model_used": body.model_used or "bybit-auto-execution",
|
| 180 |
+
"snapshot_data": {
|
| 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",
|
| 187 |
+
})
|
| 188 |
+
except Exception as j_err:
|
| 189 |
+
logger.warning("Auto journal log after execution failed: %s", j_err)
|
| 190 |
+
|
| 191 |
+
return {
|
| 192 |
+
"success": True,
|
| 193 |
+
"message": f"Order {body.symbol} berhasil dikirim ke Bybit ({exec_result.get('mode', 'DEMO').upper()})!",
|
| 194 |
+
"execution": exec_result,
|
| 195 |
+
"journal_entry": journal_entry,
|
| 196 |
+
}
|
| 197 |
+
|
| 198 |
+
except ValueError as val_err:
|
| 199 |
+
raise HTTPException(status_code=400, detail=str(val_err))
|
| 200 |
+
except Exception as exc:
|
| 201 |
+
logger.error("[%s] Execution error: %s", body.symbol, exc)
|
| 202 |
+
raise HTTPException(status_code=500, detail=f"Gagal mengeksekusi order Bybit: {str(exc)}")
|
| 203 |
+
finally:
|
| 204 |
+
await executor.close()
|
frontend/src/api/execution.ts
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { apiClient } from './client';
|
| 2 |
+
|
| 3 |
+
export interface BybitSettings {
|
| 4 |
+
configured: boolean;
|
| 5 |
+
masked_key: string;
|
| 6 |
+
mode: 'demo' | 'testnet' | 'real';
|
| 7 |
+
}
|
| 8 |
+
|
| 9 |
+
export interface BybitWalletBalance {
|
| 10 |
+
coin: string;
|
| 11 |
+
available_balance: number;
|
| 12 |
+
total_equity: number;
|
| 13 |
+
mode: string;
|
| 14 |
+
raw?: any;
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
export interface ExecuteOrderPayload {
|
| 18 |
+
symbol: string;
|
| 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;
|
| 25 |
+
take_profit_2?: number | null;
|
| 26 |
+
tp1_percent: number;
|
| 27 |
+
entry_price?: number | null;
|
| 28 |
+
mark_price?: number | null;
|
| 29 |
+
api_key?: string;
|
| 30 |
+
api_secret?: string;
|
| 31 |
+
mode?: string;
|
| 32 |
+
log_to_journal?: boolean;
|
| 33 |
+
summary_tldr?: string;
|
| 34 |
+
model_used?: string;
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
export interface ExecutionResult {
|
| 38 |
+
success: boolean;
|
| 39 |
+
message: string;
|
| 40 |
+
execution: {
|
| 41 |
+
symbol: string;
|
| 42 |
+
side: string;
|
| 43 |
+
order_type: string;
|
| 44 |
+
margin_usd: number;
|
| 45 |
+
leverage: number;
|
| 46 |
+
notional_usd: number;
|
| 47 |
+
total_qty: number;
|
| 48 |
+
entry_order_id: string;
|
| 49 |
+
stop_loss: number;
|
| 50 |
+
tp_orders: Array<{
|
| 51 |
+
tp_level: string;
|
| 52 |
+
percent: number;
|
| 53 |
+
order_id?: string;
|
| 54 |
+
price: number;
|
| 55 |
+
qty: number;
|
| 56 |
+
}>;
|
| 57 |
+
mode: string;
|
| 58 |
+
timestamp: number;
|
| 59 |
+
};
|
| 60 |
+
journal_entry?: any;
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
export const executionApi = {
|
| 64 |
+
getSettings: async (): Promise<BybitSettings> => {
|
| 65 |
+
const { data } = await apiClient.get<BybitSettings>('/api/execution/bybit/settings');
|
| 66 |
+
return data;
|
| 67 |
+
},
|
| 68 |
+
|
| 69 |
+
saveSettings: async (payload: {
|
| 70 |
+
api_key?: string;
|
| 71 |
+
api_secret?: string;
|
| 72 |
+
mode?: string;
|
| 73 |
+
}): Promise<{ success: boolean; message: string; balance?: BybitWalletBalance }> => {
|
| 74 |
+
const { data } = await apiClient.post<{ success: boolean; message: string; balance?: BybitWalletBalance }>(
|
| 75 |
+
'/api/execution/bybit/settings',
|
| 76 |
+
payload
|
| 77 |
+
);
|
| 78 |
+
return data;
|
| 79 |
+
},
|
| 80 |
+
|
| 81 |
+
getBalance: async (mode?: string): Promise<BybitWalletBalance> => {
|
| 82 |
+
const { data } = await apiClient.get<BybitWalletBalance>('/api/execution/bybit/balance', {
|
| 83 |
+
params: mode ? { mode } : {},
|
| 84 |
+
});
|
| 85 |
+
return data;
|
| 86 |
+
},
|
| 87 |
+
|
| 88 |
+
executeOrder: async (payload: ExecuteOrderPayload): Promise<ExecutionResult> => {
|
| 89 |
+
const { data } = await apiClient.post<ExecutionResult>('/api/execution/bybit/order', payload);
|
| 90 |
+
return data;
|
| 91 |
+
},
|
| 92 |
+
};
|
frontend/src/components/execution/ExecutionModal.tsx
ADDED
|
@@ -0,0 +1,600 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { useState, useEffect } from 'react';
|
| 2 |
+
import {
|
| 3 |
+
Zap,
|
| 4 |
+
TrendingUp,
|
| 5 |
+
TrendingDown,
|
| 6 |
+
ShieldAlert,
|
| 7 |
+
Target,
|
| 8 |
+
Key,
|
| 9 |
+
Wallet,
|
| 10 |
+
Settings2,
|
| 11 |
+
AlertTriangle,
|
| 12 |
+
CheckCircle2,
|
| 13 |
+
Lock,
|
| 14 |
+
} from 'lucide-react';
|
| 15 |
+
import { Modal } from '../ui/Modal';
|
| 16 |
+
import { Button } from '../ui/Button';
|
| 17 |
+
import { useToast } from '../ui/Toast';
|
| 18 |
+
import { executionApi, BybitSettings, BybitWalletBalance } from '../../api/execution';
|
| 19 |
+
import type { AIExecutiveSummary } from '../signals/AIExecutiveSummaryCard';
|
| 20 |
+
|
| 21 |
+
interface ExecutionModalProps {
|
| 22 |
+
isOpen: boolean;
|
| 23 |
+
onClose: () => void;
|
| 24 |
+
symbol: string;
|
| 25 |
+
summary: AIExecutiveSummary;
|
| 26 |
+
markPrice?: number;
|
| 27 |
+
onExecutionSuccess?: (result: any) => void;
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
function parsePrice(str?: string): number | null {
|
| 31 |
+
if (!str) return null;
|
| 32 |
+
const match = str.match(/([0-9,.]+)/);
|
| 33 |
+
if (!match) return null;
|
| 34 |
+
const cleaned = match[1].replace(/,/g, '');
|
| 35 |
+
const val = parseFloat(cleaned);
|
| 36 |
+
return isNaN(val) ? null : val;
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
function parseLeverage(str?: string): number {
|
| 40 |
+
if (!str) return 3;
|
| 41 |
+
const match = str.match(/([0-9]+)\s*x/i) || str.match(/([0-9]+)/);
|
| 42 |
+
if (!match) return 3;
|
| 43 |
+
const val = parseInt(match[1], 10);
|
| 44 |
+
return isNaN(val) ? 3 : Math.min(Math.max(val, 1), 50);
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
export function ExecutionModal({
|
| 48 |
+
isOpen,
|
| 49 |
+
onClose,
|
| 50 |
+
symbol,
|
| 51 |
+
summary,
|
| 52 |
+
markPrice,
|
| 53 |
+
onExecutionSuccess,
|
| 54 |
+
}: ExecutionModalProps) {
|
| 55 |
+
const { toast } = useToast();
|
| 56 |
+
|
| 57 |
+
const isShort = summary.bias.toUpperCase().includes('SHORT') || summary.bias.toUpperCase().includes('SELL');
|
| 58 |
+
const defaultSide: 'Buy' | 'Sell' = isShort ? 'Sell' : 'Buy';
|
| 59 |
+
|
| 60 |
+
const rawEntry = parsePrice(summary.entryZone) || markPrice || 0;
|
| 61 |
+
const rawSL = parsePrice(summary.stopLoss) || (isShort ? rawEntry * 1.03 : rawEntry * 0.97);
|
| 62 |
+
const rawTP1 = parsePrice(summary.takeProfit1) || (isShort ? rawEntry * 0.95 : rawEntry * 1.05);
|
| 63 |
+
const rawTP2 = parsePrice(summary.takeProfit2);
|
| 64 |
+
const defaultLev = parseLeverage(summary.leverage);
|
| 65 |
+
|
| 66 |
+
// Form State
|
| 67 |
+
const [orderType, setOrderType] = useState<'Market' | 'Limit'>('Limit');
|
| 68 |
+
const [marginUsd, setMarginUsd] = useState<number>(50);
|
| 69 |
+
const [leverage, setLeverage] = useState<number>(defaultLev);
|
| 70 |
+
const [entryPrice, setEntryPrice] = useState<number>(rawEntry);
|
| 71 |
+
const [stopLoss, setStopLoss] = useState<number>(rawSL);
|
| 72 |
+
const [takeProfit1, setTakeProfit1] = useState<number>(rawTP1);
|
| 73 |
+
const [takeProfit2, setTakeProfit2] = useState<number | null>(rawTP2);
|
| 74 |
+
const [tp1Percent, setTp1Percent] = useState<number>(50);
|
| 75 |
+
|
| 76 |
+
// Settings & Connection State
|
| 77 |
+
const [settings, setSettings] = useState<BybitSettings | null>(null);
|
| 78 |
+
const [balance, setBalance] = useState<BybitWalletBalance | null>(null);
|
| 79 |
+
const [isConfiguringKey, setIsConfiguringKey] = useState<boolean>(false);
|
| 80 |
+
const [apiKeyInput, setApiKeyInput] = useState<string>('');
|
| 81 |
+
const [apiSecretInput, setApiSecretInput] = useState<string>('');
|
| 82 |
+
const [modeInput, setModeInput] = useState<'demo' | 'testnet' | 'real'>('demo');
|
| 83 |
+
const [isSavingKey, setIsSavingKey] = useState<boolean>(false);
|
| 84 |
+
const [isSubmitting, setIsSubmitting] = useState<boolean>(false);
|
| 85 |
+
|
| 86 |
+
// Load Bybit Settings on open
|
| 87 |
+
useEffect(() => {
|
| 88 |
+
if (isOpen) {
|
| 89 |
+
loadSettings();
|
| 90 |
+
}
|
| 91 |
+
}, [isOpen]);
|
| 92 |
+
|
| 93 |
+
const loadSettings = async () => {
|
| 94 |
+
try {
|
| 95 |
+
const s = await executionApi.getSettings();
|
| 96 |
+
setSettings(s);
|
| 97 |
+
setModeInput(s.mode || 'demo');
|
| 98 |
+
if (s.configured) {
|
| 99 |
+
setIsConfiguringKey(false);
|
| 100 |
+
fetchBalance(s.mode);
|
| 101 |
+
} else {
|
| 102 |
+
setIsConfiguringKey(true);
|
| 103 |
+
}
|
| 104 |
+
} catch {
|
| 105 |
+
setIsConfiguringKey(true);
|
| 106 |
+
}
|
| 107 |
+
};
|
| 108 |
+
|
| 109 |
+
const fetchBalance = async (mode?: string) => {
|
| 110 |
+
try {
|
| 111 |
+
const b = await executionApi.getBalance(mode);
|
| 112 |
+
setBalance(b);
|
| 113 |
+
} catch {
|
| 114 |
+
// Ignored if keys aren't active yet
|
| 115 |
+
}
|
| 116 |
+
};
|
| 117 |
+
|
| 118 |
+
const handleSaveCredentials = async () => {
|
| 119 |
+
if (!apiKeyInput.trim() || !apiSecretInput.trim()) {
|
| 120 |
+
toast('Masukkan API Key dan API Secret Bybit Anda.', 'error');
|
| 121 |
+
return;
|
| 122 |
+
}
|
| 123 |
+
setIsSavingKey(true);
|
| 124 |
+
try {
|
| 125 |
+
const res = await executionApi.saveSettings({
|
| 126 |
+
api_key: apiKeyInput.trim(),
|
| 127 |
+
api_secret: apiSecretInput.trim(),
|
| 128 |
+
mode: modeInput,
|
| 129 |
+
});
|
| 130 |
+
toast(res.message, 'success');
|
| 131 |
+
setSettings({
|
| 132 |
+
configured: true,
|
| 133 |
+
masked_key: `${apiKeyInput.slice(0, 4)}***`,
|
| 134 |
+
mode: modeInput,
|
| 135 |
+
});
|
| 136 |
+
if (res.balance) {
|
| 137 |
+
setBalance(res.balance);
|
| 138 |
+
}
|
| 139 |
+
setIsConfiguringKey(false);
|
| 140 |
+
} catch (err: any) {
|
| 141 |
+
toast(err.message || 'Kredensial Bybit gagal divalidasi.', 'error');
|
| 142 |
+
} finally {
|
| 143 |
+
setIsSavingKey(false);
|
| 144 |
+
}
|
| 145 |
+
};
|
| 146 |
+
|
| 147 |
+
// Calculations for preview
|
| 148 |
+
const refPrice = orderType === 'Limit' && entryPrice > 0 ? entryPrice : (markPrice || entryPrice || 1.0);
|
| 149 |
+
const notionalUsd = marginUsd * leverage;
|
| 150 |
+
|
| 151 |
+
const estLossUsd = refPrice > 0
|
| 152 |
+
? (isShort ? (stopLoss - refPrice) / refPrice : (refPrice - stopLoss) / refPrice) * notionalUsd
|
| 153 |
+
: 0;
|
| 154 |
+
|
| 155 |
+
const tp1Ratio = tp1Percent / 100;
|
| 156 |
+
const tp2Ratio = (100 - tp1Percent) / 100;
|
| 157 |
+
|
| 158 |
+
const estTp1Gain = refPrice > 0 && takeProfit1 > 0
|
| 159 |
+
? (isShort ? (refPrice - takeProfit1) / refPrice : (takeProfit1 - refPrice) / refPrice) * (notionalUsd * tp1Ratio)
|
| 160 |
+
: 0;
|
| 161 |
+
|
| 162 |
+
const estTp2Gain = refPrice > 0 && takeProfit2 && takeProfit2 > 0 && tp1Percent < 100
|
| 163 |
+
? (isShort ? (refPrice - takeProfit2) / refPrice : (takeProfit2 - refPrice) / refPrice) * (notionalUsd * tp2Ratio)
|
| 164 |
+
: 0;
|
| 165 |
+
|
| 166 |
+
const totalEstGain = estTp1Gain + estTp2Gain;
|
| 167 |
+
const estimatedRR = estLossUsd > 0 ? (totalEstGain / estLossUsd).toFixed(2) : 'N/A';
|
| 168 |
+
|
| 169 |
+
const handleExecute = async () => {
|
| 170 |
+
if (!settings?.configured) {
|
| 171 |
+
setIsConfiguringKey(true);
|
| 172 |
+
toast('Harap masukkan API Key Bybit sebelum eksekusi.', 'info');
|
| 173 |
+
return;
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
if (marginUsd <= 0) {
|
| 177 |
+
toast('Masukkan margin yang valid (> $0).', 'error');
|
| 178 |
+
return;
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
if (stopLoss <= 0 || takeProfit1 <= 0) {
|
| 182 |
+
toast('Stop Loss dan Target TP1 wajib diisi.', 'error');
|
| 183 |
+
return;
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
setIsSubmitting(true);
|
| 187 |
+
try {
|
| 188 |
+
const res = await executionApi.executeOrder({
|
| 189 |
+
symbol,
|
| 190 |
+
side: defaultSide,
|
| 191 |
+
order_type: orderType,
|
| 192 |
+
margin_usd: marginUsd,
|
| 193 |
+
leverage,
|
| 194 |
+
stop_loss: stopLoss,
|
| 195 |
+
take_profit_1: takeProfit1,
|
| 196 |
+
take_profit_2: tp1Percent < 100 ? takeProfit2 : null,
|
| 197 |
+
tp1_percent: tp1Percent,
|
| 198 |
+
entry_price: orderType === 'Limit' ? entryPrice : undefined,
|
| 199 |
+
mark_price: markPrice,
|
| 200 |
+
summary_tldr: summary.verdictSummary,
|
| 201 |
+
});
|
| 202 |
+
|
| 203 |
+
toast(`🚀 ${res.message}`, 'success');
|
| 204 |
+
if (onExecutionSuccess) {
|
| 205 |
+
onExecutionSuccess(res);
|
| 206 |
+
}
|
| 207 |
+
onClose();
|
| 208 |
+
} catch (err: any) {
|
| 209 |
+
toast(err.message || 'Eksekusi order gagal.', 'error');
|
| 210 |
+
} finally {
|
| 211 |
+
setIsSubmitting(false);
|
| 212 |
+
}
|
| 213 |
+
};
|
| 214 |
+
|
| 215 |
+
return (
|
| 216 |
+
<Modal isOpen={isOpen} onClose={onClose} title={`Eksekusi Order — ${symbol}`} size="lg">
|
| 217 |
+
<div className="space-y-4 text-xs">
|
| 218 |
+
{/* ── 1. Top Header: Bias Badge & Bybit Connection Status ─────────── */}
|
| 219 |
+
<div className="flex flex-wrap items-center justify-between gap-2 p-3 rounded-xl bg-bg-elevated/60 border border-border">
|
| 220 |
+
<div className="flex items-center gap-2">
|
| 221 |
+
<div
|
| 222 |
+
className={`px-2.5 py-1 rounded-lg text-xs font-bold font-mono flex items-center gap-1.5 border ${
|
| 223 |
+
isShort
|
| 224 |
+
? 'bg-rose-500/20 text-rose-300 border-rose-500/40'
|
| 225 |
+
: 'bg-emerald-500/20 text-emerald-300 border-emerald-500/40'
|
| 226 |
+
}`}
|
| 227 |
+
>
|
| 228 |
+
{isShort ? <TrendingDown size={14} /> : <TrendingUp size={14} />}
|
| 229 |
+
<span>{defaultSide.toUpperCase()} ({summary.bias})</span>
|
| 230 |
+
</div>
|
| 231 |
+
<span className="text-[11px] text-text-muted font-mono hidden sm:inline">
|
| 232 |
+
Mark: ${markPrice?.toLocaleString(undefined, { minimumFractionDigits: 4 }) || 'N/A'}
|
| 233 |
+
</span>
|
| 234 |
+
</div>
|
| 235 |
+
|
| 236 |
+
{/* Bybit Account Status Pill */}
|
| 237 |
+
<div className="flex items-center gap-2">
|
| 238 |
+
{settings?.configured ? (
|
| 239 |
+
<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">
|
| 240 |
+
<CheckCircle2 size={12} className="text-emerald-400" />
|
| 241 |
+
<span className="font-semibold uppercase">{settings.mode} Bybit</span>
|
| 242 |
+
{balance && (
|
| 243 |
+
<span className="text-emerald-400 font-bold ml-1">
|
| 244 |
+
${balance.available_balance.toLocaleString(undefined, { maximumFractionDigits: 1 })} USDT
|
| 245 |
+
</span>
|
| 246 |
+
)}
|
| 247 |
+
</div>
|
| 248 |
+
) : (
|
| 249 |
+
<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">
|
| 250 |
+
<AlertTriangle size={12} className="text-amber-400" />
|
| 251 |
+
<span>API Belum Terpasang</span>
|
| 252 |
+
</div>
|
| 253 |
+
)}
|
| 254 |
+
|
| 255 |
+
<button
|
| 256 |
+
type="button"
|
| 257 |
+
onClick={() => setIsConfiguringKey(!isConfiguringKey)}
|
| 258 |
+
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"
|
| 259 |
+
title="Konfigurasi API Key Bybit"
|
| 260 |
+
>
|
| 261 |
+
<Settings2 size={13} />
|
| 262 |
+
</button>
|
| 263 |
+
</div>
|
| 264 |
+
</div>
|
| 265 |
+
|
| 266 |
+
{/* ── 2. Collapsible API Key Drawer (if configuring) ──────────────── */}
|
| 267 |
+
{isConfiguringKey && (
|
| 268 |
+
<div className="p-3.5 rounded-xl bg-purple-950/30 border border-purple-500/40 space-y-3 animate-fade-in">
|
| 269 |
+
<div className="flex items-center justify-between">
|
| 270 |
+
<span className="text-xs font-bold text-purple-200 flex items-center gap-1.5">
|
| 271 |
+
<Key size={14} className="text-purple-400" />
|
| 272 |
+
Kredensial API Bybit (Demo / Testnet)
|
| 273 |
+
</span>
|
| 274 |
+
<span className="text-[10px] text-purple-300/80 flex items-center gap-1">
|
| 275 |
+
<Lock size={10} /> Read & Futures Only (Tanpa Withdraw)
|
| 276 |
+
</span>
|
| 277 |
+
</div>
|
| 278 |
+
|
| 279 |
+
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2.5">
|
| 280 |
+
<div>
|
| 281 |
+
<label className="text-[10px] uppercase font-bold text-text-muted block mb-1">
|
| 282 |
+
Bybit API Key
|
| 283 |
+
</label>
|
| 284 |
+
<input
|
| 285 |
+
type="text"
|
| 286 |
+
value={apiKeyInput}
|
| 287 |
+
onChange={(e) => setApiKeyInput(e.target.value)}
|
| 288 |
+
placeholder="Masukkan API Key Bybit"
|
| 289 |
+
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"
|
| 290 |
+
/>
|
| 291 |
+
</div>
|
| 292 |
+
|
| 293 |
+
<div>
|
| 294 |
+
<label className="text-[10px] uppercase font-bold text-text-muted block mb-1">
|
| 295 |
+
Bybit API Secret
|
| 296 |
+
</label>
|
| 297 |
+
<input
|
| 298 |
+
type="password"
|
| 299 |
+
value={apiSecretInput}
|
| 300 |
+
onChange={(e) => setApiSecretInput(e.target.value)}
|
| 301 |
+
placeholder="Masukkan API Secret Bybit"
|
| 302 |
+
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"
|
| 303 |
+
/>
|
| 304 |
+
</div>
|
| 305 |
+
</div>
|
| 306 |
+
|
| 307 |
+
<div className="flex flex-wrap items-center justify-between gap-2 pt-1">
|
| 308 |
+
<div className="flex items-center gap-2">
|
| 309 |
+
<span className="text-[10px] font-bold text-text-muted uppercase">Lingkungan:</span>
|
| 310 |
+
<div className="flex items-center gap-1">
|
| 311 |
+
{[
|
| 312 |
+
{ id: 'demo', label: 'Bybit Demo (api-demo)' },
|
| 313 |
+
{ id: 'testnet', label: 'Testnet' },
|
| 314 |
+
{ id: 'real', label: 'Live Real' },
|
| 315 |
+
].map((m) => (
|
| 316 |
+
<button
|
| 317 |
+
key={m.id}
|
| 318 |
+
type="button"
|
| 319 |
+
onClick={() => setModeInput(m.id as any)}
|
| 320 |
+
className={`px-2 py-1 rounded text-[10px] font-mono font-semibold transition-all ${
|
| 321 |
+
modeInput === m.id
|
| 322 |
+
? 'bg-purple-600 text-white shadow-sm'
|
| 323 |
+
: 'bg-bg-card text-text-secondary hover:text-text-primary border border-border'
|
| 324 |
+
}`}
|
| 325 |
+
>
|
| 326 |
+
{m.label}
|
| 327 |
+
</button>
|
| 328 |
+
))}
|
| 329 |
+
</div>
|
| 330 |
+
</div>
|
| 331 |
+
|
| 332 |
+
<div className="flex items-center gap-1.5">
|
| 333 |
+
{settings?.configured && (
|
| 334 |
+
<Button variant="ghost" size="sm" onClick={() => setIsConfiguringKey(false)}>
|
| 335 |
+
Batal
|
| 336 |
+
</Button>
|
| 337 |
+
)}
|
| 338 |
+
<Button
|
| 339 |
+
variant="primary"
|
| 340 |
+
size="sm"
|
| 341 |
+
onClick={handleSaveCredentials}
|
| 342 |
+
loading={isSavingKey}
|
| 343 |
+
className="bg-purple-600 hover:bg-purple-500 text-white"
|
| 344 |
+
>
|
| 345 |
+
Simpan & Hubungkan
|
| 346 |
+
</Button>
|
| 347 |
+
</div>
|
| 348 |
+
</div>
|
| 349 |
+
</div>
|
| 350 |
+
)}
|
| 351 |
+
|
| 352 |
+
{/* ── 3. Position Sizing & Margin Allocation ──────────────────────── */}
|
| 353 |
+
<div className="p-3.5 rounded-xl bg-bg-elevated/40 border border-border space-y-3">
|
| 354 |
+
<div className="flex items-center justify-between">
|
| 355 |
+
<span className="text-[11px] font-bold uppercase tracking-wider text-text-secondary flex items-center gap-1.5">
|
| 356 |
+
<Wallet size={13} className="text-purple-400" />
|
| 357 |
+
Alokasi Modal Margin ($ USD)
|
| 358 |
+
</span>
|
| 359 |
+
<span className="text-[11px] font-mono font-bold text-purple-300">
|
| 360 |
+
Notional Posisi: ${(marginUsd * leverage).toLocaleString(undefined, { minimumFractionDigits: 1 })} USD
|
| 361 |
+
</span>
|
| 362 |
+
</div>
|
| 363 |
+
|
| 364 |
+
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
| 365 |
+
<div>
|
| 366 |
+
<div className="flex items-center gap-2">
|
| 367 |
+
<div className="relative flex-1">
|
| 368 |
+
<span className="absolute left-3 top-2 text-text-muted font-mono text-xs">$</span>
|
| 369 |
+
<input
|
| 370 |
+
type="number"
|
| 371 |
+
min="5"
|
| 372 |
+
max="10000"
|
| 373 |
+
step="5"
|
| 374 |
+
value={marginUsd}
|
| 375 |
+
onChange={(e) => setMarginUsd(Math.max(1, parseFloat(e.target.value) || 0))}
|
| 376 |
+
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"
|
| 377 |
+
/>
|
| 378 |
+
</div>
|
| 379 |
+
<div className="flex items-center gap-1">
|
| 380 |
+
{[25, 50, 100, 200].map((amt) => (
|
| 381 |
+
<button
|
| 382 |
+
key={amt}
|
| 383 |
+
type="button"
|
| 384 |
+
onClick={() => setMarginUsd(amt)}
|
| 385 |
+
className={`px-2 py-1.5 rounded-lg text-[10px] font-mono font-semibold border transition-all ${
|
| 386 |
+
marginUsd === amt
|
| 387 |
+
? 'bg-purple-600/30 border-purple-500 text-purple-200'
|
| 388 |
+
: 'bg-bg-card border-border text-text-muted hover:text-text-primary'
|
| 389 |
+
}`}
|
| 390 |
+
>
|
| 391 |
+
${amt}
|
| 392 |
+
</button>
|
| 393 |
+
))}
|
| 394 |
+
</div>
|
| 395 |
+
</div>
|
| 396 |
+
</div>
|
| 397 |
+
|
| 398 |
+
{/* Leverage & Order Type Selector */}
|
| 399 |
+
<div className="flex items-center gap-2">
|
| 400 |
+
<div className="flex-1">
|
| 401 |
+
<div className="flex items-center justify-between text-[10px] text-text-muted mb-1">
|
| 402 |
+
<span className="uppercase font-bold">Leverage:</span>
|
| 403 |
+
<span className="font-mono text-purple-300 font-bold">{leverage}x</span>
|
| 404 |
+
</div>
|
| 405 |
+
<input
|
| 406 |
+
type="range"
|
| 407 |
+
min="1"
|
| 408 |
+
max="25"
|
| 409 |
+
step="1"
|
| 410 |
+
value={leverage}
|
| 411 |
+
onChange={(e) => setLeverage(parseInt(e.target.value, 10))}
|
| 412 |
+
className="w-full accent-purple-500 cursor-pointer"
|
| 413 |
+
/>
|
| 414 |
+
</div>
|
| 415 |
+
|
| 416 |
+
<div className="flex items-center rounded-lg border border-border bg-bg-card p-0.5 shrink-0 self-end">
|
| 417 |
+
<button
|
| 418 |
+
type="button"
|
| 419 |
+
onClick={() => setOrderType('Limit')}
|
| 420 |
+
className={`px-2.5 py-1.5 rounded-md text-[10px] font-bold transition-all ${
|
| 421 |
+
orderType === 'Limit' ? 'bg-purple-600 text-white shadow-sm' : 'text-text-muted'
|
| 422 |
+
}`}
|
| 423 |
+
>
|
| 424 |
+
Limit
|
| 425 |
+
</button>
|
| 426 |
+
<button
|
| 427 |
+
type="button"
|
| 428 |
+
onClick={() => setOrderType('Market')}
|
| 429 |
+
className={`px-2.5 py-1.5 rounded-md text-[10px] font-bold transition-all ${
|
| 430 |
+
orderType === 'Market' ? 'bg-purple-600 text-white shadow-sm' : 'text-text-muted'
|
| 431 |
+
}`}
|
| 432 |
+
>
|
| 433 |
+
Market
|
| 434 |
+
</button>
|
| 435 |
+
</div>
|
| 436 |
+
</div>
|
| 437 |
+
</div>
|
| 438 |
+
</div>
|
| 439 |
+
|
| 440 |
+
{/* ── 4. Key Price Levels (Auto-filled from Damian) ───────────────── */}
|
| 441 |
+
<div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
|
| 442 |
+
{/* Entry */}
|
| 443 |
+
<div className="p-2.5 rounded-xl bg-bg-card border border-border space-y-1">
|
| 444 |
+
<span className="text-[9px] uppercase font-bold text-text-muted block">
|
| 445 |
+
{orderType === 'Limit' ? 'ENTRY PRICE (LIMIT)' : 'ENTRY MARKET'}
|
| 446 |
+
</span>
|
| 447 |
+
<input
|
| 448 |
+
type="number"
|
| 449 |
+
step="any"
|
| 450 |
+
disabled={orderType === 'Market'}
|
| 451 |
+
value={entryPrice}
|
| 452 |
+
onChange={(e) => setEntryPrice(parseFloat(e.target.value) || 0)}
|
| 453 |
+
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"
|
| 454 |
+
/>
|
| 455 |
+
</div>
|
| 456 |
+
|
| 457 |
+
{/* Stop Loss */}
|
| 458 |
+
<div className="p-2.5 rounded-xl bg-rose-500/10 border border-rose-500/25 space-y-1">
|
| 459 |
+
<span className="text-[9px] uppercase font-bold text-rose-300/80 flex items-center justify-between">
|
| 460 |
+
<span>STOP LOSS (SL)</span>
|
| 461 |
+
<ShieldAlert size={11} className="text-rose-400" />
|
| 462 |
+
</span>
|
| 463 |
+
<input
|
| 464 |
+
type="number"
|
| 465 |
+
step="any"
|
| 466 |
+
value={stopLoss}
|
| 467 |
+
onChange={(e) => setStopLoss(parseFloat(e.target.value) || 0)}
|
| 468 |
+
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"
|
| 469 |
+
/>
|
| 470 |
+
</div>
|
| 471 |
+
|
| 472 |
+
{/* Take Profit 1 */}
|
| 473 |
+
<div className="p-2.5 rounded-xl bg-emerald-500/10 border border-emerald-500/25 space-y-1">
|
| 474 |
+
<span className="text-[9px] uppercase font-bold text-emerald-300/80 flex items-center justify-between">
|
| 475 |
+
<span>TARGET TP1</span>
|
| 476 |
+
<Target size={11} className="text-emerald-400" />
|
| 477 |
+
</span>
|
| 478 |
+
<input
|
| 479 |
+
type="number"
|
| 480 |
+
step="any"
|
| 481 |
+
value={takeProfit1}
|
| 482 |
+
onChange={(e) => setTakeProfit1(parseFloat(e.target.value) || 0)}
|
| 483 |
+
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"
|
| 484 |
+
/>
|
| 485 |
+
</div>
|
| 486 |
+
|
| 487 |
+
{/* Take Profit 2 (Optional) */}
|
| 488 |
+
<div className="p-2.5 rounded-xl bg-emerald-500/10 border border-emerald-500/25 space-y-1">
|
| 489 |
+
<span className="text-[9px] uppercase font-bold text-emerald-300/80 flex items-center justify-between">
|
| 490 |
+
<span>TARGET TP2</span>
|
| 491 |
+
<Target size={11} className="text-emerald-400" />
|
| 492 |
+
</span>
|
| 493 |
+
<input
|
| 494 |
+
type="number"
|
| 495 |
+
step="any"
|
| 496 |
+
value={takeProfit2 || ''}
|
| 497 |
+
onChange={(e) => setTakeProfit2(e.target.value ? parseFloat(e.target.value) : null)}
|
| 498 |
+
placeholder="Opsional"
|
| 499 |
+
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"
|
| 500 |
+
/>
|
| 501 |
+
</div>
|
| 502 |
+
</div>
|
| 503 |
+
|
| 504 |
+
{/* ── 5. Custom Split Take Profit (TP1 %) Slider ──────────────────── */}
|
| 505 |
+
<div className="p-3.5 rounded-xl bg-purple-950/20 border border-purple-500/30 space-y-2.5">
|
| 506 |
+
<div className="flex items-center justify-between">
|
| 507 |
+
<span className="text-[11px] font-bold uppercase tracking-wider text-purple-200 flex items-center gap-1.5">
|
| 508 |
+
<Zap size={13} className="text-purple-400" />
|
| 509 |
+
Porsi Ambil Cuan TP1 (Custom Split)
|
| 510 |
+
</span>
|
| 511 |
+
<div className="flex items-center gap-1">
|
| 512 |
+
{[25, 50, 75, 100].map((pct) => (
|
| 513 |
+
<button
|
| 514 |
+
key={pct}
|
| 515 |
+
type="button"
|
| 516 |
+
onClick={() => setTp1Percent(pct)}
|
| 517 |
+
className={`px-2 py-0.5 rounded text-[10px] font-mono font-bold transition-all ${
|
| 518 |
+
tp1Percent === pct
|
| 519 |
+
? 'bg-purple-600 text-white shadow-sm'
|
| 520 |
+
: 'bg-bg-card border border-border text-text-muted hover:text-text-primary'
|
| 521 |
+
}`}
|
| 522 |
+
>
|
| 523 |
+
{pct}%
|
| 524 |
+
</button>
|
| 525 |
+
))}
|
| 526 |
+
</div>
|
| 527 |
+
</div>
|
| 528 |
+
|
| 529 |
+
<div className="space-y-1">
|
| 530 |
+
<input
|
| 531 |
+
type="range"
|
| 532 |
+
min="10"
|
| 533 |
+
max="100"
|
| 534 |
+
step="5"
|
| 535 |
+
value={tp1Percent}
|
| 536 |
+
onChange={(e) => setTp1Percent(parseInt(e.target.value, 10))}
|
| 537 |
+
className="w-full accent-purple-500 cursor-pointer"
|
| 538 |
+
/>
|
| 539 |
+
<div className="flex items-center justify-between text-[10px] font-mono text-purple-300/90">
|
| 540 |
+
<span>TP1: {tp1Percent}%</span>
|
| 541 |
+
<span>{tp1Percent < 100 ? `TP2: ${100 - tp1Percent}%` : 'TP2: Dinonaktifkan'}</span>
|
| 542 |
+
</div>
|
| 543 |
+
</div>
|
| 544 |
+
|
| 545 |
+
{/* Explanation Text */}
|
| 546 |
+
<p className="text-[11px] text-purple-200/90 leading-tight">
|
| 547 |
+
{tp1Percent >= 100 ? (
|
| 548 |
+
<span>🎯 100% posisi akan ditutup penuh di <strong>TP1</strong> saat harga tercapai.</span>
|
| 549 |
+
) : (
|
| 550 |
+
<span>
|
| 551 |
+
🎯 <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'}).
|
| 552 |
+
</span>
|
| 553 |
+
)}
|
| 554 |
+
</p>
|
| 555 |
+
</div>
|
| 556 |
+
|
| 557 |
+
{/* ── 6. Live Risk & Reward Preview Summary ────────────────────────── */}
|
| 558 |
+
<div className="p-3 rounded-xl bg-bg-elevated/40 border border-border flex flex-wrap items-center justify-between gap-3 text-xs">
|
| 559 |
+
<div>
|
| 560 |
+
<span className="text-[10px] text-text-muted uppercase font-bold block">POTENSI CUAN TOTAL</span>
|
| 561 |
+
<span className="text-sm font-bold font-mono text-emerald-400">
|
| 562 |
+
+${totalEstGain.toFixed(2)} USD
|
| 563 |
+
</span>
|
| 564 |
+
</div>
|
| 565 |
+
|
| 566 |
+
<div>
|
| 567 |
+
<span className="text-[10px] text-text-muted uppercase font-bold block">MAKSIMAL RISIKO (SL)</span>
|
| 568 |
+
<span className="text-sm font-bold font-mono text-rose-400">
|
| 569 |
+
-${Math.abs(estLossUsd).toFixed(2)} USD
|
| 570 |
+
</span>
|
| 571 |
+
</div>
|
| 572 |
+
|
| 573 |
+
<div>
|
| 574 |
+
<span className="text-[10px] text-text-muted uppercase font-bold block">RISK / REWARD RIIL</span>
|
| 575 |
+
<span className="text-sm font-bold font-mono text-purple-300">
|
| 576 |
+
1 : {estimatedRR}
|
| 577 |
+
</span>
|
| 578 |
+
</div>
|
| 579 |
+
</div>
|
| 580 |
+
|
| 581 |
+
{/* ── 7. Action Button ────────────────────────────────────────────── */}
|
| 582 |
+
<div className="flex items-center justify-end gap-2 pt-2 border-t border-border/50">
|
| 583 |
+
<Button variant="ghost" size="md" onClick={onClose} disabled={isSubmitting}>
|
| 584 |
+
Batal
|
| 585 |
+
</Button>
|
| 586 |
+
<Button
|
| 587 |
+
variant="primary"
|
| 588 |
+
size="md"
|
| 589 |
+
onClick={handleExecute}
|
| 590 |
+
loading={isSubmitting}
|
| 591 |
+
icon={<Zap size={15} />}
|
| 592 |
+
className="bg-purple-600 hover:bg-purple-500 text-white font-bold px-5 shadow-lg shadow-purple-600/30"
|
| 593 |
+
>
|
| 594 |
+
Eksekusi Order ke Bybit
|
| 595 |
+
</Button>
|
| 596 |
+
</div>
|
| 597 |
+
</div>
|
| 598 |
+
</Modal>
|
| 599 |
+
);
|
| 600 |
+
}
|
frontend/src/components/signals/AIExecutiveSummaryCard.tsx
CHANGED
|
@@ -16,6 +16,7 @@ import {
|
|
| 16 |
} from 'lucide-react';
|
| 17 |
import { useToast } from '../ui/Toast';
|
| 18 |
import { journalApi } from '../../api/journal';
|
|
|
|
| 19 |
|
| 20 |
export interface AIExecutiveSummary {
|
| 21 |
bias: string;
|
|
@@ -285,6 +286,7 @@ export function AIExecutiveSummaryCard({
|
|
| 285 |
const [copied, setCopied] = useState(false);
|
| 286 |
const [isLogging, setIsLogging] = useState(false);
|
| 287 |
const [isLogged, setIsLogged] = useState(false);
|
|
|
|
| 288 |
const { toast } = useToast();
|
| 289 |
|
| 290 |
useEffect(() => {
|
|
@@ -372,8 +374,18 @@ export function AIExecutiveSummaryCard({
|
|
| 372 |
</div>
|
| 373 |
</div>
|
| 374 |
|
| 375 |
-
{/* Action Buttons: Log to Journal & Copy Setup */}
|
| 376 |
<div className="flex items-center gap-1.5 flex-wrap">
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 377 |
<button
|
| 378 |
type="button"
|
| 379 |
onClick={handleLogToJournal}
|
|
@@ -549,6 +561,18 @@ export function AIExecutiveSummaryCard({
|
|
| 549 |
)}
|
| 550 |
</div>
|
| 551 |
)}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 552 |
</div>
|
| 553 |
);
|
| 554 |
}
|
|
|
|
| 16 |
} from 'lucide-react';
|
| 17 |
import { useToast } from '../ui/Toast';
|
| 18 |
import { journalApi } from '../../api/journal';
|
| 19 |
+
import { ExecutionModal } from '../execution/ExecutionModal';
|
| 20 |
|
| 21 |
export interface AIExecutiveSummary {
|
| 22 |
bias: string;
|
|
|
|
| 286 |
const [copied, setCopied] = useState(false);
|
| 287 |
const [isLogging, setIsLogging] = useState(false);
|
| 288 |
const [isLogged, setIsLogged] = useState(false);
|
| 289 |
+
const [isExecutionOpen, setIsExecutionOpen] = useState(false);
|
| 290 |
const { toast } = useToast();
|
| 291 |
|
| 292 |
useEffect(() => {
|
|
|
|
| 374 |
</div>
|
| 375 |
</div>
|
| 376 |
|
| 377 |
+
{/* Action Buttons: Execute, Log to Journal & Copy Setup */}
|
| 378 |
<div className="flex items-center gap-1.5 flex-wrap">
|
| 379 |
+
<button
|
| 380 |
+
type="button"
|
| 381 |
+
onClick={() => setIsExecutionOpen(true)}
|
| 382 |
+
className="px-3 py-1.5 rounded-lg border border-purple-500/50 bg-gradient-to-r from-purple-600 to-indigo-600 hover:from-purple-500 hover:to-indigo-500 text-white text-[11px] font-bold flex items-center gap-1.5 transition-all shadow-md shadow-purple-600/25 active:scale-95 group"
|
| 383 |
+
title="Eksekusi setup ini secara presisi ke bursa"
|
| 384 |
+
>
|
| 385 |
+
<Zap size={12} className="text-yellow-300 fill-yellow-300 group-hover:scale-110 transition-transform" />
|
| 386 |
+
<span>Eksekusi Order</span>
|
| 387 |
+
</button>
|
| 388 |
+
|
| 389 |
<button
|
| 390 |
type="button"
|
| 391 |
onClick={handleLogToJournal}
|
|
|
|
| 561 |
)}
|
| 562 |
</div>
|
| 563 |
)}
|
| 564 |
+
|
| 565 |
+
{/* ── 6. Execution Modal ────────────────────────────────────────── */}
|
| 566 |
+
<ExecutionModal
|
| 567 |
+
isOpen={isExecutionOpen}
|
| 568 |
+
onClose={() => setIsExecutionOpen(false)}
|
| 569 |
+
symbol={symbol}
|
| 570 |
+
summary={summary}
|
| 571 |
+
markPrice={dataSnapshot?.mark_price}
|
| 572 |
+
onExecutionSuccess={() => {
|
| 573 |
+
setIsLogged(true);
|
| 574 |
+
}}
|
| 575 |
+
/>
|
| 576 |
</div>
|
| 577 |
);
|
| 578 |
}
|
tests/test_execution.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Unit and regression tests for Bybit V5 Execution Engine and /api/execution endpoints.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import sys
|
| 6 |
+
import os
|
| 7 |
+
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "backend")))
|
| 8 |
+
|
| 9 |
+
import pytest
|
| 10 |
+
from fastapi.testclient import TestClient
|
| 11 |
+
from unittest.mock import AsyncMock, patch
|
| 12 |
+
|
| 13 |
+
from main import app
|
| 14 |
+
from engine.execution.bybit_executor import BybitExecutor
|
| 15 |
+
|
| 16 |
+
client = TestClient(app)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def test_bybit_signature_generation():
|
| 20 |
+
"""Verify HMAC-SHA256 signature algorithm against expected hash."""
|
| 21 |
+
executor = BybitExecutor(api_key="test_key", api_secret="test_secret", mode="demo")
|
| 22 |
+
timestamp = "1672531199000"
|
| 23 |
+
payload = '{"category":"linear","symbol":"BTCUSDT"}'
|
| 24 |
+
|
| 25 |
+
sig = executor._generate_signature(timestamp, payload)
|
| 26 |
+
assert isinstance(sig, str)
|
| 27 |
+
assert len(sig) == 64 # SHA256 hex digest is 64 characters
|
| 28 |
+
|
| 29 |
+
# Signature should be deterministic
|
| 30 |
+
sig2 = executor._generate_signature(timestamp, payload)
|
| 31 |
+
assert sig == sig2
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def test_bybit_rounding_step_and_tick():
|
| 35 |
+
"""Verify exchange step-size and tick-size rounding logic."""
|
| 36 |
+
# Step size: floor to nearest step
|
| 37 |
+
assert BybitExecutor._round_step(12.3456, 0.01) == 12.34
|
| 38 |
+
assert BybitExecutor._round_step(12.3456, 0.1) == 12.3
|
| 39 |
+
assert BybitExecutor._round_step(12.9, 1.0) == 12.0
|
| 40 |
+
assert BybitExecutor._round_step(0.0039, 0.001) == 0.003
|
| 41 |
+
|
| 42 |
+
# Tick size: round to nearest tick
|
| 43 |
+
assert BybitExecutor._round_tick(0.18567, 0.0001) == 0.1857
|
| 44 |
+
assert BybitExecutor._round_tick(0.18562, 0.0001) == 0.1856
|
| 45 |
+
assert BybitExecutor._round_tick(64321.4, 0.5) == 64321.5
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
@pytest.mark.anyio
|
| 49 |
+
async def test_bybit_execute_split_tp_logic():
|
| 50 |
+
"""Verify custom split TP1/TP2 allocation and calculation."""
|
| 51 |
+
executor = BybitExecutor(api_key="test_key", api_secret="test_secret", mode="demo")
|
| 52 |
+
|
| 53 |
+
# Mock get_instrument_info and _request
|
| 54 |
+
with patch.object(executor, "get_instrument_info", new_callable=AsyncMock) as mock_info, \
|
| 55 |
+
patch.object(executor, "set_leverage", new_callable=AsyncMock) as mock_lev, \
|
| 56 |
+
patch.object(executor, "_request", new_callable=AsyncMock) as mock_req:
|
| 57 |
+
|
| 58 |
+
mock_info.return_value = {
|
| 59 |
+
"symbol": "DOGEUSDT",
|
| 60 |
+
"base_coin": "DOGE",
|
| 61 |
+
"quote_coin": "USDT",
|
| 62 |
+
"qty_step": 1.0,
|
| 63 |
+
"min_order_qty": 1.0,
|
| 64 |
+
"max_order_qty": 1000000.0,
|
| 65 |
+
"tick_size": 0.0001,
|
| 66 |
+
"min_price": 0.0001,
|
| 67 |
+
"max_price": 100.0,
|
| 68 |
+
}
|
| 69 |
+
mock_lev.return_value = True
|
| 70 |
+
mock_req.return_value = {"retCode": 0, "result": {"orderId": "mock_order_123"}}
|
| 71 |
+
|
| 72 |
+
# Test 60% TP1 split
|
| 73 |
+
res = await executor.execute_trade_setup(
|
| 74 |
+
symbol="DOGEUSDT",
|
| 75 |
+
side="Buy",
|
| 76 |
+
order_type="Market",
|
| 77 |
+
margin_usd=50.0,
|
| 78 |
+
leverage=3,
|
| 79 |
+
stop_loss=0.1800,
|
| 80 |
+
take_profit_1=0.1940,
|
| 81 |
+
take_profit_2=0.2050,
|
| 82 |
+
tp1_percent=60.0,
|
| 83 |
+
mark_price=0.1850,
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
assert res["success"] is True
|
| 87 |
+
assert res["symbol"] == "DOGEUSDT"
|
| 88 |
+
assert res["leverage"] == 3
|
| 89 |
+
# notional = 50 * 3 = 150 USD. qty = 150 / 0.1850 = 810.8 -> 810.0
|
| 90 |
+
assert res["total_qty"] == 810.0
|
| 91 |
+
assert len(res["tp_orders"]) == 2
|
| 92 |
+
# TP1 = 60% of 810 = 486.0
|
| 93 |
+
assert res["tp_orders"][0]["tp_level"] == "TP1"
|
| 94 |
+
assert res["tp_orders"][0]["qty"] == 486.0
|
| 95 |
+
# TP2 = 40% of 810 = 324.0
|
| 96 |
+
assert res["tp_orders"][1]["tp_level"] == "TP2"
|
| 97 |
+
assert res["tp_orders"][1]["qty"] == 324.0
|
| 98 |
+
|
| 99 |
+
await executor.close()
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def test_execution_settings_endpoint():
|
| 103 |
+
"""Verify /api/execution/bybit/settings endpoint returns valid JSON."""
|
| 104 |
+
resp = client.get("/api/execution/bybit/settings")
|
| 105 |
+
assert resp.status_code == 200
|
| 106 |
+
data = resp.json()
|
| 107 |
+
assert "configured" in data
|
| 108 |
+
assert "mode" in data
|