Spaces:
Sleeping
Sleeping
File size: 38,902 Bytes
86abcb2 740fcec 86abcb2 740fcec 80df99b 86abcb2 740fcec 86abcb2 740fcec 86abcb2 80df99b 86abcb2 80df99b 86abcb2 80df99b 86abcb2 cc3aa02 86abcb2 80df99b cc3aa02 86abcb2 cc3aa02 48f60d7 cc3aa02 86abcb2 80df99b 86abcb2 80df99b 86abcb2 80df99b 86abcb2 80df99b 86abcb2 80df99b 86abcb2 80df99b 86abcb2 80df99b 86abcb2 48f60d7 740fcec 80df99b 48f60d7 80df99b 740fcec 80df99b 740fcec 48f60d7 740fcec 48f60d7 740fcec 48f60d7 740fcec 48f60d7 740fcec 80df99b 075133b 740fcec 48f60d7 740fcec 80df99b 740fcec 075133b 740fcec 48f60d7 075133b 48f60d7 075133b 48f60d7 075133b 48f60d7 075133b 48f60d7 075133b 48f60d7 075133b 48f60d7 075133b 48f60d7 075133b 740fcec 075133b 740fcec 075133b 740fcec 075133b 740fcec 075133b 740fcec 80df99b 740fcec 80df99b 740fcec 80df99b 740fcec 86abcb2 740fcec 86abcb2 80df99b 48f60d7 86abcb2 48f60d7 86abcb2 80df99b 86abcb2 48f60d7 86abcb2 48f60d7 86abcb2 48f60d7 86abcb2 abeb2e6 48f60d7 86abcb2 48f60d7 80df99b 86abcb2 80df99b 86abcb2 80df99b 14cdea1 80df99b 14cdea1 075133b 48f60d7 075133b 86abcb2 14cdea1 86abcb2 48f60d7 075133b 740fcec 075133b 740fcec 075133b 740fcec 075133b 740fcec 14cdea1 740fcec abeb2e6 14cdea1 48f60d7 740fcec 80df99b 740fcec 48f60d7 14cdea1 48f60d7 740fcec 80df99b 740fcec 48f60d7 14cdea1 48f60d7 740fcec 48f60d7 80df99b 740fcec 48f60d7 86abcb2 48f60d7 86abcb2 740fcec 86abcb2 740fcec 86abcb2 740fcec 075133b 740fcec 80df99b 075133b 740fcec 075133b 740fcec 075133b 740fcec 075133b 740fcec 075133b 740fcec 075133b 740fcec 075133b 740fcec 075133b 740fcec 075133b 740fcec 075133b 740fcec | 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 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 | """
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
|