File size: 19,153 Bytes
86abcb2
 
 
 
 
740fcec
86abcb2
 
 
 
 
740fcec
48f60d7
86abcb2
740fcec
 
 
 
 
 
86abcb2
740fcec
86abcb2
 
740fcec
86abcb2
740fcec
 
 
 
 
86abcb2
740fcec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86abcb2
 
 
 
 
 
740fcec
 
 
 
 
 
 
 
 
 
 
 
 
86abcb2
 
 
 
740fcec
86abcb2
 
48f60d7
 
 
 
 
 
86abcb2
 
 
 
 
 
 
 
 
 
 
 
48f60d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc3aa02
 
86abcb2
 
 
 
 
740fcec
86abcb2
 
 
 
 
 
 
 
 
 
 
740fcec
 
 
 
 
 
 
 
 
 
 
86abcb2
 
740fcec
86abcb2
740fcec
 
 
86abcb2
 
 
 
740fcec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86abcb2
 
 
 
740fcec
86abcb2
 
740fcec
 
86abcb2
 
740fcec
86abcb2
 
 
 
 
 
 
 
 
740fcec
 
 
 
 
 
 
 
 
 
 
 
 
86abcb2
 
 
 
 
 
 
 
 
 
 
740fcec
 
 
 
 
 
86abcb2
 
 
 
740fcec
86abcb2
 
 
740fcec
 
 
86abcb2
 
740fcec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc3aa02
 
740fcec
cc3aa02
 
86abcb2
 
 
 
 
 
 
 
 
 
 
 
740fcec
 
 
 
 
 
 
 
 
 
 
 
 
 
86abcb2
740fcec
 
 
48f60d7
 
 
 
 
740fcec
48f60d7
 
740fcec
 
 
 
 
 
 
075133b
 
 
 
 
 
 
 
 
 
740fcec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
075133b
 
740fcec
 
 
 
 
075133b
 
740fcec
 
 
 
 
 
 
 
 
 
 
 
 
 
075133b
 
740fcec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86abcb2
 
 
 
 
80df99b
 
 
 
 
 
86abcb2
80df99b
48f60d7
 
 
 
80df99b
 
48f60d7
 
 
 
 
 
 
 
86abcb2
cc3aa02
 
 
 
 
 
86abcb2
80df99b
86abcb2
 
80df99b
86abcb2
cc3aa02
86abcb2
 
 
 
 
 
 
 
cc3aa02
80df99b
86abcb2
 
 
a7c4232
 
 
 
 
86abcb2
 
 
 
 
 
 
 
 
 
740fcec
 
86abcb2
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
"""
/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"

    @field_validator("side")
    @classmethod
    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

    @field_validator("order_type")
    @classmethod
    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


@router.get("/bybit/settings")
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,
    }


@router.post("/bybit/settings")
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()


@router.get("/bybit/balance")
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()


@router.post("/bybit/order")
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()