feat(V2): migrazione alpaca completa
Task 6.7: porting alpaca da services/mcp-alpaca a src/cerbero_mcp. client.py + leverage_cap.py copiati 1:1 (default cap 1 cash). tools.py: 17 tool senza ACL/Principal/audit. Router /mcp-alpaca con 18 route (env_info + 17 tool). Builder branch alpaca: paper=(env=="testnet"), api_key viene da settings.alpaca.api_key_id. Test client + leverage_cap migrati (15 test alpaca pass). Test builder con stub SDK alpaca-py. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
from cerbero_mcp.exchanges.alpaca.client import AlpacaClient
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_trading():
|
||||
return MagicMock(name="alpaca_TradingClient")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_stock():
|
||||
return MagicMock(name="alpaca_StockHistoricalDataClient")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_crypto():
|
||||
return MagicMock(name="alpaca_CryptoHistoricalDataClient")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_option():
|
||||
return MagicMock(name="alpaca_OptionHistoricalDataClient")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(mock_trading, mock_stock, mock_crypto, mock_option):
|
||||
return AlpacaClient(
|
||||
api_key="test_key",
|
||||
secret_key="test_secret",
|
||||
paper=True,
|
||||
trading=mock_trading,
|
||||
stock_data=mock_stock,
|
||||
crypto_data=mock_crypto,
|
||||
option_data=mock_option,
|
||||
)
|
||||
@@ -0,0 +1,80 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_init_paper_mode(client, mock_trading):
|
||||
assert client.paper is True
|
||||
assert client._trading is mock_trading
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_account_calls_trading(client, mock_trading):
|
||||
mock_trading.get_account.return_value = MagicMock(
|
||||
model_dump=lambda: {"equity": 100000, "cash": 50000}
|
||||
)
|
||||
result = await client.get_account()
|
||||
mock_trading.get_account.assert_called_once()
|
||||
assert result["equity"] == 100000
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_positions_returns_list(client, mock_trading):
|
||||
pos_mock = MagicMock(model_dump=lambda: {"symbol": "AAPL", "qty": 10})
|
||||
mock_trading.get_all_positions.return_value = [pos_mock]
|
||||
result = await client.get_positions()
|
||||
assert len(result) == 1
|
||||
assert result[0]["symbol"] == "AAPL"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_place_market_order_stocks(client, mock_trading):
|
||||
order_mock = MagicMock(model_dump=lambda: {"id": "o123", "symbol": "AAPL"})
|
||||
mock_trading.submit_order.return_value = order_mock
|
||||
result = await client.place_order(
|
||||
symbol="AAPL", side="buy", qty=1, order_type="market", asset_class="stocks",
|
||||
)
|
||||
assert result["id"] == "o123"
|
||||
assert mock_trading.submit_order.called
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_place_limit_order_requires_price(client):
|
||||
with pytest.raises(ValueError, match="limit_price"):
|
||||
await client.place_order(
|
||||
symbol="AAPL", side="buy", qty=1, order_type="limit",
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cancel_order(client, mock_trading):
|
||||
mock_trading.cancel_order_by_id.return_value = None
|
||||
result = await client.cancel_order("o1")
|
||||
mock_trading.cancel_order_by_id.assert_called_once_with("o1")
|
||||
assert result == {"order_id": "o1", "canceled": True}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_close_position_no_options(client, mock_trading):
|
||||
order_mock = MagicMock(model_dump=lambda: {"id": "close-1"})
|
||||
mock_trading.close_position.return_value = order_mock
|
||||
result = await client.close_position("AAPL")
|
||||
assert mock_trading.close_position.called
|
||||
assert result["id"] == "close-1"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_clock(client, mock_trading):
|
||||
clock_mock = MagicMock(model_dump=lambda: {"is_open": True, "next_close": "2026-04-21T20:00:00Z"})
|
||||
mock_trading.get_clock.return_value = clock_mock
|
||||
result = await client.get_clock()
|
||||
assert result["is_open"] is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_invalid_asset_class(client):
|
||||
with pytest.raises(ValueError, match="invalid asset_class"):
|
||||
await client.get_ticker("AAPL", asset_class="forex")
|
||||
@@ -0,0 +1,46 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
from cerbero_mcp.exchanges.alpaca.leverage_cap import enforce_leverage, get_max_leverage
|
||||
|
||||
|
||||
def test_get_max_leverage_returns_creds_value():
|
||||
creds = {"max_leverage": 4}
|
||||
assert get_max_leverage(creds) == 4
|
||||
|
||||
|
||||
def test_get_max_leverage_default_when_missing():
|
||||
"""Default 1 (cash) se il secret non ha max_leverage."""
|
||||
assert get_max_leverage({}) == 1
|
||||
|
||||
|
||||
def test_enforce_leverage_pass_at_cap_one():
|
||||
"""Alpaca cash account: cap 1, leverage 1 OK."""
|
||||
creds = {"max_leverage": 1}
|
||||
enforce_leverage(1, creds=creds, exchange="alpaca") # no raise
|
||||
|
||||
|
||||
def test_enforce_leverage_reject_over_cap_one():
|
||||
creds = {"max_leverage": 1}
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
enforce_leverage(2, creds=creds, exchange="alpaca")
|
||||
assert exc.value.status_code == 403
|
||||
assert exc.value.detail["error"] == "LEVERAGE_CAP_EXCEEDED"
|
||||
assert exc.value.detail["exchange"] == "alpaca"
|
||||
assert exc.value.detail["requested"] == 2
|
||||
assert exc.value.detail["max"] == 1
|
||||
|
||||
|
||||
def test_enforce_leverage_reject_when_below_one():
|
||||
creds = {"max_leverage": 1}
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
enforce_leverage(0, creds=creds, exchange="alpaca")
|
||||
assert exc.value.status_code == 403
|
||||
|
||||
|
||||
def test_enforce_leverage_default_when_none():
|
||||
"""Se requested è None, applica il cap come default."""
|
||||
creds = {"max_leverage": 1}
|
||||
result = enforce_leverage(None, creds=creds, exchange="alpaca")
|
||||
assert result == 1
|
||||
@@ -71,6 +71,37 @@ async def test_build_client_hyperliquid_returns_correct_env(monkeypatch):
|
||||
assert "test" not in c_live.base_url.lower()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_build_client_alpaca_returns_correct_env(monkeypatch):
|
||||
from tests.unit.test_settings import _minimal_env
|
||||
|
||||
for k, v in _minimal_env().items():
|
||||
monkeypatch.setenv(k, v)
|
||||
|
||||
# Stub alpaca SDK clients per evitare connessioni reali in __init__
|
||||
from cerbero_mcp.exchanges.alpaca import client as alpaca_client
|
||||
|
||||
class _FakeSdk:
|
||||
def __init__(self, **kwargs):
|
||||
self.kwargs = kwargs
|
||||
|
||||
monkeypatch.setattr(alpaca_client, "TradingClient", _FakeSdk)
|
||||
monkeypatch.setattr(alpaca_client, "StockHistoricalDataClient", _FakeSdk)
|
||||
monkeypatch.setattr(alpaca_client, "CryptoHistoricalDataClient", _FakeSdk)
|
||||
monkeypatch.setattr(alpaca_client, "OptionHistoricalDataClient", _FakeSdk)
|
||||
|
||||
from cerbero_mcp.settings import Settings
|
||||
from cerbero_mcp.exchanges import build_client
|
||||
|
||||
s = Settings()
|
||||
c_test = await build_client(s, "alpaca", "testnet")
|
||||
c_live = await build_client(s, "alpaca", "mainnet")
|
||||
|
||||
assert c_test is not c_live
|
||||
assert c_test.paper is True
|
||||
assert c_live.paper is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_build_client_unknown_exchange_raises(monkeypatch):
|
||||
from tests.unit.test_settings import _minimal_env
|
||||
|
||||
Reference in New Issue
Block a user