from __future__ import annotations from pathlib import Path import pytest from exec_mcp import storage from exec_mcp import repo from exec_mcp.services_orders import get_open_orders, place_order class _FakeTrading: def buy_order(self, **kwargs): return {"id": "12345", "status": "open", "client_order_id": "broker-client-1", **kwargs} def buy_gtd_order(self, **kwargs): return {"id": "12345", "status": "open", "client_order_id": "broker-client-1", **kwargs} def sell_order(self, **kwargs): return {"id": "12345", "status": "open", "client_order_id": "broker-client-1", **kwargs} def sell_gtd_order(self, **kwargs): return {"id": "12345", "status": "open", "client_order_id": "broker-client-1", **kwargs} class _FakeClient: def __init__(self): self.trading = _FakeTrading() @pytest.fixture() def temp_db(tmp_path, monkeypatch): db_path = tmp_path / "exec.sqlite3" monkeypatch.setattr(storage, "DB_PATH", db_path) storage.init_db() return db_path def test_place_order_rejects_non_string_client_id(temp_db, monkeypatch): monkeypatch.setattr("exec_mcp.services_orders._get_client", lambda account_id: _FakeClient()) monkeypatch.setattr("exec_mcp.services_orders.load_market_by_symbol", lambda market: {"base_decimals": 8, "counter_decimals": 2, "minimum_order_value": "0", "counter_currency": "USD"}) with pytest.raises(Exception) as exc: place_order( account_id="acct-1", market="xrpusd", side="buy", order_type="market", amount="10", client_id=123, ) assert "client_id must be a string" in str(exc.value) def test_place_order_persists_client_id_and_get_open_orders_filters(temp_db, monkeypatch): monkeypatch.setattr("exec_mcp.services_orders._get_client", lambda account_id: _FakeClient()) monkeypatch.setattr("exec_mcp.services_orders.load_market_by_symbol", lambda market: {"base_decimals": 8, "counter_decimals": 2, "minimum_order_value": "0", "counter_currency": "USD"}) repo.create_account(display_name="strategy", venue="bitstamp", venue_account_ref="ref-1", api_key="k", api_secret="s") result = place_order( account_id=repo.list_accounts(enabled_only=False)[0]["id"], market="xrpusd", side="buy", order_type="market", amount="10", client_id="strategy-a:v1:abc123", ) assert result["ok"] is True orders = get_open_orders(account_id=repo.list_accounts(enabled_only=False)[0]["id"], client_id="strategy-a:v1:abc123") assert orders["ok"] is True assert orders["client_id"] == "strategy-a:v1:abc123" assert len(orders["orders"]) == 1 assert orders["orders"][0]["client_id"] == "strategy-a:v1:abc123"