Spaces:
Sleeping
Sleeping
Naufal Arhab
chore: full codebase audit fixes, L2/whale/calibration upgrades, and rebuild frontend dist
48f60d7 Download backend/routers/execution.py from agus1111/Perps-Terminal: direct link, hf CLI and curl.
- Browser
- Download file 19.2 kB
-
https://huggingface.co/spaces/agus1111/Perps-Terminal/resolve/main/backend/routers/execution.py
- Command line
-
hf download hf://spaces/agus1111/Perps-Terminal/backend/routers/execution.py
-
curl -L -o execution.py https://huggingface.co/spaces/agus1111/Perps-Terminal/resolve/main/backend/routers/execution.py
19.2 kB
| """ | |
| /api/execution endpoints — Bybit V5 Live/Demo Order Execution Router | |
| Connects Damian trade setups directly to Bybit Linear Futures with bracket SL and split TP. | |
| """ | |
| import asyncio | |
| import os | |
| import re | |
| import logging | |
| from typing import Any | |
| from fastapi import APIRouter, Depends, Header, HTTPException, Request | |
| from pydantic import BaseModel, Field, field_validator | |
| from config import BYBIT_API_KEY, BYBIT_SECRET, PROXY_URL | |
| from engine.execution.bybit_executor import ( | |
| BybitExecutor, | |
| watch_limit_entry_and_place_tp2, | |
| watch_position_tp1_breakeven, | |
| ) | |
| from database.db import async_create_journal_entry | |
| from security import require_api_token | |
| logger = logging.getLogger(__name__) | |
| _BG_TP2_TASKS: set[asyncio.Task] = set() | |
| router = APIRouter( | |
| prefix="/api/execution", | |
| tags=["execution"], | |
| dependencies=[Depends(require_api_token)], | |
| ) | |
| def _resolve_bybit_credentials( | |
| req_key: str | None = None, | |
| req_secret: str | None = None, | |
| req_mode: str | None = None, | |
| header_key: str | None = None, | |
| header_secret: str | None = None, | |
| header_mode: str | None = None, | |
| ) -> tuple[str, str, str, str]: | |
| """ | |
| Resolve Bybit API credentials statelessly per request without storing in global RAM. | |
| Priority: request body -> request headers -> server environment variables. | |
| Returns: (api_key, api_secret, mode, source) | |
| """ | |
| b_key = (req_key or "").strip() | |
| b_sec = (req_secret or "").strip() | |
| h_key = (header_key or "").strip() | |
| h_sec = (header_secret or "").strip() | |
| env_key = (BYBIT_API_KEY or os.getenv("BYBIT_API_KEY", "")).strip() | |
| env_sec = (BYBIT_SECRET or os.getenv("BYBIT_SECRET", "")).strip() | |
| if b_key and b_sec: | |
| api_key, api_secret, source = b_key, b_sec, "request_body" | |
| elif h_key and h_sec: | |
| api_key, api_secret, source = h_key, h_sec, "request_headers" | |
| elif env_key and env_sec: | |
| api_key, api_secret, source = env_key, env_sec, "server_env" | |
| else: | |
| api_key, api_secret, source = "", "", "none" | |
| mode = ( | |
| req_mode | |
| or header_mode | |
| or os.getenv("BYBIT_MODE", "demo") | |
| or "demo" | |
| ).lower().strip() | |
| return api_key, api_secret, mode, source | |
| def _get_active_executor( | |
| req_key: str | None = None, | |
| req_secret: str | None = None, | |
| req_mode: str | None = None, | |
| header_key: str | None = None, | |
| header_secret: str | None = None, | |
| header_mode: str | None = None, | |
| ) -> tuple[BybitExecutor, str]: | |
| """Instantiate stateless BybitExecutor for the current request only.""" | |
| api_key, api_secret, mode, source = _resolve_bybit_credentials( | |
| req_key=req_key, | |
| req_secret=req_secret, | |
| req_mode=req_mode, | |
| header_key=header_key, | |
| header_secret=header_secret, | |
| header_mode=header_mode, | |
| ) | |
| if not api_key or not api_secret: | |
| raise HTTPException( | |
| status_code=400, | |
| detail="API Key atau API Secret Bybit belum dikonfigurasi. Masukkan kredensial Bybit Anda di modal eksekusi atau set di environment server.", | |
| ) | |
| return BybitExecutor( | |
| api_key=api_key, | |
| api_secret=api_secret, | |
| mode=mode, | |
| proxy_url=PROXY_URL or None, | |
| ), source | |
| class BybitSettingsRequest(BaseModel): | |
| api_key: str | None = None | |
| api_secret: str | None = None | |
| mode: str = "demo" # "demo" | "testnet" | "real" | |
| class ExecuteBybitOrderRequest(BaseModel): | |
| symbol: str | |
| side: str # "Buy" | "Sell" | "Long" | "Short" | |
| order_type: str = "Market" # "Market" | "Limit" | |
| def _validate_side(cls, v: str) -> str: | |
| val = (v or "").strip() | |
| if val.upper() not in ("BUY", "LONG", "SELL", "SHORT"): | |
| raise ValueError("side harus bernilai Buy/Long atau Sell/Short") | |
| return val | |
| def _validate_order_type(cls, v: str) -> str: | |
| val = (v or "").strip() | |
| if val.upper() not in ("MARKET", "LIMIT"): | |
| raise ValueError("order_type harus bernilai Market atau Limit") | |
| return val | |
| margin_usd: float = Field(default=0.0, ge=0, description="Nominal modal margin dalam USD") | |
| margin_percent: float | None = Field(default=None, ge=0.1, le=100.0, description="Persentase alokasi equity (opsional)") | |
| leverage: int = Field(..., ge=1, le=50, description="Rekomendasi leverage") | |
| stop_loss: float = Field(..., gt=0, description="Harga Stop Loss") | |
| take_profit_1: float = Field(..., gt=0, description="Harga Take Profit 1") | |
| take_profit_2: float | None = None | |
| tp1_percent: float = Field(default=50.0, ge=10.0, le=100.0, description="Persentase porsi TP1") | |
| auto_breakeven: bool = Field(default=False, description="Geser SL ke breakeven (+6 bps) otomatis setelah TP1 tercapai") | |
| entry_price: float | None = None | |
| mark_price: float | None = None | |
| api_key: str | None = None | |
| api_secret: str | None = None | |
| mode: str | None = None | |
| log_to_journal: bool = True | |
| summary_tldr: str | None = None | |
| model_used: str | None = None | |
| async def get_bybit_settings( | |
| x_bybit_api_key: str | None = Header(default=None, alias="X-Bybit-Api-Key"), | |
| x_bybit_api_secret: str | None = Header(default=None, alias="X-Bybit-Api-Secret"), | |
| x_bybit_mode: str | None = Header(default=None, alias="X-Bybit-Mode"), | |
| ): | |
| """Check stateless Bybit API connection status and resolved environment mode.""" | |
| key, secret, mode, source = _resolve_bybit_credentials( | |
| header_key=x_bybit_api_key, | |
| header_secret=x_bybit_api_secret, | |
| header_mode=x_bybit_mode, | |
| ) | |
| masked_key = f"{key[:4]}***{key[-4:]}" if len(key) >= 8 else ("Sudah terpasang" if key else "") | |
| return { | |
| "configured": bool(key and secret), | |
| "masked_key": masked_key, | |
| "mode": mode, | |
| "source": source, | |
| "stateless": True, | |
| } | |
| async def save_bybit_settings( | |
| body: BybitSettingsRequest, | |
| x_bybit_api_key: str | None = Header(default=None, alias="X-Bybit-Api-Key"), | |
| x_bybit_api_secret: str | None = Header(default=None, alias="X-Bybit-Api-Secret"), | |
| x_bybit_mode: str | None = Header(default=None, alias="X-Bybit-Mode"), | |
| ): | |
| """Validate Bybit API credentials statelessly (credentials are NOT cached in global server RAM).""" | |
| executor, source = _get_active_executor( | |
| req_key=body.api_key, | |
| req_secret=body.api_secret, | |
| req_mode=body.mode, | |
| header_key=x_bybit_api_key, | |
| header_secret=x_bybit_api_secret, | |
| header_mode=x_bybit_mode, | |
| ) | |
| try: | |
| balance = await executor.get_wallet_balance() | |
| return { | |
| "success": True, | |
| "message": f"Koneksi ke Bybit ({executor.mode.upper()}) berhasil terhubung! (Mode stateless)", | |
| "balance": balance, | |
| "mode": executor.mode, | |
| "source": source, | |
| "stateless": True, | |
| } | |
| except Exception as exc: | |
| logger.warning("Bybit credential validation failed: %s", exc) | |
| raise HTTPException( | |
| status_code=400, | |
| detail=f"Kredensial Bybit gagal divalidasi: {str(exc)}", | |
| ) | |
| finally: | |
| await executor.close() | |
| async def get_bybit_balance( | |
| mode: str | None = None, | |
| x_bybit_api_key: str | None = Header(default=None, alias="X-Bybit-Api-Key"), | |
| x_bybit_api_secret: str | None = Header(default=None, alias="X-Bybit-Api-Secret"), | |
| x_bybit_mode: str | None = Header(default=None, alias="X-Bybit-Mode"), | |
| ): | |
| """Fetch live available USDT balance from Bybit Unified account statelessly.""" | |
| executor, _ = _get_active_executor( | |
| req_mode=mode, | |
| header_key=x_bybit_api_key, | |
| header_secret=x_bybit_api_secret, | |
| header_mode=x_bybit_mode, | |
| ) | |
| try: | |
| balance = await executor.get_wallet_balance() | |
| return balance | |
| except Exception as exc: | |
| logger.error("Failed to fetch Bybit balance: %s", exc) | |
| raise HTTPException(status_code=500, detail=f"Gagal mengambil saldo Bybit: {str(exc)}") | |
| finally: | |
| await executor.close() | |
| async def execute_bybit_order( | |
| body: ExecuteBybitOrderRequest, | |
| x_bybit_api_key: str | None = Header(default=None, alias="X-Bybit-Api-Key"), | |
| x_bybit_api_secret: str | None = Header(default=None, alias="X-Bybit-Api-Secret"), | |
| x_bybit_mode: str | None = Header(default=None, alias="X-Bybit-Mode"), | |
| ): | |
| """ | |
| Execute institutional trade setup directly on Bybit V5. | |
| Sets leverage, executes entry, attaches position Stop Loss, and places custom split TP1/TP2 limit orders. | |
| """ | |
| executor, _ = _get_active_executor( | |
| req_key=body.api_key, | |
| req_secret=body.api_secret, | |
| req_mode=body.mode, | |
| header_key=x_bybit_api_key, | |
| header_secret=x_bybit_api_secret, | |
| header_mode=x_bybit_mode, | |
| ) | |
| try: | |
| # If margin_usd not explicitly provided or is 0, but margin_percent is given, calculate from equity | |
| if (body.margin_usd <= 0) and body.margin_percent: | |
| bal = await executor.get_wallet_balance() | |
| equity = float(bal.get("total_equity") or bal.get("available_balance") or 0.0) | |
| if equity <= 0: | |
| raise HTTPException( | |
| status_code=400, | |
| detail="Total equity Bybit terdeteksi $0, tidak dapat menghitung alokasi margin persen.", | |
| ) | |
| body.margin_usd = round(equity * (body.margin_percent / 100.0), 2) | |
| if body.margin_usd <= 0: | |
| raise HTTPException( | |
| status_code=400, | |
| detail="Hasil perhitungan margin terlalu kecil (< $0.01).", | |
| ) | |
| elif body.margin_usd <= 0: | |
| raise HTTPException( | |
| status_code=400, | |
| detail="Margin USD harus lebih besar dari 0 atau tentukan persentase alokasi equity.", | |
| ) | |
| exec_result = await executor.execute_trade_setup( | |
| symbol=body.symbol, | |
| side=body.side, | |
| order_type=body.order_type, | |
| margin_usd=body.margin_usd, | |
| leverage=body.leverage, | |
| stop_loss=body.stop_loss, | |
| take_profit_1=body.take_profit_1, | |
| take_profit_2=body.take_profit_2, | |
| tp1_percent=body.tp1_percent, | |
| entry_price=body.entry_price, | |
| mark_price=body.mark_price, | |
| auto_breakeven=body.auto_breakeven, | |
| ) | |
| tp2_watcher_scheduled = False | |
| breakeven_watcher_scheduled = False | |
| breakeven_status = "DISABLED" | |
| is_serverless = bool(os.getenv("VERCEL") or os.getenv("NOW_REGION")) | |
| tp1_item = next( | |
| (tp for tp in exec_result.get("tp_orders", []) if tp.get("tp_level") == "TP1"), | |
| None, | |
| ) | |
| tp2_item = next( | |
| (tp for tp in exec_result.get("tp_orders", []) if tp.get("tp_level") == "TP2"), | |
| None, | |
| ) | |
| tp2_watch_item = ( | |
| tp2_item if (tp2_item and tp2_item.get("status") == "WATCHING_FILL") else None | |
| ) | |
| tp2_active = ( | |
| tp2_item is not None | |
| and tp2_item.get("status") != "FAILED" | |
| and float(tp2_item.get("qty") or 0.0) > 0.0 | |
| ) | |
| has_runner = bool( | |
| tp2_active | |
| or (tp2_item is None and float(exec_result.get("tp2_qty") or 0.0) > 0.0) | |
| ) | |
| total_qty_val = float(exec_result.get("total_qty") or 0.0) | |
| tp1_qty_val = float( | |
| exec_result.get("tp1_qty") | |
| or (tp1_item.get("qty") if tp1_item else 0.0) | |
| or 0.0 | |
| ) | |
| tp1_price_val = ( | |
| float(tp1_item["price"]) | |
| if (tp1_item and tp1_item.get("status") == "WATCHING_FILL" and tp1_item.get("price")) | |
| else None | |
| ) | |
| tp1_pct_val = ( | |
| float(tp1_item["percent"]) | |
| if (tp1_item and tp1_item.get("percent")) | |
| else None | |
| ) | |
| tp1_order_id_val = tp1_item.get("order_id") if tp1_item else None | |
| if not is_serverless and tp2_watch_item and exec_result.get("entry_order_id"): | |
| task = asyncio.create_task( | |
| watch_limit_entry_and_place_tp2( | |
| api_key=executor.api_key, | |
| api_secret=executor.api_secret, | |
| mode=executor.mode, | |
| proxy_url=PROXY_URL or None, | |
| symbol=exec_result["symbol"], | |
| entry_order_id=exec_result["entry_order_id"], | |
| opposite_side=tp2_watch_item.get("opposite_side") or ("Sell" if exec_result["side"] == "Buy" else "Buy"), | |
| tp2_qty=float(tp2_watch_item["qty"]), | |
| tp2_price=float(tp2_watch_item["price"]), | |
| percent=float(tp2_watch_item["percent"]), | |
| poll_interval=10.0, | |
| max_polls=4320, | |
| auto_breakeven=bool(body.auto_breakeven and has_runner), | |
| side=exec_result["side"], | |
| total_qty=total_qty_val, | |
| tp1_qty=tp1_qty_val, | |
| tp1_order_id=tp1_order_id_val, | |
| tp1_price=tp1_price_val, | |
| tp1_percent=tp1_pct_val, | |
| ) | |
| ) | |
| _BG_TP2_TASKS.add(task) | |
| task.add_done_callback(_BG_TP2_TASKS.discard) | |
| tp2_watcher_scheduled = True | |
| if body.auto_breakeven and has_runner: | |
| breakeven_watcher_scheduled = True | |
| breakeven_status = "WATCHING_TP1_FOR_BREAKEVEN" | |
| if body.auto_breakeven and not breakeven_watcher_scheduled: | |
| if not has_runner: | |
| breakeven_status = "SKIPPED_NO_RUNNER" | |
| elif is_serverless: | |
| breakeven_status = "STATELESS_MANUAL_BREAKEVEN" | |
| elif not tp1_order_id_val: | |
| breakeven_status = "SKIPPED_NO_TP1_ORDER" | |
| else: | |
| be_task = asyncio.create_task( | |
| watch_position_tp1_breakeven( | |
| api_key=executor.api_key, | |
| api_secret=executor.api_secret, | |
| mode=executor.mode, | |
| proxy_url=PROXY_URL or None, | |
| symbol=exec_result["symbol"], | |
| side=exec_result["side"], | |
| total_qty=total_qty_val, | |
| tp1_qty=tp1_qty_val, | |
| tp1_order_id=tp1_order_id_val, | |
| ) | |
| ) | |
| _BG_TP2_TASKS.add(be_task) | |
| be_task.add_done_callback(_BG_TP2_TASKS.discard) | |
| breakeven_watcher_scheduled = True | |
| breakeven_status = "WATCHING_TP1_FOR_BREAKEVEN" | |
| exec_result["tp2_watcher_scheduled"] = tp2_watcher_scheduled | |
| exec_result["breakeven_watcher_scheduled"] = breakeven_watcher_scheduled | |
| exec_result["breakeven_status"] = breakeven_status | |
| # Automatically log to Trade Journal if requested | |
| journal_entry = None | |
| if body.log_to_journal: | |
| try: | |
| def _fmt_exec_price(price: float) -> str: | |
| if abs(price) >= 0.01 or price == 0: | |
| return f"${price:,.4f}" | |
| decimals = 10 if abs(price) < 0.0001 else 8 | |
| return f"${price:.{decimals}f}".rstrip("0").rstrip(".") | |
| bias_label = "STRONG LONG" if body.side.upper() in ("BUY", "LONG") else "STRONG SHORT" | |
| tp1_pct = body.tp1_percent if has_runner else 100.0 | |
| if tp1_item and tp1_item.get("status") == "FAILED": | |
| tp_str = f"TP1: GAGAL PASANG ({_fmt_exec_price(body.take_profit_1)})" | |
| else: | |
| tp_str = f"TP1: {_fmt_exec_price(body.take_profit_1)} ({tp1_pct:.0f}%)" | |
| if has_runner and body.take_profit_2: | |
| tp_str += f" | TP2: {_fmt_exec_price(body.take_profit_2)} ({100 - tp1_pct:.0f}%)" | |
| elif tp2_item and tp2_item.get("status") == "FAILED" and body.take_profit_2: | |
| tp_str += f" | TP2: GAGAL PASANG ({_fmt_exec_price(body.take_profit_2)})" | |
| eff_entry = body.entry_price or exec_result.get("entry_price") | |
| if body.order_type.upper() == "LIMIT": | |
| entry_str = _fmt_exec_price(float(eff_entry)) if eff_entry else "LIMIT ORDER" | |
| else: | |
| entry_str = _fmt_exec_price(body.entry_price) if body.entry_price else "MARKET ORDER" | |
| margin_label = ( | |
| f"Margin: ${body.margin_usd:.1f} ({body.margin_percent:.1f}% eq) | Lev: {body.leverage}x" | |
| if body.margin_percent | |
| else f"Margin: ${body.margin_usd:.1f} | Lev: {body.leverage}x" | |
| ) | |
| journal_entry = await async_create_journal_entry({ | |
| "symbol": body.symbol.upper().strip().replace("/", "").replace("-", "").replace("_", "").replace(" ", ""), | |
| "bias": bias_label, | |
| "entry_zone": entry_str, | |
| "stop_loss": _fmt_exec_price(body.stop_loss), | |
| "take_profit": tp_str, | |
| "risk_reward": margin_label, | |
| "leverage": f"{body.leverage}x", | |
| "invalidation": f"Bybit Order ID: {exec_result.get('entry_order_id', 'N/A')}", | |
| "summary_tldr": body.summary_tldr or f"Order dieksekusi otomatis ke Bybit ({exec_result.get('mode', 'DEMO').upper()})", | |
| "model_used": body.model_used or "bybit-auto-execution", | |
| "snapshot_data": { | |
| "execution_result": exec_result, | |
| "mode": exec_result.get("mode"), | |
| "margin_usd": body.margin_usd, | |
| "margin_percent": body.margin_percent, | |
| "tp1_percent": tp1_pct, | |
| }, | |
| "status": "PENDING", | |
| }) | |
| try: | |
| from routers.ws import broadcast | |
| await broadcast({"type": "journal_updated", "data": journal_entry}) | |
| except Exception: | |
| pass | |
| except Exception as j_err: | |
| logger.warning("Auto journal log after execution failed: %s", j_err) | |
| return { | |
| "success": True, | |
| "message": f"Order {body.symbol} berhasil dikirim ke Bybit ({exec_result.get('mode', 'DEMO').upper()})!", | |
| "execution": exec_result, | |
| "journal_entry": journal_entry, | |
| } | |
| except HTTPException: | |
| raise | |
| except ValueError as val_err: | |
| raise HTTPException(status_code=400, detail=str(val_err)) | |
| except Exception as exc: | |
| logger.error("[%s] Execution error: %s", body.symbol, exc) | |
| raise HTTPException(status_code=500, detail=f"Gagal mengeksekusi order Bybit: {str(exc)}") | |
| finally: | |
| await executor.close() | |