| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534 |
- 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_sizing import cap_amount_to_balance_target
- from src.trader_mcp.strategy_sdk import Strategy as BaseStrategy
- from strategies.exposure_protector import Strategy as ExposureStrategy
- from strategies.dumb_trader import Strategy as DumbStrategy
- from strategies.grid_trader import Strategy as GridStrategy
- 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_strategy_context_cancel_all_orders_confirmed_after_empty_followup(monkeypatch):
- calls = {"open_orders": 0}
- def fake_cancel_all(account_id, client_id=None):
- calls["cancel_all"] = {"account_id": account_id, "client_id": client_id}
- return {"ok": True, "cancelled": [{"ok": True, "order_id": "o1"}]}
- def fake_open_orders(account_id, client_id=None):
- calls["open_orders"] += 1
- return {"orders": []}
- monkeypatch.setattr("src.trader_mcp.strategy_context.cancel_all_orders", fake_cancel_all)
- monkeypatch.setattr("src.trader_mcp.strategy_context.list_open_orders", fake_open_orders)
- ctx = StrategyContext(id="inst-1", account_id="acct-1", client_id="client-1", mode="active")
- result = ctx.cancel_all_orders_confirmed()
- assert result["conclusive"] is True
- assert result["cleanup_status"] == "cleanup_confirmed"
- assert result["cancelled_order_ids"] == ["o1"]
- assert result["remaining_orders"] == []
- assert result["error"] is None
- assert calls["cancel_all"] == {"account_id": "acct-1", "client_id": "client-1"}
- assert calls["open_orders"] == 1
- def test_strategy_context_cancel_all_orders_confirmed_preserves_inconclusive_failure(monkeypatch):
- calls = {"open_orders": 0}
- def fake_cancel_all(account_id, client_id=None):
- raise RuntimeError("auth breaker active")
- def fake_open_orders(account_id, client_id=None):
- calls["open_orders"] += 1
- return {"orders": [{"id": "o1"}]}
- monkeypatch.setattr("src.trader_mcp.strategy_context.cancel_all_orders", fake_cancel_all)
- monkeypatch.setattr("src.trader_mcp.strategy_context.list_open_orders", fake_open_orders)
- ctx = StrategyContext(id="inst-1", account_id="acct-1", client_id="client-1", mode="active")
- result = ctx.cancel_all_orders_confirmed()
- assert result["conclusive"] is False
- assert result["cleanup_status"] == "cleanup_failed"
- assert result["cancelled_order_ids"] == []
- assert result["remaining_orders"] == [{"id": "o1"}]
- assert result["error"] == "auth breaker active"
- assert calls["open_orders"] == 1
- def test_strategy_context_cancel_all_orders_confirmed_keeps_partial_reply_inconclusive(monkeypatch):
- calls = {"open_orders": 0}
- def fake_cancel_all(account_id, client_id=None):
- calls["cancel_all"] = {"account_id": account_id, "client_id": client_id}
- return {
- "ok": True,
- "cancelled": [
- {"ok": True, "order_id": "o1"},
- {"ok": False, "order_id": "o2", "status": "deferred", "error": "auth breaker active"},
- ],
- }
- def fake_open_orders(account_id, client_id=None):
- calls["open_orders"] += 1
- return {"orders": []}
- monkeypatch.setattr("src.trader_mcp.strategy_context.cancel_all_orders", fake_cancel_all)
- monkeypatch.setattr("src.trader_mcp.strategy_context.list_open_orders", fake_open_orders)
- ctx = StrategyContext(id="inst-1", account_id="acct-1", client_id="client-1", mode="active")
- result = ctx.cancel_all_orders_confirmed()
- assert result["conclusive"] is False
- assert result["cleanup_status"] == "cleanup_partial"
- assert result["cancelled_order_ids"] == ["o1"]
- assert result["remaining_orders"] == []
- assert result["error"] == "cancel-all reported uncancelled orders"
- assert calls["cancel_all"] == {"account_id": "acct-1", "client_id": "client-1"}
- assert calls["open_orders"] == 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_reports_factual_capacity_not_handoff_commands():
- 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["capacity_available"] is False
- assert supervision["side_capacity"] == {"buy": True, "sell": True}
- strategy.state.update({
- "base_available": 88.0,
- "counter_available": 4.0,
- })
- supervision = strategy._supervision()
- assert supervision["inventory_pressure"] == "base_side_depleted"
- assert supervision["side_capacity"] == {"buy": True, "sell": False}
- def test_grid_supervision_exposes_adverse_side_open_orders():
- 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.60,
- "center_price": 1.45,
- "orders": [
- {"side": "sell", "price": "1.62", "amount": "10", "status": "open"},
- {"side": "sell", "price": "1.66", "amount": "5", "status": "open"},
- {"side": "buy", "price": "1.38", "amount": "7", "status": "open"},
- ],
- })
- supervision = strategy._supervision()
- assert supervision["market_bias"] == "bullish"
- assert supervision["adverse_side"] == "sell"
- assert supervision["adverse_side_open_order_count"] == 2
- assert supervision["adverse_side_open_order_notional_quote"] > 0
- assert "sell ladder exposed" in " ".join(supervision["concerns"])
- def test_dumb_trader_and_protector_supervision_reports_facts_only():
- class FakeContext:
- account_id = "acct-1"
- market_symbol = "xrpusd"
- base_currency = "XRP"
- counter_currency = "USD"
- mode = "active"
- trend = DumbStrategy(FakeContext(), {"trade_side": "buy", "order_notional_quote": 1.0})
- trend.state.update({"last_price": 1.45, "base_available": 20.0, "counter_available": 20.0, "last_order_at": 0.0})
- trend_supervision = trend._supervision()
- assert trend_supervision["trade_side"] == "buy"
- assert trend_supervision["capacity_available"] is True
- assert trend_supervision["entry_offset_pct"] == 0.003
- assert trend_supervision["chasing_risk"] in {"low", "moderate", "elevated"}
- assert "switch_readiness" not in trend_supervision
- assert "desired_companion" not in trend_supervision
- protector = ExposureStrategy(FakeContext(), {})
- protector.state.update({"last_price": 1.45, "base_available": 40.0, "counter_available": 10.0})
- protector_supervision = protector._supervision()
- assert protector_supervision["rebalance_needed"] is True
- assert protector_supervision["repair_progress"] <= 1.0
- assert "switch_readiness" not in protector_supervision
- assert "desired_companion" not in protector_supervision
- def test_exposure_protector_holds_inside_hysteresis_band(monkeypatch):
- class FakeContext:
- account_id = "acct-1"
- market_symbol = "xrpusd"
- base_currency = "XRP"
- counter_currency = "USD"
- mode = "active"
- def __init__(self):
- self.placed_orders = []
- def get_account_info(self):
- return {"balances": [{"asset_code": "XRP", "available": 9.2}, {"asset_code": "USD", "available": 10.0}]}
- def get_price(self, market):
- return {"price": 1.0}
- def get_fee_rates(self, market):
- return {"maker": 0.0, "taker": 0.004}
- def place_order(self, **kwargs):
- self.placed_orders.append(kwargs)
- return {"status": "ok", "id": f"oid-{len(self.placed_orders)}"}
- ctx = FakeContext()
- strategy = ExposureStrategy(ctx, {"rebalance_target_ratio": 0.5, "rebalance_step_ratio": 0.15, "balance_tolerance": 0.05, "cooldown_ticks": 0, "min_rebalance_seconds": 0, "trail_distance_pct": 0.03})
- strategy.state["last_rebalance_side"] = "sell"
- strategy.state["last_order_at"] = 0
- monkeypatch.setattr(strategy, "_refresh_regimes", lambda: None)
- result = strategy.on_tick({})
- assert result["action"] == "hold"
- assert result["reason"] == "within rebalance hysteresis"
- assert ctx.placed_orders == []
- def test_grid_apply_policy_keeps_explicit_grid_levels():
- class FakeContext:
- account_id = "acct-1"
- market_symbol = "xrpusd"
- base_currency = "XRP"
- counter_currency = "USD"
- mode = "active"
- strategy = GridStrategy(FakeContext(), {"grid_levels": 5, "policy": {"risk_posture": "normal"}})
- strategy.apply_policy()
- assert strategy.config["grid_levels"] == 5
- assert strategy.state["policy_derived"]["grid_levels"] == 5
- def test_grid_seed_keeps_other_side_when_one_side_fails(monkeypatch):
- class FakeContext:
- base_currency = "XRP"
- counter_currency = "USD"
- market_symbol = "xrpusd"
- minimum_order_value = 10.0
- mode = "active"
- def __init__(self):
- self.attempts = []
- self.buy_attempts = 0
- self.sell_attempts = 0
- def get_fee_rates(self, market):
- return {"maker": 0.0, "taker": 0.0}
- def suggest_order_amount(self, **kwargs):
- return 10.0
- def place_order(self, **kwargs):
- self.attempts.append(kwargs)
- if kwargs["side"] == "buy":
- self.buy_attempts += 1
- if self.buy_attempts == 3:
- raise RuntimeError("insufficient USD")
- elif kwargs["side"] == "sell":
- self.sell_attempts += 1
- return {"status": "ok", "id": f"{kwargs['side']}-{len(self.attempts)}"}
- ctx = FakeContext()
- strategy = GridStrategy(ctx, {"grid_levels": 5, "order_call_delay_ms": 0, "enable_trend_guard": False, "fee_rate": 0.0})
- strategy.state["center_price"] = 100.0
- monkeypatch.setattr(strategy, "_supported_levels", lambda side, center, min_notional: 5)
- monkeypatch.setattr(strategy, "_refresh_balance_snapshot", lambda: None)
- strategy._place_grid(100.0)
- orders = strategy.state["orders"]
- assert ctx.buy_attempts == 5
- assert ctx.sell_attempts == 5
- assert len([o for o in orders if o["side"] == "buy"]) == 4
- assert len([o for o in orders if o["side"] == "sell"]) == 5
- assert any("partial success" in line for line in (strategy.state.get("debug_log") or [])) or strategy.state.get("last_error") == "insufficient USD"
- def test_grid_skips_rebuild_when_balance_refresh_fails(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):
- raise RuntimeError("Bitstamp auth breaker active, retry later")
- 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": 5, "order_call_delay_ms": 0, "enable_trend_guard": False, "fee_rate": 0.004})
- strategy.state["center_price"] = 1.4397
- strategy.state["seeded"] = True
- strategy.state["orders"] = [{"side": "buy", "price": 1.43, "amount": 10.0, "id": "o1"}]
- strategy.state["order_ids"] = ["o1"]
- monkeypatch.setattr(strategy, "_sync_open_orders_state", lambda: [{"side": "buy", "price": 1.43, "amount": 10.0, "id": "o1"}])
- monkeypatch.setattr(strategy, "_price", lambda: 1.4397)
- monkeypatch.setattr(strategy, "_refresh_regimes", lambda: None)
- result = strategy.on_tick({})
- assert result["action"] == "hold"
- assert result["reason"] == "balance refresh unavailable"
- assert ctx.cancelled_all == 0
- assert ctx.placed_orders == []
- def test_grid_skips_shape_rebuild_when_balance_reads_turn_inconclusive(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 = []
- self.calls = 0
- def get_fee_rates(self, market):
- return {"maker": 0.0, "taker": 0.004}
- def get_account_info(self):
- self.calls += 1
- if self.calls == 1:
- return {
- "balances": [
- {"asset_code": "USD", "available": 41.29},
- {"asset_code": "XRP", "available": 9.98954},
- ]
- }
- raise RuntimeError("Bitstamp auth breaker active, retry later")
- 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.3285
- strategy.state["seeded"] = True
- 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"] == "hold"
- assert ctx.cancelled_all == 0
- assert ctx.placed_orders == []
- 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: True)
- 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 cancel_all_orders_confirmed(self):
- return {"conclusive": True, "error": None, "cleanup_status": "cleanup_confirmed", "cancelled_order_ids": []}
- 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_recenter_preserves_tracked_orders_when_cancel_is_inconclusive():
- class FakeContext:
- base_currency = "XRP"
- counter_currency = "USD"
- market_symbol = "xrpusd"
- minimum_order_value = 10.0
- mode = "active"
- def __init__(self):
- self.placed_orders = []
- def cancel_all_orders_confirmed(self):
- return {
- "conclusive": False,
- "error": "auth breaker active",
- "cleanup_status": "cleanup_partial",
- "cancelled_order_ids": ["o1"],
- }
- 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):
- self.placed_orders.append(kwargs)
- return {"status": "ok", "id": "oid-1"}
- ctx = FakeContext()
- strategy = GridStrategy(ctx, {})
- strategy.state["center_price"] = 100.0
- strategy.state["orders"] = [{"id": "o1"}, {"id": "o2"}]
- strategy.state["order_ids"] = ["o1", "o2"]
- strategy.state["open_order_count"] = 2
- strategy._recenter_and_rebuild_from_price(160.0, "test recenter")
- assert strategy.state["center_price"] == 100.0
- assert strategy.state["orders"] == [{"id": "o2"}]
- assert strategy.state["order_ids"] == ["o2"]
- assert strategy.state["open_order_count"] == 1
- assert strategy.state["cleanup_status"] == "cleanup_partial"
- assert strategy.state["last_action"] == "test recenter cleanup pending"
- assert ctx.placed_orders == []
- 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 cancel_all_orders_confirmed(self):
- self.cancelled = True
- return {"conclusive": True, "error": None, "cleanup_status": "cleanup_confirmed", "cancelled_order_ids": ["o1"]}
- 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["cleanup_status"] == "cleanup_confirmed"
- assert strategy.state["last_action"] == "stopped"
- def test_grid_stop_preserves_tracked_orders_when_cancel_is_inconclusive():
- class FakeContext:
- base_currency = "XRP"
- counter_currency = "USD"
- market_symbol = "xrpusd"
- minimum_order_value = 10.0
- mode = "active"
- def cancel_all_orders_confirmed(self):
- return {
- "conclusive": False,
- "error": "auth breaker active",
- "cleanup_status": "cleanup_failed",
- "cancelled_order_ids": [],
- }
- 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.state["orders"] == [{"id": "o1"}]
- assert strategy.state["order_ids"] == ["o1"]
- assert strategy.state["open_order_count"] == 1
- assert strategy.state["cleanup_status"] == "cleanup_failed"
- assert strategy.state["last_action"] == "stop cleanup pending"
- assert strategy.state["last_error"] == "auth breaker active"
- def test_grid_observe_mode_preserves_tracked_orders_when_cancel_is_inconclusive(monkeypatch):
- class FakeContext:
- base_currency = "XRP"
- counter_currency = "USD"
- market_symbol = "xrpusd"
- minimum_order_value = 10.0
- mode = "observe"
- def cancel_all_orders_confirmed(self):
- return {
- "conclusive": False,
- "error": "auth breaker active",
- "cleanup_status": "cleanup_failed",
- "cancelled_order_ids": [],
- }
- def get_fee_rates(self, market):
- return {"maker": 0.0, "taker": 0.0}
- def get_account_info(self):
- return {"balances": [{"asset_code": "USD", "available": 50.0}, {"asset_code": "XRP", "available": 5.0}]}
- strategy = GridStrategy(FakeContext(), {})
- strategy.state["center_price"] = 1.42
- strategy.state["seeded"] = True
- strategy.state["orders"] = [{"id": "o1", "side": "buy", "price": 1.4, "amount": 10.0}]
- strategy.state["order_ids"] = ["o1"]
- strategy.state["open_order_count"] = 1
- monkeypatch.setattr(strategy, "_price", lambda: 1.42)
- monkeypatch.setattr(strategy, "_refresh_regimes", lambda: None)
- monkeypatch.setattr(strategy, "_refresh_balance_snapshot", lambda: True)
- monkeypatch.setattr(strategy, "_sync_open_orders_state", lambda: [{"id": "o1", "side": "buy", "price": 1.4, "amount": 10.0}])
- result = strategy.on_tick({})
- assert result["action"] == "observe"
- assert result["cleanup_pending"] is True
- assert strategy.state["orders"] == [{"id": "o1", "side": "buy", "price": 1.4, "amount": 10.0}]
- assert strategy.state["order_ids"] == ["o1"]
- assert strategy.state["open_order_count"] == 1
- assert strategy.state["cleanup_status"] == "cleanup_failed"
- assert strategy.state["last_action"] == "observe cleanup pending"
- assert strategy.state["last_error"] == "auth breaker active"
- 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_dumb_trader_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 place_order(self, **kwargs):
- return {"ok": True, "order": kwargs}
- def get_strategy_snapshot(self):
- return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
- strat = DumbStrategy(FakeContext(), {"trade_side": "buy", "order_notional_quote": 1.5})
- strat.apply_policy()
- report = strat.report()
- assert report["fit"]["risk_profile"] == "neutral"
- assert strat.state["policy_derived"]["order_notional_quote"] > 0
- def test_dumb_trader_buys_on_configured_side_without_regime_input():
- 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 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 float(kwargs.get("quote_notional") or 0.0) / float(kwargs.get("price") or 1.0)
- def get_strategy_snapshot(self):
- return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
- ctx = FakeContext()
- strat = DumbStrategy(ctx, {"trade_side": "buy", "order_notional_quote": 20.0})
- result = strat.on_tick({})
- assert result["action"] == "buy"
- assert ctx.orders[-1]["side"] == "buy"
- assert ctx.orders[-1]["amount"] == 20.0 / 1.2
- assert strat.state["last_action"] == "buy_dumb"
- def test_dumb_trader_sells_on_configured_side_without_regime_input():
- 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 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 float(kwargs.get("quote_notional") or 0.0) / float(kwargs.get("price") or 1.0)
- def get_strategy_snapshot(self):
- return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
- ctx = FakeContext()
- strat = DumbStrategy(ctx, {"trade_side": "sell", "order_notional_quote": 20.0})
- result = strat.on_tick({})
- assert result["action"] == "sell"
- assert ctx.orders[-1]["side"] == "sell"
- assert ctx.orders[-1]["amount"] == 20.0 / 1.2
- assert strat.state["last_action"] == "sell_dumb"
- def test_dumb_trader_buy_only_ignores_bear_regime():
- class FakeContext:
- id = "s-buy-only"
- 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 10.0
- def get_strategy_snapshot(self):
- return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
- ctx = FakeContext()
- strat = DumbStrategy(ctx, {"trade_side": "buy", "order_notional_quote": 20.0})
- result = strat.on_tick({})
- assert result["action"] == "buy"
- assert ctx.orders[-1]["side"] == "buy"
- assert strat.state["last_action"] == "buy_dumb"
- def test_dumb_trader_sell_only_ignores_bull_regime():
- class FakeContext:
- id = "s-sell-only"
- 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 = DumbStrategy(ctx, {"trade_side": "sell", "order_notional_quote": 20.0})
- result = strat.on_tick({})
- assert result["action"] == "sell"
- assert ctx.orders[-1]["side"] == "sell"
- assert strat.state["last_action"] == "sell_dumb"
- def test_dumb_trader_policy_does_not_override_explicit_order_notional_quote():
- 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_strategy_snapshot(self):
- return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
- strat = DumbStrategy(FakeContext(), {"trade_side": "buy", "order_notional_quote": 10.5})
- strat.apply_policy()
- assert strat.config["order_notional_quote"] == 10.5
- assert strat.state["policy_derived"]["order_notional_quote"] == 10.5
- def test_dumb_trader_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_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 = DumbStrategy(ctx, {"trade_side": "buy", "order_notional_quote": 10.5, "dust_collect": True})
- strat.on_tick({})
- assert ctx.fee_calls == ["xrpusd"]
- assert ctx.suggest_calls[-1]["fee_rate"] == 0.0025
- assert ctx.suggest_calls[-1]["dust_collect"] is True
- def test_grid_sizing_helper_receives_quote_controls_and_dust_collect():
- class FakeContext:
- base_currency = "XRP"
- counter_currency = "USD"
- market_symbol = "xrpusd"
- minimum_order_value = 10.0
- mode = "active"
- def __init__(self):
- self.suggest_calls = []
- def get_fee_rates(self, market_symbol=None):
- return {"maker": 0.001, "taker": 0.004}
- def suggest_order_amount(self, **kwargs):
- self.suggest_calls.append(kwargs)
- return 7.0
- ctx = FakeContext()
- strategy = GridStrategy(
- ctx,
- {
- "grid_levels": 3,
- "order_notional_quote": 11.0,
- "max_order_notional_quote": 12.0,
- "dust_collect": True,
- },
- )
- amount = strategy._suggest_amount("buy", 1.5, 3, 10.0)
- assert amount == 7.0
- assert ctx.suggest_calls[-1]["fee_rate"] == 0.004
- assert ctx.suggest_calls[-1]["quote_notional"] == 11.0
- assert ctx.suggest_calls[-1]["max_notional_per_order"] == 12.0
- assert ctx.suggest_calls[-1]["dust_collect"] is True
- assert ctx.suggest_calls[-1]["levels"] == 3
- def test_dumb_trader_buy_uses_requested_notional_even_with_balance_target_configured():
- class FakeContext:
- id = "s-buy-clamp"
- account_id = "acct-1"
- client_id = "cid-1"
- mode = "active"
- market_symbol = "xrpusd"
- base_currency = "XRP"
- counter_currency = "USD"
- minimum_order_value = 0.5
- def __init__(self):
- self.orders = []
- def get_price(self, symbol):
- return {"price": 1.0}
- def get_fee_rates(self, market_symbol=None):
- return {"maker": 0.0, "taker": 0.0}
- def suggest_order_amount(self, **kwargs):
- return float(kwargs.get("quote_notional") or 0.0) / float(kwargs.get("price") or 1.0)
- 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": 6.0}, {"asset_code": "XRP", "available": 4.0}]}
- def get_strategy_snapshot(self):
- return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
- ctx = FakeContext()
- strat = DumbStrategy(ctx, {"trade_side": "buy", "order_notional_quote": 3.0, "balance_target": 0.5})
- result = strat.on_tick({})
- assert result["action"] == "buy"
- assert ctx.orders[-1]["amount"] == 3.0
- def test_dumb_trader_sell_uses_requested_notional_even_with_balance_target_configured():
- class FakeContext:
- id = "s-sell-clamp"
- account_id = "acct-1"
- client_id = "cid-1"
- mode = "active"
- market_symbol = "xrpusd"
- base_currency = "XRP"
- counter_currency = "USD"
- minimum_order_value = 0.5
- def __init__(self):
- self.orders = []
- def get_price(self, symbol):
- return {"price": 1.0}
- def get_fee_rates(self, market_symbol=None):
- return {"maker": 0.0, "taker": 0.0}
- def suggest_order_amount(self, **kwargs):
- return float(kwargs.get("quote_notional") or 0.0) / float(kwargs.get("price") or 1.0)
- 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": 3.0}, {"asset_code": "XRP", "available": 7.0}]}
- def get_strategy_snapshot(self):
- return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
- ctx = FakeContext()
- strat = DumbStrategy(ctx, {"trade_side": "sell", "order_notional_quote": 5.0, "balance_target": 0.5})
- result = strat.on_tick({})
- assert result["action"] == "sell"
- assert ctx.orders[-1]["amount"] == 5.0
- def test_dumb_trader_sell_holds_sub_minimum_order():
- class FakeContext:
- id = "s-sell-min"
- account_id = "acct-1"
- client_id = "cid-1"
- mode = "active"
- market_symbol = "solusd"
- base_currency = "SOL"
- counter_currency = "USD"
- minimum_order_value = 1.0
- def __init__(self):
- self.orders = []
- def get_price(self, symbol):
- return {"price": 86.20062}
- def get_fee_rates(self, market_symbol=None):
- return {"maker": 0.0, "taker": 0.0}
- def suggest_order_amount(self, **kwargs):
- return 0.001
- 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.0}, {"asset_code": "SOL", "available": 0.00447}]}
- def get_strategy_snapshot(self):
- return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
- ctx = FakeContext()
- strat = DumbStrategy(ctx, {"trade_side": "sell", "order_notional_quote": 5.0, "balance_target": 1.0})
- result = strat.on_tick({})
- assert result["action"] == "hold"
- assert result["reason"] == "no usable size"
- assert ctx.orders == []
- def test_dumb_trader_holds_when_live_sizing_reports_no_affordable_sell():
- class FakeContext:
- id = "s-sell-no-funds"
- account_id = "acct-1"
- client_id = "cid-1"
- mode = "active"
- market_symbol = "solusd"
- base_currency = "SOL"
- counter_currency = "USD"
- minimum_order_value = 0.5
- def __init__(self):
- self.orders = []
- def get_price(self, symbol):
- return {"price": 86.69}
- def get_fee_rates(self, market_symbol=None):
- return {"maker": 0.0, "taker": 0.0}
- def suggest_order_amount(self, **kwargs):
- return 0.0
- 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.0}, {"asset_code": "SOL", "available": 0.00447}]}
- def get_strategy_snapshot(self):
- return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
- ctx = FakeContext()
- strat = DumbStrategy(ctx, {"trade_side": "sell", "order_notional_quote": 11.0, "dust_collect": True})
- result = strat.on_tick({})
- assert result["action"] == "hold"
- assert result["reason"] == "no usable size"
- assert ctx.orders == []
- def test_dumb_trader_holds_when_balance_refresh_fails_after_restart():
- class FakeContext:
- id = "s-restart-hold"
- account_id = "acct-1"
- client_id = "cid-1"
- mode = "active"
- market_symbol = "solusd"
- base_currency = "SOL"
- counter_currency = "USD"
- minimum_order_value = 1.0
- def __init__(self):
- self.orders = []
- def get_price(self, symbol):
- return {"price": 86.51}
- def get_fee_rates(self, market_symbol=None):
- return {"maker": 0.0, "taker": 0.0}
- def get_account_info(self):
- raise RuntimeError("Bitstamp auth breaker active, retry later")
- def suggest_order_amount(self, **kwargs):
- raise AssertionError("should not size an order after balance refresh failure")
- def place_order(self, **kwargs):
- self.orders.append(kwargs)
- return {"ok": True, "order": kwargs}
- def get_strategy_snapshot(self):
- return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
- ctx = FakeContext()
- strat = DumbStrategy(
- ctx,
- {
- "trade_side": "sell",
- "order_notional_quote": 5.0,
- "dust_collect": True,
- },
- )
- strat.state["base_available"] = 0.127153
- strat.state["counter_available"] = 0.0
- result = strat.on_tick({})
- assert result["action"] == "hold"
- assert result["reason"] == "balance refresh unavailable"
- assert strat.state["balance_snapshot_ok"] is False
- assert strat.state["base_available"] == 0.0
- assert ctx.orders == []
- def test_dumb_trader_holds_when_trade_side_is_symmetrical():
- class FakeContext:
- id = "s-target-hold"
- account_id = "acct-1"
- client_id = "cid-1"
- mode = "active"
- market_symbol = "xrpusd"
- base_currency = "XRP"
- counter_currency = "USD"
- minimum_order_value = 0.5
- def get_price(self, symbol):
- return {"price": 1.0}
- def get_fee_rates(self, market_symbol=None):
- return {"maker": 0.0, "taker": 0.0}
- def suggest_order_amount(self, **kwargs):
- return 10.0
- def get_account_info(self):
- return {"balances": [{"asset_code": "USD", "available": 5.0}, {"asset_code": "XRP", "available": 5.0}]}
- def get_strategy_snapshot(self):
- return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
- strat = DumbStrategy(FakeContext(), {"trade_side": "both", "order_notional_quote": 3.0, "balance_target": 0.5})
- result = strat.on_tick({})
- assert result["action"] == "hold"
- assert result["reason"] == "trade_side must be buy or sell"
- def test_cap_amount_to_balance_target_caps_sell_to_live_base():
- amount = cap_amount_to_balance_target(
- suggested_amount=0.127226,
- side="sell",
- price=86.20062,
- fee_rate=0.0,
- balance_target=1.0,
- base_available=0.00447,
- counter_available=0.0,
- min_notional=0.0,
- )
- assert amount == 0.00447
- def test_cap_amount_to_balance_target_rejects_sell_below_min_notional():
- amount = cap_amount_to_balance_target(
- suggested_amount=0.127226,
- side="sell",
- price=86.20062,
- fee_rate=0.0,
- balance_target=1.0,
- base_available=0.00447,
- counter_available=0.0,
- min_notional=1.0,
- )
- assert amount == 0.0
- def test_dumb_trader_ignores_balance_target_and_keeps_size():
- class FakeContext:
- id = "s-target-open"
- account_id = "acct-1"
- client_id = "cid-1"
- mode = "active"
- market_symbol = "xrpusd"
- base_currency = "XRP"
- counter_currency = "USD"
- minimum_order_value = 0.5
- def __init__(self):
- self.orders = []
- def get_price(self, symbol):
- return {"price": 1.0}
- def get_fee_rates(self, market_symbol=None):
- return {"maker": 0.0, "taker": 0.0}
- def suggest_order_amount(self, **kwargs):
- return float(kwargs.get("quote_notional") or 0.0) / float(kwargs.get("price") or 1.0)
- 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": 6.0}, {"asset_code": "XRP", "available": 4.0}]}
- def get_strategy_snapshot(self):
- return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
- ctx = FakeContext()
- strat = DumbStrategy(ctx, {"trade_side": "buy", "order_notional_quote": 3.0, "balance_target": 0.5})
- result = strat.on_tick({})
- assert result["action"] == "buy"
- assert ctx.orders[-1]["amount"] == 3.0
- def test_exposure_protector_buy_sizing_respects_fee_when_min_order_quote_is_unaffordable():
- class FakeContext:
- account_id = "acct-1"
- client_id = "cid-1"
- mode = "active"
- market_symbol = "xrpusd"
- base_currency = "XRP"
- counter_currency = "USD"
- def get_fee_rates(self, market_symbol=None):
- return {"maker": 0.1, "taker": 0.2}
- strategy = ExposureStrategy(
- FakeContext(),
- {
- "rebalance_target_ratio": 0.9,
- "rebalance_step_ratio": 1.0,
- "balance_tolerance": 0.0,
- "min_order_notional_quote": 10.0,
- },
- )
- strategy.state["base_available"] = 0.0
- strategy.state["counter_available"] = 10.0
- amount = strategy._suggest_amount("buy", 1.0)
- assert amount == 0.0
|