Spaces:
Sleeping
Sleeping
File size: 29,331 Bytes
86abcb2 bbdcd47 86abcb2 abeb2e6 86abcb2 abeb2e6 740fcec 86abcb2 740fcec cc3aa02 740fcec cc3aa02 740fcec cc3aa02 740fcec cc3aa02 740fcec cc3aa02 e748eb0 8996291 bbdcd47 48f60d7 bbdcd47 48f60d7 bbdcd47 48f60d7 bbdcd47 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 | """
Unit and regression tests for Bybit V5 Execution Engine and /api/execution endpoints.
"""
import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "backend")))
import pytest
from fastapi.testclient import TestClient
from unittest.mock import AsyncMock, MagicMock, patch
from main import app
from engine.execution.bybit_executor import BybitExecutor
client = TestClient(app)
@pytest.fixture
def anyio_backend():
return 'asyncio'
def test_bybit_signature_generation():
"""Verify HMAC-SHA256 signature algorithm against expected hash."""
executor = BybitExecutor(api_key="test_key", api_secret="test_secret", mode="demo")
timestamp = "1672531199000"
payload = '{"category":"linear","symbol":"BTCUSDT"}'
sig = executor._generate_signature(timestamp, payload)
assert isinstance(sig, str)
assert len(sig) == 64 # SHA256 hex digest is 64 characters
# Signature should be deterministic
sig2 = executor._generate_signature(timestamp, payload)
assert sig == sig2
def test_bybit_rounding_step_and_tick():
"""Verify exchange step-size and tick-size rounding logic."""
# Step size: floor to nearest step
assert BybitExecutor._round_step(12.3456, 0.01) == 12.34
assert BybitExecutor._round_step(12.3456, 0.1) == 12.3
assert BybitExecutor._round_step(12.9, 1.0) == 12.0
assert BybitExecutor._round_step(0.0039, 0.001) == 0.003
# Tick size: round to nearest tick
assert BybitExecutor._round_tick(0.18567, 0.0001) == 0.1857
assert BybitExecutor._round_tick(0.18562, 0.0001) == 0.1856
assert BybitExecutor._round_tick(64321.4, 0.5) == 64321.5
@pytest.mark.anyio
async def test_bybit_execute_split_tp_logic():
"""Verify custom split TP1/TP2 allocation and calculation."""
executor = BybitExecutor(api_key="test_key", api_secret="test_secret", mode="demo")
# Mock get_instrument_info and _request
with patch.object(executor, "get_instrument_info", new_callable=AsyncMock) as mock_info, \
patch.object(executor, "set_leverage", new_callable=AsyncMock) as mock_lev, \
patch.object(executor, "_request", new_callable=AsyncMock) as mock_req:
mock_info.return_value = {
"symbol": "DOGEUSDT",
"base_coin": "DOGE",
"quote_coin": "USDT",
"qty_step": 1.0,
"min_order_qty": 1.0,
"max_order_qty": 1000000.0,
"tick_size": 0.0001,
"min_price": 0.0001,
"max_price": 100.0,
}
mock_lev.return_value = True
mock_req.return_value = {"retCode": 0, "result": {"orderId": "mock_order_123"}}
# Test 60% TP1 split
res = await executor.execute_trade_setup(
symbol="DOGEUSDT",
side="Buy",
order_type="Market",
margin_usd=50.0,
leverage=3,
stop_loss=0.1800,
take_profit_1=0.1940,
take_profit_2=0.2050,
tp1_percent=60.0,
mark_price=0.1850,
)
assert res["success"] is True
assert res["symbol"] == "DOGEUSDT"
assert res["leverage"] == 3
# notional = 50 * 3 = 150 USD. qty = 150 / 0.1850 = 810.8 -> 810.0
assert res["total_qty"] == 810.0
assert len(res["tp_orders"]) == 2
# TP1 = 60% of 810 = 486.0
assert res["tp_orders"][0]["tp_level"] == "TP1"
assert res["tp_orders"][0]["qty"] == 486.0
# TP2 = 40% of 810 = 324.0
assert res["tp_orders"][1]["tp_level"] == "TP2"
assert res["tp_orders"][1]["qty"] == 324.0
await executor.close()
@pytest.mark.anyio
async def test_bybit_directional_validation_and_tp2_merge():
"""Verify that inverted SL/TP are caught and small TP2 merge works."""
executor = BybitExecutor(api_key="test_key", api_secret="test_secret", mode="demo")
with patch.object(executor, "get_instrument_info", new_callable=AsyncMock) as mock_info, \
patch.object(executor, "set_leverage", new_callable=AsyncMock) as mock_lev, \
patch.object(executor, "_request", new_callable=AsyncMock) as mock_req:
mock_info.return_value = {
"symbol": "BTCUSDT",
"base_coin": "BTC",
"quote_coin": "USDT",
"qty_step": 0.001,
"min_order_qty": 0.001,
"max_order_qty": 100.0,
"tick_size": 0.1,
"min_price": 0.1,
"max_price": 1000000.0,
}
mock_lev.return_value = True
mock_req.return_value = {"retCode": 0, "result": {"orderId": "mock_btc_123"}}
# 1. Inverted Long SL (SL > entry) must raise ValueError
with pytest.raises(ValueError, match="harus lebih rendah dari harga Entry"):
await executor.execute_trade_setup(
symbol="BTCUSDT",
side="Buy",
order_type="Market",
margin_usd=100.0,
leverage=2,
stop_loss=65000.0, # Invalid: above entry 60000.0
take_profit_1=70000.0,
mark_price=60000.0,
)
# 2. Inverted Short SL (SL < entry) must raise ValueError
with pytest.raises(ValueError, match="harus lebih tinggi dari harga Entry"):
await executor.execute_trade_setup(
symbol="BTCUSDT",
side="Sell",
order_type="Market",
margin_usd=100.0,
leverage=2,
stop_loss=55000.0, # Invalid: below entry 60000.0
take_profit_1=50000.0,
mark_price=60000.0,
)
# 3. TP2 merge when remaining qty is below min_order_qty
# Margin 30, Lev 2 = 60 USD / 60000 = 0.001 BTC (exactly min_order_qty)
# 50% split would be 0.0005 BTC (< 0.001 min_qty), so 100% must be merged to TP1!
res_merge = await executor.execute_trade_setup(
symbol="BTCUSDT",
side="Buy",
order_type="Market",
margin_usd=30.0,
leverage=2,
stop_loss=58000.0,
take_profit_1=65000.0,
take_profit_2=70000.0,
tp1_percent=50.0,
mark_price=60000.0,
)
assert res_merge["success"] is True
assert len(res_merge["tp_orders"]) == 1
assert res_merge["tp_orders"][0]["tp_level"] == "TP1"
assert res_merge["tp_orders"][0]["qty"] == 0.001
assert res_merge["tp_orders"][0]["percent"] == 100.0
await executor.close()
def test_execution_settings_endpoint(monkeypatch):
"""Verify /api/execution/bybit/settings endpoint returns stateless config JSON when authorized."""
import security
monkeypatch.setattr(security, "PERPS_API_TOKEN", "exec-test-token")
resp = client.get(
"/api/execution/bybit/settings",
headers={"Authorization": "Bearer exec-test-token"},
)
assert resp.status_code == 200
data = resp.json()
assert "configured" in data
assert "mode" in data
assert data.get("stateless") is True
@pytest.mark.anyio
async def test_execution_order_with_equity_percentage(monkeypatch):
"""Verify backend calculates margin_usd from margin_percent and account equity statelessly."""
import security
monkeypatch.setattr(security, "PERPS_API_TOKEN", "exec-test-token")
with patch.object(BybitExecutor, "get_wallet_balance", new_callable=AsyncMock) as mock_bal, \
patch.object(BybitExecutor, "execute_trade_setup", new_callable=AsyncMock) as mock_exec, \
patch("routers.execution.async_create_journal_entry", new_callable=AsyncMock) as mock_j:
mock_bal.return_value = {
"coin": "USDT",
"available_balance": 1500.0,
"total_equity": 2000.0,
"mode": "demo",
}
mock_exec.return_value = {
"success": True,
"symbol": "BTCUSDT",
"mode": "demo",
"entry_order_id": "test_order_999",
"margin_usd": 100.0,
}
mock_j.return_value = {"id": "j_123"}
# Call endpoint with margin_percent=5.0 (5% of 2000 = 100.0 USD) and stateless Bybit keys
payload = {
"symbol": "BTCUSDT",
"side": "Buy",
"order_type": "Market",
"margin_usd": 0.0,
"margin_percent": 5.0,
"leverage": 3,
"stop_loss": 58000.0,
"take_profit_1": 65000.0,
"mark_price": 60000.0,
"api_key": "dummy_key",
"api_secret": "dummy_sec",
"mode": "demo",
}
resp = client.post(
"/api/execution/bybit/order",
headers={"Authorization": "Bearer exec-test-token"},
json=payload,
)
assert resp.status_code == 200
res_data = resp.json()
assert res_data["success"] is True
# Verify executor was called with calculated 100.0 USD
mock_exec.assert_called_once()
call_kwargs = mock_exec.call_args.kwargs
assert call_kwargs["margin_usd"] == 100.0
@pytest.mark.anyio
async def test_refresh_signal_endpoint_no_name_error():
"""Verify /api/signals/{symbol}/refresh executes without NameError or scope errors."""
mock_collector = AsyncMock()
mock_collector._binance.check_symbol_exists = AsyncMock(return_value=True)
mock_collector._bybit.check_symbol_exists = AsyncMock(return_value=True)
mock_collector._okx.check_symbol_exists = AsyncMock(return_value=True)
mock_collector._bitget.check_symbol_exists = AsyncMock(return_value=True)
mock_collector._hyperliquid.check_symbol_exists = AsyncMock(return_value=False)
mock_collector.collect = AsyncMock(return_value={"symbol": "BTCUSDT", "binance": {}, "bybit": {}, "okx": {}, "bitget": {}, "hyperliquid": {}})
with patch("routers.signals.async_get_pair", new_callable=AsyncMock) as mock_gp, \
patch("routers.signals._signal_engine.compute") as mock_comp, \
patch("routers.signals.async_save_signal", new_callable=AsyncMock), \
patch("routers.signals.broadcast", new_callable=AsyncMock):
mock_gp.return_value = {
"symbol": "BTCUSDT",
"on_binance": True,
"on_bybit": True,
"on_okx": False,
"on_bitget": False,
"on_hyperliquid": False,
"streak_count": 0,
}
mock_comp.return_value = {
"symbol": "BTCUSDT",
"direction": "LONG",
"conviction": 4,
"score": 10,
"active_timeframe": "1h",
"exchange_data": {},
}
# Set mock collector on app state
app.state.collector = mock_collector
resp = client.post("/api/signals/BTCUSDT/refresh")
assert resp.status_code == 200
data = resp.json()
assert data["symbol"] == "BTCUSDT"
assert data["direction"] == "LONG"
def test_ai_prompt_mode_switching():
"""Verify Damian distinguishes between conversational inquiries vs setup requests."""
from routers.ai import _build_ai_prompt
mock_signal = {
"symbol": "ERAUSDT",
"direction": "LONG",
"conviction": 7,
"active_timeframe": "4h",
"signal_data": {
"factors": {},
"exchange_data": {},
}
}
# Case 1: Conversational inquiry - user asks about sell dominance
p_conv, _ = _build_ai_prompt("ERAUSDT", mock_signal, [], custom_question="disini terlihat sell lebih mendominasi")
assert "MISI UTAMA: JAWAB LANGSUNG PERTANYAAN / OBSERVASI USER" in p_conv
assert "DILARANG KERAS MENGELUARKAN TEMPLATE SETUP LENGKAP 4 BAB" in p_conv
assert "### 🎯 4. ACTIONABLE TRADE SETUP" not in p_conv
# Case 2: Full analysis (no question)
p_full, _ = _build_ai_prompt("ERAUSDT", mock_signal, [], custom_question=None)
assert "### 🎯 4. ACTIONABLE TRADE SETUP" in p_full
assert "### 🏛️ 1. EXECUTIVE VERDICT & KONSENSUS BURSA" in p_full
# Case 3: Explicit setup request
p_setup, _ = _build_ai_prompt("ERAUSDT", mock_signal, [], custom_question="kasih gw setup scalp 15m")
assert "### 🎯 4. ACTIONABLE TRADE SETUP" in p_setup
@pytest.mark.anyio
async def test_ai_stale_signal_recollects_live_data():
"""Verify that when a signal in DB is older than 60s, /api/ai/analyze triggers live exchange collection."""
from datetime import datetime, timezone, timedelta
stale_time = (datetime.now(timezone.utc) - timedelta(seconds=120)).isoformat()
mock_stale_signal = {
"symbol": "BTCUSDT",
"direction": "LONG",
"conviction": 6,
"score": 12,
"created_at": stale_time,
"signal_data": {"exchange_data": {}},
}
mock_collector = AsyncMock()
mock_collector.collect = AsyncMock(return_value={"symbol": "BTCUSDT", "binance": {}})
app.state.collector = mock_collector
mock_resp = MagicMock()
mock_resp.status_code = 200
mock_resp.json.return_value = {
"candidates": [
{"content": {"parts": [{"text": "Analisis data live real-time."}]}}
]
}
with patch("routers.ai.async_get_latest_signal", new_callable=AsyncMock) as mock_get_signal, \
patch("database.db.async_get_pair", new_callable=AsyncMock) as mock_get_pair, \
patch("engine.signal_engine.SignalEngine.compute") as mock_comp, \
patch("database.db.async_save_signal", new_callable=AsyncMock), \
patch("httpx.AsyncClient.post", new_callable=AsyncMock, return_value=mock_resp):
mock_get_signal.return_value = mock_stale_signal
mock_get_pair.return_value = {
"symbol": "BTCUSDT",
"on_binance": True,
"on_bybit": True,
"on_okx": True,
"on_hyperliquid": True,
"on_bitget": True,
}
mock_comp.return_value = {
"symbol": "BTCUSDT",
"direction": "LONG",
"conviction": 8,
"created_at": datetime.now(timezone.utc).isoformat(),
"signal_data": {},
}
resp = client.post(
"/api/ai/analyze",
json={
"symbol": "BTCUSDT",
"question": "apakah ada volume buy baru?",
"api_key": "fake_test_key_12345",
"provider": "gemini",
},
)
assert resp.status_code == 200
# Check that collector.collect was triggered because DB signal was 120s old
mock_collector.collect.assert_called_once_with("BTCUSDT", on_binance=True, on_bybit=True, on_okx=True, on_hyperliquid=True, on_bitget=True)
@pytest.mark.anyio
async def test_limit_tp2_reconcile_and_serverless_status(monkeypatch):
"""Limit orders must replace 'pending-' stub with explicit STATELESS_MANUAL_TP2 on Vercel or WATCHING_FILL + post-fill reduceOnly TP2."""
from engine.execution.bybit_executor import BybitExecutor
async def fake_request(method: str, path: str, params=None, json_body=None):
if path == "/v5/market/instruments-info":
return {
"retCode": 0,
"result": {
"list": [{
"baseCoin": "BTC",
"lotSizeFilter": {"qtyStep": "0.001", "minOrderQty": "0.001", "maxOrderQty": "100"},
"priceFilter": {"tickSize": "0.1", "minPrice": "1", "maxPrice": "500000"},
}]
},
}
if path == "/v5/position/set-leverage":
return {"retCode": 0, "result": {}}
if path == "/v5/order/create":
return {"retCode": 0, "result": {"orderId": "tp2-real-id-999" if json_body and json_body.get("reduceOnly") else "lim-entry-123"}}
raise AssertionError(f"Unexpected call {method} {path}")
# Part A: Vercel serverless -> explicit STATELESS_MANUAL_TP2
monkeypatch.setenv("VERCEL", "1")
executor = BybitExecutor(api_key="k", api_secret="s", mode="demo")
executor._request = fake_request # type: ignore[method-assign]
res_serverless = await executor.execute_trade_setup(
symbol="BTCUSDT",
side="Buy",
order_type="Limit",
margin_usd=100.0,
leverage=5,
stop_loss=95.0,
take_profit_1=105.0,
take_profit_2=110.0,
tp1_percent=50.0,
entry_price=99.0,
mark_price=100.0,
)
tp2_sv = [t for t in res_serverless["tp_orders"] if t["tp_level"] == "TP2"][0]
assert tp2_sv["status"] == "STATELESS_MANUAL_TP2"
assert tp2_sv["order_id"] is None
# Part B: Stateful -> WATCHING_FILL then reconcile_limit_tp2_once places reduceOnly TP2 after Filled
monkeypatch.delenv("VERCEL", raising=False)
res_stateful = await executor.execute_trade_setup(
symbol="BTCUSDT",
side="Buy",
order_type="Limit",
margin_usd=100.0,
leverage=5,
stop_loss=95.0,
take_profit_1=105.0,
take_profit_2=110.0,
tp1_percent=50.0,
entry_price=99.0,
mark_price=100.0,
)
tp2_st = [t for t in res_stateful["tp_orders"] if t["tp_level"] == "TP2"][0]
assert tp2_st["status"] == "WATCHING_FILL"
assert tp2_st["order_id"] is None
order_statuses = iter(["New", "Filled"])
placed_payloads: list[dict] = []
async def fake_reconcile_request(method: str, path: str, params=None, json_body=None):
if path == "/v5/order/realtime":
return {"retCode": 0, "result": {"list": [{"orderId": "lim-entry-123", "orderStatus": next(order_statuses)}]}}
if path == "/v5/order/create":
placed_payloads.append(dict(json_body or {}))
return {"retCode": 0, "result": {"orderId": "tp2-real-id-999"}}
raise AssertionError(f"Unexpected call {method} {path}")
executor._request = fake_reconcile_request # type: ignore[method-assign]
r1 = await executor.reconcile_limit_tp2_once("BTCUSDT", "lim-entry-123", "Sell", tp2_st["qty"], 110.0, 50.0)
assert r1["status"] == "PENDING"
assert placed_payloads == []
r2 = await executor.reconcile_limit_tp2_once("BTCUSDT", "lim-entry-123", "Sell", tp2_st["qty"], 110.0, 50.0)
assert r2["status"] == "PLACED"
assert r2["tp2_order"]["order_id"] == "tp2-real-id-999"
assert placed_payloads[0]["reduceOnly"] is True
assert placed_payloads[0]["price"] == "110.0"
await executor.close()
@pytest.mark.anyio
async def test_execution_router_schedules_tp2_watcher_when_stateful(monkeypatch):
"""Router schedules background TP2 watcher on stateful servers but omits it on Vercel."""
import security
monkeypatch.setattr(security, "PERPS_API_TOKEN", "test-exec-token")
monkeypatch.delenv("VERCEL", raising=False)
mock_exec_result = {
"success": True,
"symbol": "BTCUSDT",
"side": "Buy",
"order_type": "LIMIT",
"margin_usd": 100.0,
"leverage": 5,
"notional_usd": 500.0,
"total_qty": 5.0,
"entry_order_id": "lim-999",
"stop_loss": 95.0,
"tp_orders": [
{"tp_level": "TP1", "percent": 50.0, "order_id": "bound-lim-999", "price": 105.0, "qty": 2.5},
{"tp_level": "TP2", "percent": 50.0, "status": "WATCHING_FILL", "order_id": None, "price": 110.0, "qty": 2.5, "opposite_side": "Sell"},
],
"mode": "demo",
"timestamp": 1.0,
}
payload = {
"symbol": "BTCUSDT",
"side": "Buy",
"order_type": "Limit",
"margin_usd": 100.0,
"leverage": 5,
"stop_loss": 95.0,
"take_profit_1": 105.0,
"take_profit_2": 110.0,
"tp1_percent": 50.0,
"entry_price": 99.0,
"log_to_journal": False,
}
headers = {
"Authorization": "Bearer test-exec-token",
"X-Bybit-Api-Key": "bybit-k",
"X-Bybit-Api-Secret": "bybit-s",
"X-Bybit-Mode": "demo",
}
watcher_mock = AsyncMock(return_value={"status": "PLACED"})
with patch("routers.execution.BybitExecutor.execute_trade_setup", new_callable=AsyncMock, return_value=dict(mock_exec_result)), \
patch("routers.execution.BybitExecutor.close", new_callable=AsyncMock), \
patch("routers.execution.watch_limit_entry_and_place_tp2", watcher_mock):
resp = client.post("/api/execution/bybit/order", json=payload, headers=headers)
assert resp.status_code == 200
assert resp.json()["execution"]["tp2_watcher_scheduled"] is True
assert watcher_mock.called
# On Vercel serverless, watcher must NOT be scheduled even if a Limit TP2 spec exists
monkeypatch.setenv("VERCEL", "1")
watcher_mock_sv = AsyncMock(return_value={"status": "PLACED"})
with patch("routers.execution.BybitExecutor.execute_trade_setup", new_callable=AsyncMock, return_value=dict(mock_exec_result)), \
patch("routers.execution.BybitExecutor.close", new_callable=AsyncMock), \
patch("routers.execution.watch_limit_entry_and_place_tp2", watcher_mock_sv):
resp_sv = client.post("/api/execution/bybit/order", json=payload, headers=headers)
assert resp_sv.status_code == 200
assert resp_sv.json()["execution"]["tp2_watcher_scheduled"] is False
assert not watcher_mock_sv.called
def test_bybit_executor_get_open_position_and_move_sl_to_breakeven():
"""get_open_position parses active linear position; move_sl_to_breakeven rounds avgPrice ± 6 bps to tick_size."""
import asyncio
from engine.execution.bybit_executor import BybitExecutor
async def _run():
ex = BybitExecutor(api_key="k", api_secret="s", mode="demo")
calls = []
async def _fake_req(method, endpoint, params=None, json_body=None):
calls.append((method, endpoint, params, json_body))
if endpoint == "/v5/position/list":
return {
"retCode": 0,
"result": {"list": [{"symbol": "BTCUSDT", "side": "Buy", "size": "2.5", "avgPrice": "100.0", "stopLoss": "95.0"}]},
}
if endpoint == "/v5/market/instruments-info":
return {
"retCode": 0,
"result": {
"list": [{
"symbol": "BTCUSDT",
"baseCoin": "BTC",
"lotSizeFilter": {"qtyStep": "0.01", "minOrderQty": "0.01"},
"priceFilter": {"tickSize": "0.05"},
}]
},
}
if endpoint == "/v5/position/trading-stop":
return {"retCode": 0, "result": {}}
return {"retCode": 0, "result": {}}
ex._request = _fake_req
pos = await ex.get_open_position("BTCUSDT")
assert pos is not None
assert float(pos["size"]) == 2.5
be_res = await ex.move_sl_to_breakeven("BTCUSDT", side="Buy", avg_entry_price=100.0)
# 100.0 * 1.0006 = 100.06 -> rounded to tickSize 0.05 -> 100.05
assert be_res["breakeven_sl"] == 100.05
stop_call = [c for c in calls if c[1] == "/v5/position/trading-stop"][0]
assert stop_call[3]["stopLoss"] == "100.05"
assert stop_call[3]["slTriggerBy"] == "MarkPrice"
await ex.close()
asyncio.run(_run())
def test_watch_position_tp1_breakeven_market_and_limit_25pct_split():
"""watch_position_tp1_breakeven handles both Market TP1 order fill and Limit bound- TP1 with 25% TP1 split."""
import asyncio
from unittest.mock import AsyncMock, patch
from engine.execution.bybit_executor import watch_position_tp1_breakeven
async def _run():
# 1. Market TP1 order ID ("tp1-777") reaches Filled -> moves SL to breakeven
with patch("engine.execution.bybit_executor.BybitExecutor._request", new_callable=AsyncMock) as req_mock, \
patch("engine.execution.bybit_executor.BybitExecutor.get_open_position", new_callable=AsyncMock, return_value={"size": "1.25", "avgPrice": "100.0", "side": "Buy"}), \
patch("engine.execution.bybit_executor.BybitExecutor.move_sl_to_breakeven", new_callable=AsyncMock, return_value={"breakeven_sl": 100.06}) as move_mock, \
patch("engine.execution.bybit_executor.BybitExecutor.close", new_callable=AsyncMock):
req_mock.return_value = {"retCode": 0, "result": {"list": [{"orderId": "tp1-777", "orderStatus": "Filled"}]}}
res_mkt = await watch_position_tp1_breakeven(
api_key="k",
api_secret="s",
mode="demo",
proxy_url=None,
symbol="BTCUSDT",
side="Buy",
total_qty=2.5,
tp1_qty=1.25,
tp1_order_id="tp1-777",
poll_interval=0.01,
max_polls=2,
)
assert res_mkt["status"] == "BREAKEVEN_ARMED"
assert move_mock.called
# 2. Limit order with bound TP1 ("bound-lim-999") and 25% TP1 split (total_qty=4.0, tp1_qty=1.0 -> drops to 3.0 <= 3.5)
with patch("engine.execution.bybit_executor.BybitExecutor.get_open_position", new_callable=AsyncMock, return_value={"size": "3.0", "avgPrice": "200.0", "side": "Sell"}), \
patch("engine.execution.bybit_executor.BybitExecutor.move_sl_to_breakeven", new_callable=AsyncMock, return_value={"breakeven_sl": 199.88}) as move_mock_lim, \
patch("engine.execution.bybit_executor.BybitExecutor.close", new_callable=AsyncMock):
res_lim = await watch_position_tp1_breakeven(
api_key="k",
api_secret="s",
mode="demo",
proxy_url=None,
symbol="ETHUSDT",
side="Sell",
total_qty=4.0,
tp1_qty=1.0,
tp1_order_id="bound-lim-999",
poll_interval=0.01,
max_polls=2,
)
assert res_lim["status"] == "BREAKEVEN_ARMED"
assert move_mock_lim.called
asyncio.run(_run())
def test_execution_route_auto_breakeven_stateful_vs_serverless(monkeypatch):
"""POST /api/execution/bybit/order with auto_breakeven=True schedules watcher in stateful mode and returns STATELESS_MANUAL_BREAKEVEN on Vercel."""
from unittest.mock import AsyncMock, patch
from fastapi.testclient import TestClient
from main import app
import security
client = TestClient(app)
monkeypatch.setattr(security, "PERPS_API_TOKEN", "test-exec-token")
monkeypatch.delenv("VERCEL", raising=False)
mock_exec_result = {
"success": True,
"symbol": "BTCUSDT",
"side": "Buy",
"order_type": "MARKET",
"margin_usd": 100.0,
"leverage": 5,
"notional_usd": 500.0,
"total_qty": 5.0,
"tp1_qty": 2.5,
"tp2_qty": 2.5,
"entry_order_id": "mkt-111",
"stop_loss": 95.0,
"tp_orders": [
{"tp_level": "TP1", "percent": 50.0, "order_id": "tp1-111", "price": 105.0, "qty": 2.5},
{"tp_level": "TP2", "percent": 50.0, "order_id": "tp2-111", "price": 110.0, "qty": 2.5},
],
"mode": "demo",
"timestamp": 1.0,
}
payload = {
"symbol": "BTCUSDT",
"side": "Buy",
"order_type": "Market",
"margin_usd": 100.0,
"leverage": 5,
"stop_loss": 95.0,
"take_profit_1": 105.0,
"take_profit_2": 110.0,
"tp1_percent": 50.0,
"auto_breakeven": True,
"log_to_journal": False,
}
headers = {
"Authorization": "Bearer test-exec-token",
"X-Bybit-Api-Key": "bybit-k",
"X-Bybit-Api-Secret": "bybit-s",
"X-Bybit-Mode": "demo",
}
be_watcher_mock = AsyncMock(return_value={"status": "BREAKEVEN_ARMED"})
with patch("routers.execution.BybitExecutor.execute_trade_setup", new_callable=AsyncMock, return_value=dict(mock_exec_result)), \
patch("routers.execution.BybitExecutor.close", new_callable=AsyncMock), \
patch("routers.execution.watch_position_tp1_breakeven", be_watcher_mock):
resp = client.post("/api/execution/bybit/order", json=payload, headers=headers)
assert resp.status_code == 200
assert resp.json()["execution"]["breakeven_watcher_scheduled"] is True
assert resp.json()["execution"]["breakeven_status"] == "WATCHING_TP1_FOR_BREAKEVEN"
assert be_watcher_mock.called
monkeypatch.setenv("VERCEL", "1")
be_watcher_sv = AsyncMock(return_value={"status": "BREAKEVEN_ARMED"})
with patch("routers.execution.BybitExecutor.execute_trade_setup", new_callable=AsyncMock, return_value=dict(mock_exec_result)), \
patch("routers.execution.BybitExecutor.close", new_callable=AsyncMock), \
patch("routers.execution.watch_position_tp1_breakeven", be_watcher_sv):
resp_sv = client.post("/api/execution/bybit/order", json=payload, headers=headers)
assert resp_sv.status_code == 200
assert resp_sv.json()["execution"]["breakeven_watcher_scheduled"] is False
assert resp_sv.json()["execution"]["breakeven_status"] == "STATELESS_MANUAL_BREAKEVEN"
assert not be_watcher_sv.called
|