Perps-Terminal / tests /test_execution.py
Naufal Arhab
chore: full codebase audit fixes, L2/whale/calibration upgrades, and rebuild frontend dist
48f60d7
Raw History Blame Contribute Delete
29.3 kB
"""
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