Perps-Terminal / backend /engine /execution /bybit_executor.py
Naufal Arhab
chore: full codebase audit fixes, L2/whale/calibration upgrades, and rebuild frontend dist
48f60d7
Raw History Blame Contribute Delete
38.9 kB
"""
Bybit V5 Execution Engine — Institutional-Grade Order Placement
Handles HMAC-SHA256 authentication, instrument step-size rounding,
dynamic leverage configuration, and custom split TP1/TP2 bracket orders.
"""
import asyncio
import time
import json
import hmac
import hashlib
import logging
import math
import os
from decimal import Decimal, InvalidOperation, ROUND_DOWN, ROUND_HALF_UP
from typing import Any
from urllib.parse import urlencode
import httpx
from engine.doh_resolver import enable_doh_bypass
enable_doh_bypass()
logger = logging.getLogger(__name__)
# Official Bybit V5 URLs
BYBIT_URLS = {
"demo": "https://api-demo.bybit.com", # Bybit Official Demo Trading
"testnet": "https://api-testnet.bybit.com", # Bybit Testnet Platform
"real": "https://api.bybit.com", # Bybit Production Mainnet
"real_alt": "https://api.bybit.biz", # Bybit Production Alternative (Bypass)
}
class BybitExecutor:
def __init__(
self,
api_key: str,
api_secret: str,
mode: str = "demo", # "demo" | "testnet" | "real"
proxy_url: str | None = None,
) -> None:
self.api_key = api_key.strip()
self.api_secret = api_secret.strip()
self.mode = mode.lower().strip()
self.proxy_url = proxy_url
self.base_url = BYBIT_URLS.get(self.mode, BYBIT_URLS["demo"])
self.recv_window = "5000"
client_kwargs = {
"base_url": self.base_url,
"timeout": httpx.Timeout(connect=5.0, read=15.0, write=5.0, pool=10.0),
"verify": True,
}
if proxy_url:
client_kwargs["proxy"] = proxy_url
self._client = httpx.AsyncClient(**client_kwargs)
async def close(self) -> None:
await self._client.aclose()
@staticmethod
def _clean_symbol(symbol: str) -> str:
"""Normalize perpetual pair formatting (e.g. BTC/USDT, btc-usdt -> BTCUSDT)."""
return symbol.upper().strip().replace("/", "").replace("-", "")
def _generate_signature(self, timestamp: str, payload_str: str) -> str:
"""Bybit V5 HMAC-SHA256 signature generator."""
param_str = f"{timestamp}{self.api_key}{self.recv_window}{payload_str}"
return hmac.new(
self.api_secret.encode("utf-8"),
param_str.encode("utf-8"),
hashlib.sha256,
).hexdigest()
async def _request(self, method: str, path: str, params: dict | None = None, json_body: dict | None = None) -> dict[str, Any]:
"""Send authenticated Bybit V5 request."""
timestamp = str(int(time.time() * 1000))
headers = {
"X-BAPI-API-KEY": self.api_key,
"X-BAPI-TIMESTAMP": timestamp,
"X-BAPI-RECV-WINDOW": self.recv_window,
"Content-Type": "application/json",
}
if method.upper() == "GET":
sorted_items = sorted((params or {}).items()) if params else []
query_str = urlencode(sorted_items) if sorted_items else ""
sign = self._generate_signature(timestamp, query_str)
headers["X-BAPI-SIGN"] = sign
req_path = f"{path}?{query_str}" if query_str else path
resp = await self._client.get(req_path, headers=headers)
else:
body_str = json.dumps(json_body, separators=(",", ":")) if json_body else ""
sign = self._generate_signature(timestamp, body_str)
headers["X-BAPI-SIGN"] = sign
resp = await self._client.post(path, content=body_str, headers=headers)
if resp.status_code != 200:
logger.error("Bybit HTTP %d error on %s: %s", resp.status_code, path, resp.text[:300])
raise RuntimeError(f"Bybit HTTP {resp.status_code}: {resp.text[:200]}")
data = resp.json()
ret_code = data.get("retCode", -1)
ret_msg = data.get("retMsg", "Unknown")
# retCode 0 is success; 110043 is "Set leverage not modified" which is fine
if ret_code != 0 and ret_code != 110043:
logger.warning("Bybit API error code %d: %s", ret_code, ret_msg)
raise RuntimeError(f"Bybit API Error ({ret_code}): {ret_msg}")
return data
# -------------------------------------------------------------------------
# Account & Instrument Information
# -------------------------------------------------------------------------
async def get_wallet_balance(self) -> dict[str, Any]:
"""Fetch Unified/Futures USDT available balance and total equity."""
data = await self._request("GET", "/v5/account/wallet-balance", {"accountType": "UNIFIED"})
acct_list = data.get("result", {}).get("list") or []
acct_item = acct_list[0] if acct_list else {}
coins = acct_item.get("coin", [])
usdt_info = next((c for c in coins if c.get("coin") == "USDT"), {})
acct_equity = float(acct_item.get("totalEquity") or 0.0)
available_balance = float(
acct_item.get("totalAvailableBalance")
or usdt_info.get("availableToWithdraw")
or usdt_info.get("walletBalance")
or 0.0
)
total_equity = float(usdt_info.get("equity") or acct_equity or usdt_info.get("walletBalance") or 0.0)
return {
"coin": "USDT",
"available_balance": available_balance,
"total_equity": total_equity,
"mode": self.mode,
"raw": data.get("result", {}),
}
async def get_instrument_info(self, symbol: str) -> dict[str, Any]:
"""Fetch contract precision, tickSize, and lotSize."""
sym = self._clean_symbol(symbol)
data = await self._request("GET", "/v5/market/instruments-info", {
"category": "linear",
"symbol": sym,
})
items = data.get("result", {}).get("list", [])
if not items:
raise ValueError(f"Symbol {sym} tidak ditemukan di Bybit Linear instruments.")
info = items[0]
lot_filter = info.get("lotSizeFilter", {})
price_filter = info.get("priceFilter", {})
return {
"symbol": sym,
"base_coin": info.get("baseCoin", ""),
"quote_coin": info.get("quoteCoin", "USDT"),
"qty_step": float(lot_filter.get("qtyStep", 0.001)),
"min_order_qty": float(lot_filter.get("minOrderQty", 0.001)),
"max_order_qty": float(lot_filter.get("maxOrderQty", 1000000.0)),
"tick_size": float(price_filter.get("tickSize", 0.0001)),
"min_price": float(price_filter.get("minPrice", 0.0001)),
"max_price": float(price_filter.get("maxPrice", 1000000.0)),
}
async def set_leverage(self, symbol: str, leverage: int) -> bool:
"""Set cross/isolated leverage for linear contract."""
sym = self._clean_symbol(symbol)
lev_str = str(max(1, min(leverage, 100)))
try:
await self._request("POST", "/v5/position/set-leverage", json_body={
"category": "linear",
"symbol": sym,
"buyLeverage": lev_str,
"sellLeverage": lev_str,
})
return True
except RuntimeError as exc:
# 110043 = "Set leverage not modified", already correct
if "110043" in str(exc) or "not modified" in str(exc).lower():
return True
raise
# -------------------------------------------------------------------------
# Execution Helpers: Rounding
# -------------------------------------------------------------------------
@staticmethod
def _get_precision(num: float) -> int:
"""Determine decimal precision of a step or tick."""
s = f"{num:.10f}".rstrip("0")
if "." in s:
return len(s.split(".")[1])
return 0
@classmethod
def _format_num(cls, value: float, step_or_tick: float | None = None) -> str:
"""Format price/qty as a plain decimal string without scientific notation."""
num = 0.0 if value == 0 else float(value)
if step_or_tick and step_or_tick > 0:
precision = cls._get_precision(step_or_tick)
return f"{num:.{precision}f}"
return format(Decimal(str(num)), "f")
@classmethod
def _round_step(cls, value: float, step: float) -> float:
"""Round down value to the nearest step using Decimal to avoid IEEE 754 truncation loss."""
if step <= 0:
return value
precision = cls._get_precision(step)
try:
d_val = Decimal(str(value))
d_step = Decimal(str(step))
steps = (d_val / d_step).to_integral_value(rounding=ROUND_DOWN)
return round(float(steps * d_step), precision)
except (InvalidOperation, ZeroDivisionError):
return round(math.floor((value / step) + 1e-9) * step, precision)
@classmethod
def _round_tick(cls, value: float, tick: float) -> float:
"""Round price to the nearest tick using Decimal precision."""
if tick <= 0:
return value
precision = cls._get_precision(tick)
try:
d_val = Decimal(str(value))
d_tick = Decimal(str(tick))
ticks = (d_val / d_tick).to_integral_value(rounding=ROUND_HALF_UP)
return round(float(ticks * d_tick), precision)
except (InvalidOperation, ZeroDivisionError):
return round(round(value / tick) * tick, precision)
async def _place_reduce_only_tp_detailed(
self,
symbol: str,
opposite_side: str,
qty: float,
price: float,
tp_level: str,
percent: float,
qty_step: float | None = None,
tick_size: float | None = None,
) -> tuple[dict[str, Any] | None, str | None]:
"""Place a reduce-only Limit TP order and return (order_info, error_msg)."""
sym = self._clean_symbol(symbol)
payload = {
"category": "linear",
"symbol": sym,
"side": opposite_side,
"orderType": "Limit",
"qty": self._format_num(qty, qty_step),
"price": self._format_num(price, tick_size),
"timeInForce": "GTC",
"reduceOnly": True,
"positionIdx": 0,
}
last_err: str | None = None
for attempt in range(3):
try:
resp = await self._request("POST", "/v5/order/create", json_body=payload)
return {
"tp_level": tp_level,
"percent": percent,
"status": "PLACED",
"order_id": resp.get("result", {}).get("orderId"),
"price": price,
"qty": qty,
}, None
except Exception as exc:
last_err = str(exc)
if attempt < 2 and ("position" in last_err.lower() or "110017" in last_err):
await asyncio.sleep(0.3)
continue
logger.warning("[%s] Failed to place %s limit order: %s", sym, tp_level, exc)
return None, last_err
return None, last_err
async def _place_reduce_only_tp(
self,
symbol: str,
opposite_side: str,
qty: float,
price: float,
tp_level: str,
percent: float,
qty_step: float | None = None,
tick_size: float | None = None,
) -> dict[str, Any] | None:
"""Place a reduce-only Limit TP order with transient position-settle retries."""
res, _ = await self._place_reduce_only_tp_detailed(
symbol=symbol,
opposite_side=opposite_side,
qty=qty,
price=price,
tp_level=tp_level,
percent=percent,
qty_step=qty_step,
tick_size=tick_size,
)
return res
async def reconcile_limit_tp2_once(
self,
symbol: str,
entry_order_id: str,
opposite_side: str,
tp2_qty: float,
tp2_price: float,
percent: float,
qty_step: float | None = None,
tick_size: float | None = None,
tp1_qty: float | None = None,
tp1_price: float | None = None,
tp1_percent: float | None = None,
) -> dict[str, Any]:
"""
Check a Limit entry order's fill state once and attach reduce-only split TP1/TP2 upon Filled
(including partially-filled Cancelled/Deactivated entries where cumExecQty > 0).
"""
sym = self._clean_symbol(symbol)
params = {"category": "linear", "symbol": sym, "orderId": entry_order_id}
resp = await self._request("GET", "/v5/order/realtime", params=params)
items = resp.get("result", {}).get("list", [])
if not items:
hist = await self._request("GET", "/v5/order/history", params=params)
items = hist.get("result", {}).get("list", [])
if not items:
return {"status": "PENDING", "order_status": "UNKNOWN", "tp1_order": None, "tp2_order": None}
order_status = str(items[0].get("orderStatus", ""))
try:
cum_exec = float(items[0].get("cumExecQty") or 0.0)
except (TypeError, ValueError):
cum_exec = 0.0
has_partial_cancel_fill = order_status in ("Cancelled", "Deactivated") and cum_exec > 0.0
if order_status == "Filled" or has_partial_cancel_fill:
min_qty = 0.0
try:
inst = await self.get_instrument_info(sym)
qty_step = qty_step or inst.get("qty_step")
tick_size = tick_size or inst.get("tick_size")
min_qty = float(inst.get("min_order_qty") or 0.0)
except Exception as exc:
if qty_step is None and cum_exec > 0.0:
logger.warning("[%s] Failed to load instrument info during TP reconcile: %s", sym, exc)
eff_tp1_qty = tp1_qty if (tp1_qty and tp1_qty > 0) else 0.0
eff_tp2_qty = tp2_qty
merged_to_single_tp1 = False
if cum_exec > 0.0:
d_cum = Decimal(str(cum_exec))
d_tp1 = Decimal(str(eff_tp1_qty))
d_tp2 = Decimal(str(eff_tp2_qty))
d_planned = d_tp1 + d_tp2
step_val = qty_step or 0.0
if d_planned > Decimal("0") and abs(float(d_cum - d_planned)) > (step_val * 0.5):
if d_tp1 > Decimal("0"):
raw_tp1 = float(d_cum * d_tp1 / d_planned)
eff_tp1_qty = self._round_step(raw_tp1, step_val) if step_val > 0 else raw_tp1
d_rem = max(Decimal("0"), d_cum - Decimal(str(eff_tp1_qty)))
eff_tp2_qty = self._round_step(float(d_rem), step_val) if step_val > 0 else float(d_rem)
if (min_qty > 0 and (eff_tp1_qty < min_qty or eff_tp2_qty < min_qty)) or eff_tp2_qty <= 0.0:
eff_tp1_qty = self._round_step(cum_exec, step_val) if step_val > 0 else cum_exec
eff_tp2_qty = 0.0
merged_to_single_tp1 = True
else:
capped = min(cum_exec, eff_tp2_qty)
eff_tp2_qty = self._round_step(capped, step_val) if step_val > 0 else capped
tp1_order = None
expects_tp1 = bool(eff_tp1_qty > 0.0 and tp1_price and tp1_price > 0.0)
if expects_tp1:
eff_tp1_pct = 100.0 if merged_to_single_tp1 else (tp1_percent if tp1_percent is not None else max(0.0, round(100.0 - percent, 1)))
tp1_order = await self._place_reduce_only_tp(
symbol=sym,
opposite_side=opposite_side,
qty=eff_tp1_qty,
price=tp1_price,
tp_level="TP1",
percent=eff_tp1_pct,
qty_step=qty_step,
tick_size=tick_size,
)
tp2_order = None
expects_tp2 = bool(eff_tp2_qty > 0.0)
if expects_tp2:
tp2_order = await self._place_reduce_only_tp(
symbol=sym,
opposite_side=opposite_side,
qty=eff_tp2_qty,
price=tp2_price,
tp_level="TP2",
percent=percent,
qty_step=qty_step,
tick_size=tick_size,
)
if (not expects_tp1 or tp1_order) and (not expects_tp2 or tp2_order) and (tp1_order or tp2_order):
status = "PLACED"
elif tp1_order or tp2_order:
status = "PARTIAL"
else:
status = "FAILED"
return {
"status": status,
"order_status": order_status,
"tp1_order": tp1_order,
"tp2_order": tp2_order,
}
if order_status in ("Cancelled", "Rejected", "Deactivated"):
return {
"status": f"ENTRY_{order_status.upper()}",
"order_status": order_status,
"tp1_order": None,
"tp2_order": None,
}
return {"status": "PENDING", "order_status": order_status, "tp1_order": None, "tp2_order": None}
async def get_open_position(self, symbol: str) -> dict[str, Any] | None:
"""Fetch active Bybit linear position for symbol (returns None if size == 0)."""
sym = self._clean_symbol(symbol)
resp = await self._request("GET", "/v5/position/list", params={"category": "linear", "symbol": sym})
items = resp.get("result", {}).get("list", [])
for item in items:
try:
if float(item.get("size") or 0.0) > 0.0:
return item
except (TypeError, ValueError):
continue
return None
async def move_sl_to_breakeven(
self,
symbol: str,
side: str,
avg_entry_price: float,
) -> dict[str, Any]:
"""
Move position Stop Loss to avg_entry_price ± 6 bps fee-buffer rounded to tick_size.
"""
sym = self._clean_symbol(symbol)
inst = await self.get_instrument_info(sym)
tick_size = inst["tick_size"]
is_buy = side.upper() in ("BUY", "LONG")
raw_be_sl = float(avg_entry_price) * (1.0 + 0.0006) if is_buy else float(avg_entry_price) * (1.0 - 0.0006)
rounded_be_sl = self._round_tick(raw_be_sl, tick_size)
payload = {
"category": "linear",
"symbol": sym,
"positionIdx": 0,
"stopLoss": self._format_num(rounded_be_sl, tick_size),
"slTriggerBy": "MarkPrice",
}
await self._request("POST", "/v5/position/trading-stop", json_body=payload)
return {
"success": True,
"symbol": sym,
"breakeven_sl": rounded_be_sl,
"raw_be_sl": raw_be_sl,
}
# -------------------------------------------------------------------------
# Core Setup Execution
# -------------------------------------------------------------------------
async def execute_trade_setup(
self,
symbol: str,
side: str, # "Buy" (Long) | "Sell" (Short)
order_type: str, # "Market" | "Limit"
margin_usd: float, # Nominal margin to risk, e.g. 50.0 USD
leverage: int, # Leverage, e.g. 3
stop_loss: float, # Mandatory Stop Loss price
take_profit_1: float, # TP1 price
take_profit_2: float | None = None, # Optional TP2 price
tp1_percent: float = 50.0, # Custom % of position qty for TP1 (10.0 to 100.0)
entry_price: float | None = None, # Price if Limit order
mark_price: float | None = None, # Reference price for qty calculation
auto_breakeven: bool = False, # Move SL to breakeven + 6 bps after TP1 fills
) -> dict[str, Any]:
"""
Execute trade setup on Bybit V5 with bracket Stop Loss and custom split TP1/TP2.
"""
sym = self._clean_symbol(symbol)
side_up = (side or "").strip().upper()
if side_up in ("BUY", "LONG"):
side_norm = "Buy"
elif side_up in ("SELL", "SHORT"):
side_norm = "Sell"
else:
raise ValueError(f"Side tidak valid: '{side}'. Gunakan Buy/Long atau Sell/Short.")
ot_up = (order_type or "").strip().upper()
if ot_up not in ("MARKET", "LIMIT"):
raise ValueError(f"Order type tidak valid: '{order_type}'. Gunakan Market atau Limit.")
if margin_usd <= 0:
raise ValueError("Margin USD harus lebih besar dari 0.")
opposite_side = "Sell" if side_norm == "Buy" else "Buy"
# 1. Fetch instrument precision filters
inst = await self.get_instrument_info(sym)
qty_step = inst["qty_step"]
min_qty = inst["min_order_qty"]
tick_size = inst["tick_size"]
lev = max(1, min(int(leverage), 50))
# 2. Determine base calculation price (and round Limit entry to tick_size BEFORE checks)
calc_price = entry_price if (ot_up == "LIMIT" and entry_price and entry_price > 0) else mark_price
if not calc_price or calc_price <= 0:
# Fallback: fetch current ticker price
ticker_data = await self._request("GET", "/v5/market/tickers", {"category": "linear", "symbol": sym})
ticker_list = ticker_data.get("result", {}).get("list") or []
calc_price = float((ticker_list[0] if ticker_list else {}).get("lastPrice") or 0.0)
if calc_price <= 0:
raise ValueError(f"Tidak dapat menentukan harga acuan untuk {sym}.")
if ot_up == "LIMIT":
calc_price = self._round_tick(calc_price, tick_size)
# 3. Calculate total contract quantity
notional_usd = margin_usd * lev
raw_total_qty = notional_usd / calc_price
total_qty = self._round_step(raw_total_qty, qty_step)
if total_qty < min_qty:
raise ValueError(
f"Ukuran order terlalu kecil ({total_qty} {inst['base_coin']}). "
f"Minimal order untuk {sym} adalah {min_qty} {inst['base_coin']} "
f"(Naikkan margin atau leverage minimal ~${(min_qty * calc_price) / lev:.1f} USD)."
)
# 4. Format prices according to tickSize & validate directional brackets BEFORE changing leverage
rounded_sl = self._round_tick(stop_loss, tick_size)
rounded_tp1 = self._round_tick(take_profit_1, tick_size)
rounded_tp2 = self._round_tick(take_profit_2, tick_size) if (take_profit_2 and take_profit_2 > 0) else None
if side_norm == "Buy":
if rounded_sl >= calc_price:
raise ValueError(f"Stop Loss (${rounded_sl}) harus lebih rendah dari harga Entry (${calc_price}) untuk posisi Long.")
if rounded_tp1 <= calc_price:
raise ValueError(f"Take Profit 1 (${rounded_tp1}) harus lebih tinggi dari harga Entry (${calc_price}) untuk posisi Long.")
if rounded_tp2 and rounded_tp2 <= rounded_tp1:
raise ValueError(f"Take Profit 2 (${rounded_tp2}) harus lebih tinggi dari TP1 (${rounded_tp1}) untuk posisi Long.")
else:
if rounded_sl <= calc_price:
raise ValueError(f"Stop Loss (${rounded_sl}) harus lebih tinggi dari harga Entry (${calc_price}) untuk posisi Short.")
if rounded_tp1 >= calc_price:
raise ValueError(f"Take Profit 1 (${rounded_tp1}) harus lebih rendah dari harga Entry (${calc_price}) untuk posisi Short.")
if rounded_tp2 and rounded_tp2 >= rounded_tp1:
raise ValueError(f"Take Profit 2 (${rounded_tp2}) harus lebih rendah dari TP1 (${rounded_tp1}) untuk posisi Short.")
# 5. Configure leverage on exchange only after all parameter & bracket checks pass
await self.set_leverage(sym, lev)
# 6. Build and submit primary entry order
order_payload: dict[str, Any] = {
"category": "linear",
"symbol": sym,
"side": side_norm,
"orderType": "Market" if ot_up == "MARKET" else "Limit",
"qty": self._format_num(total_qty, qty_step),
"timeInForce": "GTC",
"positionIdx": 0, # One-way mode
"stopLoss": self._format_num(rounded_sl, tick_size),
"slTriggerBy": "MarkPrice",
}
# Calculate TP split quantities using Decimal subtraction to prevent IEEE 754 precision loss
tp1_pct = max(10.0, min(float(tp1_percent), 100.0))
if tp1_pct >= 99.0 or not rounded_tp2:
tp1_qty = total_qty
tp2_qty = 0.0
else:
raw_tp1_qty = total_qty * (tp1_pct / 100.0)
tp1_qty = self._round_step(raw_tp1_qty, qty_step)
raw_rem_qty = float(Decimal(str(total_qty)) - Decimal(str(tp1_qty)))
tp2_qty = self._round_step(max(0.0, raw_rem_qty), qty_step)
if tp1_qty < min_qty or tp2_qty < min_qty:
tp1_qty = total_qty
tp2_qty = 0.0
# For Limit orders: attach takeProfit natively ONLY when closing 100% at TP1.
# On split TP1+TP2, Bybit POST /v5/order/create does not support tpSize (tpslMode="Partial"
# creates a TP matching 100% of filled qty), so split reduce-only TP1/TP2 are placed post-fill.
if ot_up == "LIMIT":
order_payload["price"] = self._format_num(calc_price, tick_size)
if tp2_qty <= 0 or not rounded_tp2:
order_payload["takeProfit"] = self._format_num(rounded_tp1, tick_size)
order_payload["tpTriggerBy"] = "MarkPrice"
logger.info("[%s] Sending Bybit Entry order: %s", sym, order_payload)
entry_resp = await self._request("POST", "/v5/order/create", json_body=order_payload)
entry_order_id = entry_resp.get("result", {}).get("orderId", "")
# 7. Split Take Profit Orders
tp1_orders_info = []
if ot_up == "LIMIT":
if tp2_qty <= 0 or not rounded_tp2:
# 100% single TP bound directly to the Limit order upon fill
tp1_orders_info.append({
"tp_level": "TP1",
"percent": 100.0,
"status": "BOUND_TO_ENTRY",
"order_id": f"bound-{entry_order_id}",
"price": rounded_tp1,
"qty": tp1_qty,
"note": "Terkait langsung ke Limit Order (aktif otomatis menutup 100% saat terisi)",
})
else:
is_serverless = bool(os.getenv("VERCEL") or os.getenv("NOW_REGION"))
if is_serverless:
tp1_orders_info.append({
"tp_level": "TP1",
"percent": tp1_pct,
"status": "STATELESS_MANUAL_TP1",
"order_id": None,
"price": rounded_tp1,
"qty": tp1_qty,
"opposite_side": opposite_side,
"note": "Serverless stateless: Entry Limit & SL terpasang; pasang TP1 reduce-only manual setelah Limit entry terisi.",
})
tp1_orders_info.append({
"tp_level": "TP2",
"percent": round(100.0 - tp1_pct, 1),
"status": "STATELESS_MANUAL_TP2",
"order_id": None,
"price": rounded_tp2,
"qty": tp2_qty,
"opposite_side": opposite_side,
"note": "Serverless stateless: Entry Limit & SL terpasang; pasang TP2 reduce-only manual setelah Limit entry terisi.",
})
else:
tp1_orders_info.append({
"tp_level": "TP1",
"percent": tp1_pct,
"status": "WATCHING_FILL",
"order_id": None,
"price": rounded_tp1,
"qty": tp1_qty,
"opposite_side": opposite_side,
"note": "Watcher background aktif: TP1 reduce-only dipasang otomatis saat Limit Order terisi.",
})
tp1_orders_info.append({
"tp_level": "TP2",
"percent": round(100.0 - tp1_pct, 1),
"status": "WATCHING_FILL",
"order_id": None,
"price": rounded_tp2,
"qty": tp2_qty,
"opposite_side": opposite_side,
"note": "Watcher background aktif: TP2 reduce-only dipasang otomatis saat Limit Order terisi.",
})
else:
# MARKET ORDER: Wait briefly to let Bybit matching engine register filled position
await asyncio.sleep(0.3)
if tp1_pct >= 99.0 or not rounded_tp2 or tp2_qty == 0.0:
placed, err_tp1 = await self._place_reduce_only_tp_detailed(
symbol=sym,
opposite_side=opposite_side,
qty=tp1_qty,
price=rounded_tp1,
tp_level="TP1",
percent=100.0,
qty_step=qty_step,
tick_size=tick_size,
)
if placed:
tp1_orders_info.append(placed)
else:
tp1_orders_info.append({
"tp_level": "TP1",
"percent": 100.0,
"status": "FAILED",
"order_id": None,
"price": rounded_tp1,
"qty": tp1_qty,
"error": err_tp1,
"note": "Gagal memasang reduce-only TP1; periksa & pasang TP manual.",
})
else:
if tp1_qty >= min_qty:
placed_tp1, err_tp1 = await self._place_reduce_only_tp_detailed(
symbol=sym,
opposite_side=opposite_side,
qty=tp1_qty,
price=rounded_tp1,
tp_level="TP1",
percent=tp1_pct,
qty_step=qty_step,
tick_size=tick_size,
)
if placed_tp1:
tp1_orders_info.append(placed_tp1)
else:
tp1_orders_info.append({
"tp_level": "TP1",
"percent": tp1_pct,
"status": "FAILED",
"order_id": None,
"price": rounded_tp1,
"qty": tp1_qty,
"error": err_tp1,
"note": "Gagal memasang reduce-only TP1; periksa & pasang TP manual.",
})
if tp2_qty >= min_qty and rounded_tp2:
tp2_pct_val = round(100.0 - tp1_pct, 1)
placed_tp2, err_tp2 = await self._place_reduce_only_tp_detailed(
symbol=sym,
opposite_side=opposite_side,
qty=tp2_qty,
price=rounded_tp2,
tp_level="TP2",
percent=tp2_pct_val,
qty_step=qty_step,
tick_size=tick_size,
)
if placed_tp2:
tp1_orders_info.append(placed_tp2)
else:
tp1_orders_info.append({
"tp_level": "TP2",
"percent": tp2_pct_val,
"status": "FAILED",
"order_id": None,
"price": rounded_tp2,
"qty": tp2_qty,
"error": err_tp2,
"note": "Gagal memasang reduce-only TP2; periksa & pasang TP manual.",
})
return {
"success": True,
"symbol": sym,
"side": side_norm,
"order_type": ot_up,
"entry_price": calc_price,
"margin_usd": margin_usd,
"leverage": lev,
"notional_usd": notional_usd,
"total_qty": total_qty,
"tp1_qty": tp1_qty,
"tp2_qty": tp2_qty,
"entry_order_id": entry_order_id,
"stop_loss": rounded_sl,
"tp_orders": tp1_orders_info,
"auto_breakeven": bool(auto_breakeven),
"mode": self.mode,
"timestamp": time.time(),
}
async def watch_position_tp1_breakeven(
api_key: str,
api_secret: str,
mode: str,
proxy_url: str | None,
symbol: str,
side: str,
total_qty: float,
tp1_qty: float,
tp1_order_id: str | None = None,
poll_interval: float = 10.0,
max_polls: int = 4320,
) -> dict[str, Any]:
"""
Poll TP1 fill status (up to 12h by default) and automatically move position SL to breakeven ± 6 bps.
Supports both explicit reduce-only TP1 order IDs (Market entry) and bound Limit TP1 triggers (10%-99% split).
"""
if not tp1_order_id:
return {"status": "NO_TP1_ORDER", "breakeven_sl": None}
watcher = BybitExecutor(api_key=api_key, api_secret=api_secret, mode=mode, proxy_url=proxy_url)
sym = BybitExecutor._clean_symbol(symbol)
is_bound = str(tp1_order_id).startswith("bound-")
threshold_size = max(0.0, float(total_qty) - (0.5 * float(tp1_qty)))
try:
for _ in range(max_polls):
try:
pos = await watcher.get_open_position(sym)
if not pos or float(pos.get("size") or 0.0) <= 0.0:
return {"status": "POSITION_CLOSED", "breakeven_sl": None}
pos_size = float(pos.get("size") or 0.0)
avg_px = float(pos.get("avgPrice") or 0.0)
pos_side = str(pos.get("side") or side)
tp1_filled = False
if not is_bound:
params = {"category": "linear", "symbol": sym, "orderId": str(tp1_order_id)}
resp = await watcher._request("GET", "/v5/order/realtime", params=params)
items = resp.get("result", {}).get("list", [])
if not items:
hist = await watcher._request("GET", "/v5/order/history", params=params)
items = hist.get("result", {}).get("list", [])
if items:
st = str(items[0].get("orderStatus", ""))
if st == "Filled":
tp1_filled = True
elif st in ("Cancelled", "Rejected", "Deactivated"):
return {"status": f"TP1_{st.upper()}", "breakeven_sl": None}
else:
if pos_size <= threshold_size and float(tp1_qty) > 0.0:
tp1_filled = True
if tp1_filled and avg_px > 0.0:
be_res = await watcher.move_sl_to_breakeven(sym, side=pos_side, avg_entry_price=avg_px)
logger.info("[%s] Auto-Breakeven SL armed at %s", sym, be_res.get("breakeven_sl"))
return {"status": "BREAKEVEN_ARMED", "breakeven_sl": be_res.get("breakeven_sl")}
except Exception as exc:
logger.warning("[%s] TP1 breakeven watcher poll error: %s", sym, exc)
await asyncio.sleep(poll_interval)
return {"status": "TIMEOUT", "breakeven_sl": None}
finally:
await watcher.close()
async def watch_limit_entry_and_place_tp2(
api_key: str,
api_secret: str,
mode: str,
proxy_url: str | None,
symbol: str,
entry_order_id: str,
opposite_side: str,
tp2_qty: float,
tp2_price: float,
percent: float,
poll_interval: float = 10.0,
max_polls: int = 4320,
auto_breakeven: bool = False,
side: str = "Buy",
total_qty: float = 0.0,
tp1_qty: float = 0.0,
tp1_order_id: str | None = None,
tp1_price: float | None = None,
tp1_percent: float | None = None,
) -> dict[str, Any]:
"""
Isolated background watcher that opens its own short-lived BybitExecutor,
polls Limit entry fill status, attaches reduce-only TP1/TP2 limit orders once Filled,
and optionally chains into watch_position_tp1_breakeven.
"""
watcher = BybitExecutor(api_key=api_key, api_secret=api_secret, mode=mode, proxy_url=proxy_url)
res: dict[str, Any] = {"status": "TIMEOUT", "tp1_order": None, "tp2_order": None}
try:
for _ in range(max_polls):
try:
res = await watcher.reconcile_limit_tp2_once(
symbol=symbol,
entry_order_id=entry_order_id,
opposite_side=opposite_side,
tp2_qty=tp2_qty,
tp2_price=tp2_price,
percent=percent,
tp1_qty=tp1_qty if tp1_qty > 0 else None,
tp1_price=tp1_price,
tp1_percent=tp1_percent,
)
if res["status"] != "PENDING":
logger.info("[%s] Limit TP1/TP2 watcher finished for %s: %s", symbol, entry_order_id, res["status"])
break
except Exception as exc:
logger.warning("[%s] Limit TP2 poll error for %s: %s", symbol, entry_order_id, exc)
await asyncio.sleep(poll_interval)
finally:
await watcher.close()
effective_tp1_order_id = (res.get("tp1_order") or {}).get("order_id") or tp1_order_id
if res.get("status") in ("PLACED", "PARTIAL") and auto_breakeven and tp2_qty > 0 and effective_tp1_order_id:
be_res = await watch_position_tp1_breakeven(
api_key=api_key,
api_secret=api_secret,
mode=mode,
proxy_url=proxy_url,
symbol=symbol,
side=side,
total_qty=total_qty,
tp1_qty=tp1_qty,
tp1_order_id=effective_tp1_order_id,
)
res["breakeven_result"] = be_res
return res