| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582 |
- from __future__ import annotations
- from pathlib import Path
- from tempfile import TemporaryDirectory
- from fastapi.testclient import TestClient
- from src.trader_mcp import strategy_registry, strategy_store
- from src.trader_mcp.server import app
- from src.trader_mcp.strategy_context import StrategyContext
- from src.trader_mcp.strategy_sdk import Strategy as BaseStrategy
- from strategies.grid_trader import Strategy as GridStrategy
- from strategies.trend_follower import Strategy as TrendStrategy
- STRATEGY_CODE = '''
- from src.trader_mcp.strategy_sdk import Strategy
- class Strategy(Strategy):
- def init(self):
- return {"started": True, "config_copy": dict(self.config)}
- '''
- def test_strategies_endpoints_roundtrip():
- with TemporaryDirectory() as tmpdir:
- strategy_store.DB_PATH = Path(tmpdir) / "trader_mcp.sqlite3"
- from src.trader_mcp import strategy_registry
- strategy_registry.STRATEGIES_DIR = Path(tmpdir) / "strategies"
- strategy_registry.STRATEGIES_DIR.mkdir()
- (strategy_registry.STRATEGIES_DIR / "demo.py").write_text(STRATEGY_CODE)
- client = TestClient(app)
- r = client.get("/strategies")
- assert r.status_code == 200
- body = r.json()
- assert "available" in body
- assert "configured" in body
- r = client.post(
- "/strategies",
- json={
- "id": "demo-1",
- "strategy_type": "demo",
- "account_id": "acct-1",
- "client_id": "strategy:test",
- "mode": "observe",
- "config": {"risk": 0.01},
- },
- )
- assert r.status_code == 200
- assert r.json()["id"] == "demo-1"
- r = client.get("/strategies")
- assert any(item["id"] == "demo-1" for item in r.json()["configured"])
- r = client.delete("/strategies/demo-1")
- assert r.status_code == 200
- assert r.json()["ok"] is True
- def test_strategy_context_binds_identity(monkeypatch):
- calls = {}
- def fake_place_order(arguments):
- calls["place_order"] = arguments
- return {"ok": True}
- def fake_open_orders(account_id, client_id=None):
- calls["open_orders"] = {"account_id": account_id, "client_id": client_id}
- return {"ok": True}
- def fake_cancel_all(account_id, client_id=None):
- calls["cancel_all"] = {"account_id": account_id, "client_id": client_id}
- return {"ok": True}
- monkeypatch.setattr("src.trader_mcp.strategy_context.place_order", fake_place_order)
- monkeypatch.setattr("src.trader_mcp.strategy_context.list_open_orders", fake_open_orders)
- monkeypatch.setattr("src.trader_mcp.strategy_context.cancel_all_orders", fake_cancel_all)
- ctx = StrategyContext(id="inst-1", account_id="acct-1", client_id="client-1", mode="active")
- ctx.place_order(side="sell", market="xrpusd", order_type="limit", amount="10", price="2")
- ctx.get_open_orders()
- ctx.cancel_all_orders()
- assert calls["place_order"]["account_id"] == "acct-1"
- assert calls["place_order"]["client_id"] == "client-1"
- assert calls["open_orders"] == {"account_id": "acct-1", "client_id": "client-1"}
- assert calls["cancel_all"] == {"account_id": "acct-1", "client_id": "client-1"}
- def test_stop_loss_strategy_loads_with_aligned_regime_config(tmp_path):
- original_db = strategy_store.DB_PATH
- original_dir = strategy_registry.STRATEGIES_DIR
- try:
- strategy_store.DB_PATH = tmp_path / "trader_mcp.sqlite3"
- strategy_registry.STRATEGIES_DIR = tmp_path / "strategies"
- strategy_registry.STRATEGIES_DIR.mkdir()
- (strategy_registry.STRATEGIES_DIR / "grid_trader.py").write_text((Path(__file__).resolve().parents[1] / "strategies" / "grid_trader.py").read_text())
- (strategy_registry.STRATEGIES_DIR / "exposure_protector.py").write_text((Path(__file__).resolve().parents[1] / "strategies" / "exposure_protector.py").read_text())
- grid_defaults = strategy_registry.get_strategy_default_config("grid_trader")
- stop_defaults = strategy_registry.get_strategy_default_config("exposure_protector")
- assert grid_defaults["trade_sides"] == "both"
- assert grid_defaults["grid_step_pct"] == 0.012
- assert stop_defaults["trail_distance_pct"] == 0.03
- assert stop_defaults["rebalance_target_ratio"] == 0.5
- assert stop_defaults["min_rebalance_seconds"] == 180
- assert stop_defaults["min_price_move_pct"] == 0.005
- finally:
- strategy_store.DB_PATH = original_db
- strategy_registry.STRATEGIES_DIR = original_dir
- def test_grid_supervision_only_reports_ready_for_handoff_on_true_depletion():
- class FakeContext:
- account_id = "acct-1"
- market_symbol = "xrpusd"
- base_currency = "XRP"
- counter_currency = "USD"
- mode = "active"
- strategy = GridStrategy(FakeContext(), {})
- strategy.state.update({
- "last_price": 1.45,
- "base_available": 50.0,
- "counter_available": 38.7,
- "regimes": {"1h": {"trend": {"state": "bull"}}},
- })
- supervision = strategy._supervision()
- assert supervision["inventory_pressure"] == "base_heavy"
- assert supervision["switch_readiness"] == "watch_handoff"
- assert supervision["desired_companion"] is None
- strategy.state.update({
- "base_available": 88.0,
- "counter_available": 4.0,
- })
- supervision = strategy._supervision()
- assert supervision["inventory_pressure"] == "base_side_depleted"
- assert supervision["switch_readiness"] == "ready_for_handoff"
- assert supervision["desired_companion"] == "exposure_protector"
- def test_grid_missing_order_triggers_full_rebuild(monkeypatch):
- class FakeContext:
- base_currency = "XRP"
- counter_currency = "USD"
- market_symbol = "xrpusd"
- minimum_order_value = 10.0
- mode = "active"
- def __init__(self):
- self.cancelled_all = 0
- self.placed_orders = []
- def get_fee_rates(self, market):
- return {"maker": 0.0, "taker": 0.004}
- def get_account_info(self):
- return {
- "balances": [
- {"asset_code": "USD", "available": 13.55},
- {"asset_code": "XRP", "available": 22.0103},
- ]
- }
- def suggest_order_amount(
- self,
- *,
- side,
- price,
- levels,
- min_notional,
- fee_rate,
- max_notional_per_order=0.0,
- dust_collect=False,
- order_size=0.0,
- safety=0.995,
- ):
- if side == "buy":
- quote_available = 13.55
- spendable_quote = quote_available * safety
- quote_cap = min(spendable_quote, max_notional_per_order) if max_notional_per_order > 0 else spendable_quote
- if quote_cap < min_notional * (1 + fee_rate):
- return 0.0
- return quote_cap / (price * (1 + fee_rate))
- return 0.0
- def cancel_all_orders(self):
- self.cancelled_all += 1
- return {"ok": True}
- def place_order(self, **kwargs):
- self.placed_orders.append(kwargs)
- return {"status": "ok", "id": f"oid-{len(self.placed_orders)}"}
- ctx = FakeContext()
- strategy = GridStrategy(
- ctx,
- {
- "grid_levels": 2,
- "grid_step_pct": 0.0062,
- "grid_step_min_pct": 0.0033,
- "grid_step_max_pct": 0.012,
- "max_notional_per_order": 12,
- "order_call_delay_ms": 0,
- "trade_sides": "both",
- "debug_orders": True,
- "dust_collect": True,
- "enable_trend_guard": False,
- "fee_rate": 0.004,
- },
- )
- strategy.state["center_price"] = 1.3285
- strategy.state["seeded"] = True
- strategy.state["base_available"] = 22.0103
- strategy.state["counter_available"] = 13.55
- strategy.state["orders"] = [
- {"side": "buy", "price": 1.3243993, "amount": 7.63, "id": "existing-buy"},
- {"side": "sell", "price": 1.3326007, "amount": 9.0, "id": "sell-1"},
- {"side": "sell", "price": 1.3367011, "amount": 9.0, "id": "sell-2"},
- ]
- strategy.state["order_ids"] = ["existing-buy", "sell-1", "sell-2"]
- def fake_sync_open_orders_state():
- live = [{"side": "sell", "price": 1.3326007, "amount": 9.0, "id": "sell-1"}]
- strategy.state["orders"] = live
- strategy.state["order_ids"] = ["sell-1"]
- strategy.state["open_order_count"] = 1
- return live
- monkeypatch.setattr(strategy, "_sync_open_orders_state", fake_sync_open_orders_state)
- monkeypatch.setattr(strategy, "_price", lambda: 1.3285)
- monkeypatch.setattr(strategy, "_refresh_regimes", lambda: None)
- monkeypatch.setattr(strategy, "_grid_refresh_paused", lambda: False)
- monkeypatch.setattr(strategy, "_recenter_threshold_pct", lambda: 0.5)
- result = strategy.on_tick({})
- assert result["action"] in {"seed", "reseed"}
- assert ctx.cancelled_all == 1
- assert len(ctx.placed_orders) > 0
- assert strategy.state["last_action"] == "reseeded"
- def test_grid_side_imbalance_triggers_full_rebuild(monkeypatch):
- class FakeContext:
- base_currency = "XRP"
- counter_currency = "USD"
- market_symbol = "xrpusd"
- minimum_order_value = 10.0
- mode = "active"
- def __init__(self):
- self.cancelled_all = 0
- self.placed_orders = []
- def get_fee_rates(self, market):
- return {"maker": 0.0, "taker": 0.004}
- def get_account_info(self):
- return {"balances": [{"asset_code": "USD", "available": 41.29}, {"asset_code": "XRP", "available": 9.98954}]}
- def cancel_all_orders(self):
- self.cancelled_all += 1
- return {"ok": True}
- def suggest_order_amount(self, **kwargs):
- return 10.0
- def place_order(self, **kwargs):
- self.placed_orders.append(kwargs)
- return {"status": "ok", "id": f"oid-{len(self.placed_orders)}"}
- ctx = FakeContext()
- strategy = GridStrategy(ctx, {"grid_levels": 2, "order_call_delay_ms": 0, "enable_trend_guard": False, "fee_rate": 0.004})
- strategy.state["center_price"] = 1.3907
- strategy.state["seeded"] = True
- strategy.state["orders"] = [{"side": "buy", "price": 1.3800, "amount": 10.0, "id": "o1"} for _ in range(5)]
- strategy.state["order_ids"] = [f"o{i}" for i in range(5)]
- def fake_sync_open_orders_state():
- live = [{"side": "buy", "price": 1.3800, "amount": 10.0, "id": f"o{i}"} for i in range(5)]
- strategy.state["orders"] = live
- strategy.state["order_ids"] = [f"o{i}" for i in range(5)]
- strategy.state["open_order_count"] = 5
- return live
- monkeypatch.setattr(strategy, "_sync_open_orders_state", fake_sync_open_orders_state)
- monkeypatch.setattr(strategy, "_refresh_balance_snapshot", lambda: None)
- monkeypatch.setattr(strategy, "_price", lambda: 1.3915)
- monkeypatch.setattr(strategy, "_refresh_regimes", lambda: None)
- monkeypatch.setattr(strategy, "_grid_refresh_paused", lambda: False)
- monkeypatch.setattr(strategy, "_recenter_threshold_pct", lambda: 0.5)
- result = strategy.on_tick({})
- assert result["action"] in {"seed", "reseed"}
- assert ctx.cancelled_all == 1
- assert len(ctx.placed_orders) > 0
- def test_grid_recenters_exactly_on_live_price():
- class FakeContext:
- base_currency = "XRP"
- counter_currency = "USD"
- market_symbol = "xrpusd"
- minimum_order_value = 10.0
- mode = "active"
- def cancel_all_orders(self):
- return {"ok": True}
- def get_fee_rates(self, market):
- return {"maker": 0.0, "taker": 0.0}
- def suggest_order_amount(self, **kwargs):
- return 0.1
- def place_order(self, **kwargs):
- return {"status": "ok", "id": "oid-1"}
- strategy = GridStrategy(FakeContext(), {})
- strategy.state["center_price"] = 100.0
- strategy._recenter_and_rebuild_from_price(160.0, "test recenter")
- assert strategy.state["center_price"] == 160.0
- def test_grid_stop_cancels_all_open_orders():
- class FakeContext:
- base_currency = "XRP"
- counter_currency = "USD"
- market_symbol = "xrpusd"
- minimum_order_value = 10.0
- mode = "active"
- def __init__(self):
- self.cancelled = False
- def cancel_all_orders(self):
- self.cancelled = True
- return {"ok": True}
- def get_fee_rates(self, market):
- return {"maker": 0.0, "taker": 0.0}
- strategy = GridStrategy(FakeContext(), {})
- strategy.state["orders"] = [{"id": "o1"}]
- strategy.state["order_ids"] = ["o1"]
- strategy.state["open_order_count"] = 1
- strategy.on_stop()
- assert strategy.context.cancelled is True
- assert strategy.state["open_order_count"] == 0
- assert strategy.state["last_action"] == "stopped"
- def test_base_strategy_report_uses_context_snapshot():
- class FakeContext:
- id = "s-1"
- account_id = "acct-1"
- market_symbol = "xrpusd"
- base_currency = "XRP"
- counter_currency = "USD"
- mode = "active"
- def get_strategy_snapshot(self):
- return {
- "identity": {"strategy_id": "s-1", "strategy_name": "Demo", "account_id": "acct-1", "market": "xrpusd", "base_currency": "XRP", "quote_currency": "USD"},
- "control": {"enabled_state": "on", "mode": "active"},
- "position": {"balances": [{"asset_code": "XRP", "available": 1.0}]},
- "orders": {"open_orders": [{"id": "o1"}]},
- "execution": {"execution_quality": "good"},
- }
- class DemoStrategy(BaseStrategy):
- LABEL = "Demo"
- report = DemoStrategy(FakeContext(), {}).report()
- assert report["identity"]["strategy_id"] == "s-1"
- assert report["control"]["mode"] == "active"
- assert report["position"]["open_orders"][0]["id"] == "o1"
- def test_trend_follower_uses_policy_and_reports_fit():
- class FakeContext:
- id = "s-2"
- account_id = "acct-2"
- client_id = "cid-2"
- mode = "active"
- market_symbol = "xrpusd"
- base_currency = "XRP"
- counter_currency = "USD"
- def get_price(self, symbol):
- return {"price": 1.2}
- def get_regime(self, symbol, timeframe="1h"):
- return {"trend": {"state": "bull", "strength": 0.9}}
- def place_order(self, **kwargs):
- return {"ok": True, "order": kwargs}
- def get_strategy_snapshot(self):
- return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
- strat = TrendStrategy(FakeContext(), {"order_size": 1.5})
- strat.apply_policy()
- report = strat.report()
- assert report["fit"]["risk_profile"] == "growth"
- assert strat.state["policy_derived"]["order_size"] > 0
- def test_trend_follower_buys_from_bull_regime_without_explicit_strength():
- class FakeContext:
- id = "s-bull"
- account_id = "acct-1"
- client_id = "cid-1"
- mode = "active"
- market_symbol = "xrpusd"
- base_currency = "XRP"
- counter_currency = "USD"
- def __init__(self):
- self.orders = []
- def get_price(self, symbol):
- return {"price": 1.2}
- def get_regime(self, symbol, timeframe="1h"):
- return {
- "trend": {"state": "bull", "ema_fast": 1.21, "ema_slow": 1.18},
- "momentum": {"state": "bull", "rsi": 64, "macd_histogram": 0.002},
- }
- def place_order(self, **kwargs):
- self.orders.append(kwargs)
- return {"ok": True, "order": kwargs}
- def get_account_info(self):
- return {"balances": [{"asset_code": "USD", "available": 1000}, {"asset_code": "XRP", "available": 0}]}
- minimum_order_value = 10.0
- def suggest_order_amount(self, **kwargs):
- return 10.0
- def get_strategy_snapshot(self):
- return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
- ctx = FakeContext()
- strat = TrendStrategy(ctx, {"order_size": 2.0, "trend_timeframe": "15m"})
- result = strat.on_tick({})
- assert result["action"] == "buy"
- assert ctx.orders[-1]["side"] == "buy"
- assert ctx.orders[-1]["amount"] == 10.0
- assert strat.state["last_action"] == "buy_trend"
- assert strat.state["last_strength"] >= 0.65
- def test_trend_follower_sells_from_bear_regime_without_explicit_strength():
- class FakeContext:
- id = "s-bear"
- account_id = "acct-1"
- client_id = "cid-1"
- mode = "active"
- market_symbol = "xrpusd"
- base_currency = "XRP"
- counter_currency = "USD"
- def __init__(self):
- self.orders = []
- def get_price(self, symbol):
- return {"price": 1.2}
- def get_regime(self, symbol, timeframe="1h"):
- return {
- "trend": {"state": "bear", "ema_fast": 1.17, "ema_slow": 1.2},
- "momentum": {"state": "bear", "rsi": 36, "macd_histogram": -0.002},
- }
- def place_order(self, **kwargs):
- self.orders.append(kwargs)
- return {"ok": True, "order": kwargs}
- def get_account_info(self):
- return {"balances": [{"asset_code": "USD", "available": 1000}, {"asset_code": "XRP", "available": 10}]}
- minimum_order_value = 10.0
- def suggest_order_amount(self, **kwargs):
- return 6.0
- def get_strategy_snapshot(self):
- return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
- ctx = FakeContext()
- strat = TrendStrategy(ctx, {"order_size": 2.0, "trend_timeframe": "15m"})
- result = strat.on_tick({})
- assert result["action"] == "sell"
- assert ctx.orders[-1]["side"] == "sell"
- assert ctx.orders[-1]["amount"] == 6.0
- assert strat.state["last_action"] == "sell_trend"
- assert strat.state["last_strength"] >= 0.65
- def test_trend_follower_policy_does_not_override_explicit_order_size():
- class FakeContext:
- id = "s-explicit"
- account_id = "acct-1"
- client_id = "cid-1"
- mode = "active"
- market_symbol = "xrpusd"
- base_currency = "XRP"
- counter_currency = "USD"
- def get_price(self, symbol):
- return {"price": 1.2}
- def get_regime(self, symbol, timeframe="1h"):
- return {"trend": {"state": "bull", "strength": 0.9}}
- def get_strategy_snapshot(self):
- return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
- strat = TrendStrategy(FakeContext(), {"order_size": 10.5})
- strat.apply_policy()
- assert strat.config["order_size"] == 10.5
- assert strat.state["policy_derived"]["order_size"] == 10.5
- def test_trend_follower_passes_live_fee_rate_into_sizing_helper():
- class FakeContext:
- id = "s-fee"
- account_id = "acct-1"
- client_id = "cid-1"
- mode = "active"
- market_symbol = "xrpusd"
- base_currency = "XRP"
- counter_currency = "USD"
- minimum_order_value = 10.0
- def __init__(self):
- self.fee_calls = []
- self.suggest_calls = []
- def get_price(self, symbol):
- return {"price": 1.2}
- def get_regime(self, symbol, timeframe="1h"):
- return {"trend": {"state": "bull", "strength": 0.9}}
- def get_fee_rates(self, market_symbol=None):
- self.fee_calls.append(market_symbol)
- return {"maker": 0.0025, "taker": 0.004}
- def suggest_order_amount(self, **kwargs):
- self.suggest_calls.append(kwargs)
- return 8.0
- def place_order(self, **kwargs):
- return {"ok": True, "order": kwargs}
- def get_account_info(self):
- return {"balances": [{"asset_code": "USD", "available": 1000}, {"asset_code": "XRP", "available": 0}]}
- def get_strategy_snapshot(self):
- return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
- ctx = FakeContext()
- strat = TrendStrategy(ctx, {"order_size": 10.5, "trend_timeframe": "15m"})
- strat.on_tick({})
- assert ctx.fee_calls == ["xrpusd"]
- assert ctx.suggest_calls[-1]["fee_rate"] == 0.0025
|