test_strategies.py 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534
  1. from __future__ import annotations
  2. from pathlib import Path
  3. from tempfile import TemporaryDirectory
  4. from fastapi.testclient import TestClient
  5. from src.trader_mcp import strategy_registry, strategy_store
  6. from src.trader_mcp.server import app
  7. from src.trader_mcp.strategy_context import StrategyContext
  8. from src.trader_mcp.strategy_sizing import cap_amount_to_balance_target
  9. from src.trader_mcp.strategy_sdk import Strategy as BaseStrategy
  10. from strategies.exposure_protector import Strategy as ExposureStrategy
  11. from strategies.dumb_trader import Strategy as DumbStrategy
  12. from strategies.grid_trader import Strategy as GridStrategy
  13. STRATEGY_CODE = '''
  14. from src.trader_mcp.strategy_sdk import Strategy
  15. class Strategy(Strategy):
  16. def init(self):
  17. return {"started": True, "config_copy": dict(self.config)}
  18. '''
  19. def test_strategies_endpoints_roundtrip():
  20. with TemporaryDirectory() as tmpdir:
  21. strategy_store.DB_PATH = Path(tmpdir) / "trader_mcp.sqlite3"
  22. from src.trader_mcp import strategy_registry
  23. strategy_registry.STRATEGIES_DIR = Path(tmpdir) / "strategies"
  24. strategy_registry.STRATEGIES_DIR.mkdir()
  25. (strategy_registry.STRATEGIES_DIR / "demo.py").write_text(STRATEGY_CODE)
  26. client = TestClient(app)
  27. r = client.get("/strategies")
  28. assert r.status_code == 200
  29. body = r.json()
  30. assert "available" in body
  31. assert "configured" in body
  32. r = client.post(
  33. "/strategies",
  34. json={
  35. "id": "demo-1",
  36. "strategy_type": "demo",
  37. "account_id": "acct-1",
  38. "client_id": "strategy:test",
  39. "mode": "observe",
  40. "config": {"risk": 0.01},
  41. },
  42. )
  43. assert r.status_code == 200
  44. assert r.json()["id"] == "demo-1"
  45. r = client.get("/strategies")
  46. assert any(item["id"] == "demo-1" for item in r.json()["configured"])
  47. r = client.delete("/strategies/demo-1")
  48. assert r.status_code == 200
  49. assert r.json()["ok"] is True
  50. def test_strategy_context_binds_identity(monkeypatch):
  51. calls = {}
  52. def fake_place_order(arguments):
  53. calls["place_order"] = arguments
  54. return {"ok": True}
  55. def fake_open_orders(account_id, client_id=None):
  56. calls["open_orders"] = {"account_id": account_id, "client_id": client_id}
  57. return {"ok": True}
  58. def fake_cancel_all(account_id, client_id=None):
  59. calls["cancel_all"] = {"account_id": account_id, "client_id": client_id}
  60. return {"ok": True}
  61. monkeypatch.setattr("src.trader_mcp.strategy_context.place_order", fake_place_order)
  62. monkeypatch.setattr("src.trader_mcp.strategy_context.list_open_orders", fake_open_orders)
  63. monkeypatch.setattr("src.trader_mcp.strategy_context.cancel_all_orders", fake_cancel_all)
  64. ctx = StrategyContext(id="inst-1", account_id="acct-1", client_id="client-1", mode="active")
  65. ctx.place_order(side="sell", market="xrpusd", order_type="limit", amount="10", price="2")
  66. ctx.get_open_orders()
  67. ctx.cancel_all_orders()
  68. assert calls["place_order"]["account_id"] == "acct-1"
  69. assert calls["place_order"]["client_id"] == "client-1"
  70. assert calls["open_orders"] == {"account_id": "acct-1", "client_id": "client-1"}
  71. assert calls["cancel_all"] == {"account_id": "acct-1", "client_id": "client-1"}
  72. def test_strategy_context_cancel_all_orders_confirmed_after_empty_followup(monkeypatch):
  73. calls = {"open_orders": 0}
  74. def fake_cancel_all(account_id, client_id=None):
  75. calls["cancel_all"] = {"account_id": account_id, "client_id": client_id}
  76. return {"ok": True, "cancelled": [{"ok": True, "order_id": "o1"}]}
  77. def fake_open_orders(account_id, client_id=None):
  78. calls["open_orders"] += 1
  79. return {"orders": []}
  80. monkeypatch.setattr("src.trader_mcp.strategy_context.cancel_all_orders", fake_cancel_all)
  81. monkeypatch.setattr("src.trader_mcp.strategy_context.list_open_orders", fake_open_orders)
  82. ctx = StrategyContext(id="inst-1", account_id="acct-1", client_id="client-1", mode="active")
  83. result = ctx.cancel_all_orders_confirmed()
  84. assert result["conclusive"] is True
  85. assert result["cleanup_status"] == "cleanup_confirmed"
  86. assert result["cancelled_order_ids"] == ["o1"]
  87. assert result["remaining_orders"] == []
  88. assert result["error"] is None
  89. assert calls["cancel_all"] == {"account_id": "acct-1", "client_id": "client-1"}
  90. assert calls["open_orders"] == 1
  91. def test_strategy_context_cancel_all_orders_confirmed_preserves_inconclusive_failure(monkeypatch):
  92. calls = {"open_orders": 0}
  93. def fake_cancel_all(account_id, client_id=None):
  94. raise RuntimeError("auth breaker active")
  95. def fake_open_orders(account_id, client_id=None):
  96. calls["open_orders"] += 1
  97. return {"orders": [{"id": "o1"}]}
  98. monkeypatch.setattr("src.trader_mcp.strategy_context.cancel_all_orders", fake_cancel_all)
  99. monkeypatch.setattr("src.trader_mcp.strategy_context.list_open_orders", fake_open_orders)
  100. ctx = StrategyContext(id="inst-1", account_id="acct-1", client_id="client-1", mode="active")
  101. result = ctx.cancel_all_orders_confirmed()
  102. assert result["conclusive"] is False
  103. assert result["cleanup_status"] == "cleanup_failed"
  104. assert result["cancelled_order_ids"] == []
  105. assert result["remaining_orders"] == [{"id": "o1"}]
  106. assert result["error"] == "auth breaker active"
  107. assert calls["open_orders"] == 1
  108. def test_strategy_context_cancel_all_orders_confirmed_keeps_partial_reply_inconclusive(monkeypatch):
  109. calls = {"open_orders": 0}
  110. def fake_cancel_all(account_id, client_id=None):
  111. calls["cancel_all"] = {"account_id": account_id, "client_id": client_id}
  112. return {
  113. "ok": True,
  114. "cancelled": [
  115. {"ok": True, "order_id": "o1"},
  116. {"ok": False, "order_id": "o2", "status": "deferred", "error": "auth breaker active"},
  117. ],
  118. }
  119. def fake_open_orders(account_id, client_id=None):
  120. calls["open_orders"] += 1
  121. return {"orders": []}
  122. monkeypatch.setattr("src.trader_mcp.strategy_context.cancel_all_orders", fake_cancel_all)
  123. monkeypatch.setattr("src.trader_mcp.strategy_context.list_open_orders", fake_open_orders)
  124. ctx = StrategyContext(id="inst-1", account_id="acct-1", client_id="client-1", mode="active")
  125. result = ctx.cancel_all_orders_confirmed()
  126. assert result["conclusive"] is False
  127. assert result["cleanup_status"] == "cleanup_partial"
  128. assert result["cancelled_order_ids"] == ["o1"]
  129. assert result["remaining_orders"] == []
  130. assert result["error"] == "cancel-all reported uncancelled orders"
  131. assert calls["cancel_all"] == {"account_id": "acct-1", "client_id": "client-1"}
  132. assert calls["open_orders"] == 1
  133. def test_stop_loss_strategy_loads_with_aligned_regime_config(tmp_path):
  134. original_db = strategy_store.DB_PATH
  135. original_dir = strategy_registry.STRATEGIES_DIR
  136. try:
  137. strategy_store.DB_PATH = tmp_path / "trader_mcp.sqlite3"
  138. strategy_registry.STRATEGIES_DIR = tmp_path / "strategies"
  139. strategy_registry.STRATEGIES_DIR.mkdir()
  140. (strategy_registry.STRATEGIES_DIR / "grid_trader.py").write_text((Path(__file__).resolve().parents[1] / "strategies" / "grid_trader.py").read_text())
  141. (strategy_registry.STRATEGIES_DIR / "exposure_protector.py").write_text((Path(__file__).resolve().parents[1] / "strategies" / "exposure_protector.py").read_text())
  142. grid_defaults = strategy_registry.get_strategy_default_config("grid_trader")
  143. stop_defaults = strategy_registry.get_strategy_default_config("exposure_protector")
  144. assert grid_defaults["trade_sides"] == "both"
  145. assert grid_defaults["grid_step_pct"] == 0.012
  146. assert stop_defaults["trail_distance_pct"] == 0.03
  147. assert stop_defaults["rebalance_target_ratio"] == 0.5
  148. assert stop_defaults["min_rebalance_seconds"] == 180
  149. assert stop_defaults["min_price_move_pct"] == 0.005
  150. finally:
  151. strategy_store.DB_PATH = original_db
  152. strategy_registry.STRATEGIES_DIR = original_dir
  153. def test_grid_supervision_reports_factual_capacity_not_handoff_commands():
  154. class FakeContext:
  155. account_id = "acct-1"
  156. market_symbol = "xrpusd"
  157. base_currency = "XRP"
  158. counter_currency = "USD"
  159. mode = "active"
  160. strategy = GridStrategy(FakeContext(), {})
  161. strategy.state.update({
  162. "last_price": 1.45,
  163. "base_available": 50.0,
  164. "counter_available": 38.7,
  165. "regimes": {"1h": {"trend": {"state": "bull"}}},
  166. })
  167. supervision = strategy._supervision()
  168. assert supervision["inventory_pressure"] == "base_heavy"
  169. assert supervision["capacity_available"] is False
  170. assert supervision["side_capacity"] == {"buy": True, "sell": True}
  171. strategy.state.update({
  172. "base_available": 88.0,
  173. "counter_available": 4.0,
  174. })
  175. supervision = strategy._supervision()
  176. assert supervision["inventory_pressure"] == "base_side_depleted"
  177. assert supervision["side_capacity"] == {"buy": True, "sell": False}
  178. def test_grid_supervision_exposes_adverse_side_open_orders():
  179. class FakeContext:
  180. account_id = "acct-1"
  181. market_symbol = "xrpusd"
  182. base_currency = "XRP"
  183. counter_currency = "USD"
  184. mode = "active"
  185. strategy = GridStrategy(FakeContext(), {})
  186. strategy.state.update({
  187. "last_price": 1.60,
  188. "center_price": 1.45,
  189. "orders": [
  190. {"side": "sell", "price": "1.62", "amount": "10", "status": "open"},
  191. {"side": "sell", "price": "1.66", "amount": "5", "status": "open"},
  192. {"side": "buy", "price": "1.38", "amount": "7", "status": "open"},
  193. ],
  194. })
  195. supervision = strategy._supervision()
  196. assert supervision["market_bias"] == "bullish"
  197. assert supervision["adverse_side"] == "sell"
  198. assert supervision["adverse_side_open_order_count"] == 2
  199. assert supervision["adverse_side_open_order_notional_quote"] > 0
  200. assert "sell ladder exposed" in " ".join(supervision["concerns"])
  201. def test_dumb_trader_and_protector_supervision_reports_facts_only():
  202. class FakeContext:
  203. account_id = "acct-1"
  204. market_symbol = "xrpusd"
  205. base_currency = "XRP"
  206. counter_currency = "USD"
  207. mode = "active"
  208. trend = DumbStrategy(FakeContext(), {"trade_side": "buy", "order_notional_quote": 1.0})
  209. trend.state.update({"last_price": 1.45, "base_available": 20.0, "counter_available": 20.0, "last_order_at": 0.0})
  210. trend_supervision = trend._supervision()
  211. assert trend_supervision["trade_side"] == "buy"
  212. assert trend_supervision["capacity_available"] is True
  213. assert trend_supervision["entry_offset_pct"] == 0.003
  214. assert trend_supervision["chasing_risk"] in {"low", "moderate", "elevated"}
  215. assert "switch_readiness" not in trend_supervision
  216. assert "desired_companion" not in trend_supervision
  217. protector = ExposureStrategy(FakeContext(), {})
  218. protector.state.update({"last_price": 1.45, "base_available": 40.0, "counter_available": 10.0})
  219. protector_supervision = protector._supervision()
  220. assert protector_supervision["rebalance_needed"] is True
  221. assert protector_supervision["repair_progress"] <= 1.0
  222. assert "switch_readiness" not in protector_supervision
  223. assert "desired_companion" not in protector_supervision
  224. def test_exposure_protector_holds_inside_hysteresis_band(monkeypatch):
  225. class FakeContext:
  226. account_id = "acct-1"
  227. market_symbol = "xrpusd"
  228. base_currency = "XRP"
  229. counter_currency = "USD"
  230. mode = "active"
  231. def __init__(self):
  232. self.placed_orders = []
  233. def get_account_info(self):
  234. return {"balances": [{"asset_code": "XRP", "available": 9.2}, {"asset_code": "USD", "available": 10.0}]}
  235. def get_price(self, market):
  236. return {"price": 1.0}
  237. def get_fee_rates(self, market):
  238. return {"maker": 0.0, "taker": 0.004}
  239. def place_order(self, **kwargs):
  240. self.placed_orders.append(kwargs)
  241. return {"status": "ok", "id": f"oid-{len(self.placed_orders)}"}
  242. ctx = FakeContext()
  243. 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})
  244. strategy.state["last_rebalance_side"] = "sell"
  245. strategy.state["last_order_at"] = 0
  246. monkeypatch.setattr(strategy, "_refresh_regimes", lambda: None)
  247. result = strategy.on_tick({})
  248. assert result["action"] == "hold"
  249. assert result["reason"] == "within rebalance hysteresis"
  250. assert ctx.placed_orders == []
  251. def test_grid_apply_policy_keeps_explicit_grid_levels():
  252. class FakeContext:
  253. account_id = "acct-1"
  254. market_symbol = "xrpusd"
  255. base_currency = "XRP"
  256. counter_currency = "USD"
  257. mode = "active"
  258. strategy = GridStrategy(FakeContext(), {"grid_levels": 5, "policy": {"risk_posture": "normal"}})
  259. strategy.apply_policy()
  260. assert strategy.config["grid_levels"] == 5
  261. assert strategy.state["policy_derived"]["grid_levels"] == 5
  262. def test_grid_seed_keeps_other_side_when_one_side_fails(monkeypatch):
  263. class FakeContext:
  264. base_currency = "XRP"
  265. counter_currency = "USD"
  266. market_symbol = "xrpusd"
  267. minimum_order_value = 10.0
  268. mode = "active"
  269. def __init__(self):
  270. self.attempts = []
  271. self.buy_attempts = 0
  272. self.sell_attempts = 0
  273. def get_fee_rates(self, market):
  274. return {"maker": 0.0, "taker": 0.0}
  275. def suggest_order_amount(self, **kwargs):
  276. return 10.0
  277. def place_order(self, **kwargs):
  278. self.attempts.append(kwargs)
  279. if kwargs["side"] == "buy":
  280. self.buy_attempts += 1
  281. if self.buy_attempts == 3:
  282. raise RuntimeError("insufficient USD")
  283. elif kwargs["side"] == "sell":
  284. self.sell_attempts += 1
  285. return {"status": "ok", "id": f"{kwargs['side']}-{len(self.attempts)}"}
  286. ctx = FakeContext()
  287. strategy = GridStrategy(ctx, {"grid_levels": 5, "order_call_delay_ms": 0, "enable_trend_guard": False, "fee_rate": 0.0})
  288. strategy.state["center_price"] = 100.0
  289. monkeypatch.setattr(strategy, "_supported_levels", lambda side, center, min_notional: 5)
  290. monkeypatch.setattr(strategy, "_refresh_balance_snapshot", lambda: None)
  291. strategy._place_grid(100.0)
  292. orders = strategy.state["orders"]
  293. assert ctx.buy_attempts == 5
  294. assert ctx.sell_attempts == 5
  295. assert len([o for o in orders if o["side"] == "buy"]) == 4
  296. assert len([o for o in orders if o["side"] == "sell"]) == 5
  297. assert any("partial success" in line for line in (strategy.state.get("debug_log") or [])) or strategy.state.get("last_error") == "insufficient USD"
  298. def test_grid_skips_rebuild_when_balance_refresh_fails(monkeypatch):
  299. class FakeContext:
  300. base_currency = "XRP"
  301. counter_currency = "USD"
  302. market_symbol = "xrpusd"
  303. minimum_order_value = 10.0
  304. mode = "active"
  305. def __init__(self):
  306. self.cancelled_all = 0
  307. self.placed_orders = []
  308. def get_fee_rates(self, market):
  309. return {"maker": 0.0, "taker": 0.004}
  310. def get_account_info(self):
  311. raise RuntimeError("Bitstamp auth breaker active, retry later")
  312. def cancel_all_orders(self):
  313. self.cancelled_all += 1
  314. return {"ok": True}
  315. def suggest_order_amount(self, **kwargs):
  316. return 10.0
  317. def place_order(self, **kwargs):
  318. self.placed_orders.append(kwargs)
  319. return {"status": "ok", "id": f"oid-{len(self.placed_orders)}"}
  320. ctx = FakeContext()
  321. strategy = GridStrategy(ctx, {"grid_levels": 5, "order_call_delay_ms": 0, "enable_trend_guard": False, "fee_rate": 0.004})
  322. strategy.state["center_price"] = 1.4397
  323. strategy.state["seeded"] = True
  324. strategy.state["orders"] = [{"side": "buy", "price": 1.43, "amount": 10.0, "id": "o1"}]
  325. strategy.state["order_ids"] = ["o1"]
  326. monkeypatch.setattr(strategy, "_sync_open_orders_state", lambda: [{"side": "buy", "price": 1.43, "amount": 10.0, "id": "o1"}])
  327. monkeypatch.setattr(strategy, "_price", lambda: 1.4397)
  328. monkeypatch.setattr(strategy, "_refresh_regimes", lambda: None)
  329. result = strategy.on_tick({})
  330. assert result["action"] == "hold"
  331. assert result["reason"] == "balance refresh unavailable"
  332. assert ctx.cancelled_all == 0
  333. assert ctx.placed_orders == []
  334. def test_grid_skips_shape_rebuild_when_balance_reads_turn_inconclusive(monkeypatch):
  335. class FakeContext:
  336. base_currency = "XRP"
  337. counter_currency = "USD"
  338. market_symbol = "xrpusd"
  339. minimum_order_value = 10.0
  340. mode = "active"
  341. def __init__(self):
  342. self.cancelled_all = 0
  343. self.placed_orders = []
  344. self.calls = 0
  345. def get_fee_rates(self, market):
  346. return {"maker": 0.0, "taker": 0.004}
  347. def get_account_info(self):
  348. self.calls += 1
  349. if self.calls == 1:
  350. return {
  351. "balances": [
  352. {"asset_code": "USD", "available": 41.29},
  353. {"asset_code": "XRP", "available": 9.98954},
  354. ]
  355. }
  356. raise RuntimeError("Bitstamp auth breaker active, retry later")
  357. def cancel_all_orders(self):
  358. self.cancelled_all += 1
  359. return {"ok": True}
  360. def suggest_order_amount(self, **kwargs):
  361. return 10.0
  362. def place_order(self, **kwargs):
  363. self.placed_orders.append(kwargs)
  364. return {"status": "ok", "id": f"oid-{len(self.placed_orders)}"}
  365. ctx = FakeContext()
  366. strategy = GridStrategy(ctx, {"grid_levels": 2, "order_call_delay_ms": 0, "enable_trend_guard": False, "fee_rate": 0.004})
  367. strategy.state["center_price"] = 1.3285
  368. strategy.state["seeded"] = True
  369. strategy.state["orders"] = [
  370. {"side": "buy", "price": 1.3243993, "amount": 7.63, "id": "existing-buy"},
  371. {"side": "sell", "price": 1.3326007, "amount": 9.0, "id": "sell-1"},
  372. {"side": "sell", "price": 1.3367011, "amount": 9.0, "id": "sell-2"},
  373. ]
  374. strategy.state["order_ids"] = ["existing-buy", "sell-1", "sell-2"]
  375. def fake_sync_open_orders_state():
  376. live = [{"side": "sell", "price": 1.3326007, "amount": 9.0, "id": "sell-1"}]
  377. strategy.state["orders"] = live
  378. strategy.state["order_ids"] = ["sell-1"]
  379. strategy.state["open_order_count"] = 1
  380. return live
  381. monkeypatch.setattr(strategy, "_sync_open_orders_state", fake_sync_open_orders_state)
  382. monkeypatch.setattr(strategy, "_price", lambda: 1.3285)
  383. monkeypatch.setattr(strategy, "_refresh_regimes", lambda: None)
  384. monkeypatch.setattr(strategy, "_grid_refresh_paused", lambda: False)
  385. monkeypatch.setattr(strategy, "_recenter_threshold_pct", lambda: 0.5)
  386. result = strategy.on_tick({})
  387. assert result["action"] == "hold"
  388. assert ctx.cancelled_all == 0
  389. assert ctx.placed_orders == []
  390. def test_grid_missing_order_triggers_full_rebuild(monkeypatch):
  391. class FakeContext:
  392. base_currency = "XRP"
  393. counter_currency = "USD"
  394. market_symbol = "xrpusd"
  395. minimum_order_value = 10.0
  396. mode = "active"
  397. def __init__(self):
  398. self.cancelled_all = 0
  399. self.placed_orders = []
  400. def get_fee_rates(self, market):
  401. return {"maker": 0.0, "taker": 0.004}
  402. def get_account_info(self):
  403. return {
  404. "balances": [
  405. {"asset_code": "USD", "available": 13.55},
  406. {"asset_code": "XRP", "available": 22.0103},
  407. ]
  408. }
  409. def suggest_order_amount(
  410. self,
  411. *,
  412. side,
  413. price,
  414. levels,
  415. min_notional,
  416. fee_rate,
  417. max_notional_per_order=0.0,
  418. dust_collect=False,
  419. order_size=0.0,
  420. safety=0.995,
  421. ):
  422. if side == "buy":
  423. quote_available = 13.55
  424. spendable_quote = quote_available * safety
  425. quote_cap = min(spendable_quote, max_notional_per_order) if max_notional_per_order > 0 else spendable_quote
  426. if quote_cap < min_notional * (1 + fee_rate):
  427. return 0.0
  428. return quote_cap / (price * (1 + fee_rate))
  429. return 0.0
  430. def cancel_all_orders(self):
  431. self.cancelled_all += 1
  432. return {"ok": True}
  433. def place_order(self, **kwargs):
  434. self.placed_orders.append(kwargs)
  435. return {"status": "ok", "id": f"oid-{len(self.placed_orders)}"}
  436. ctx = FakeContext()
  437. strategy = GridStrategy(
  438. ctx,
  439. {
  440. "grid_levels": 2,
  441. "grid_step_pct": 0.0062,
  442. "grid_step_min_pct": 0.0033,
  443. "grid_step_max_pct": 0.012,
  444. "max_notional_per_order": 12,
  445. "order_call_delay_ms": 0,
  446. "trade_sides": "both",
  447. "debug_orders": True,
  448. "dust_collect": True,
  449. "enable_trend_guard": False,
  450. "fee_rate": 0.004,
  451. },
  452. )
  453. strategy.state["center_price"] = 1.3285
  454. strategy.state["seeded"] = True
  455. strategy.state["base_available"] = 22.0103
  456. strategy.state["counter_available"] = 13.55
  457. strategy.state["orders"] = [
  458. {"side": "buy", "price": 1.3243993, "amount": 7.63, "id": "existing-buy"},
  459. {"side": "sell", "price": 1.3326007, "amount": 9.0, "id": "sell-1"},
  460. {"side": "sell", "price": 1.3367011, "amount": 9.0, "id": "sell-2"},
  461. ]
  462. strategy.state["order_ids"] = ["existing-buy", "sell-1", "sell-2"]
  463. def fake_sync_open_orders_state():
  464. live = [{"side": "sell", "price": 1.3326007, "amount": 9.0, "id": "sell-1"}]
  465. strategy.state["orders"] = live
  466. strategy.state["order_ids"] = ["sell-1"]
  467. strategy.state["open_order_count"] = 1
  468. return live
  469. monkeypatch.setattr(strategy, "_sync_open_orders_state", fake_sync_open_orders_state)
  470. monkeypatch.setattr(strategy, "_price", lambda: 1.3285)
  471. monkeypatch.setattr(strategy, "_refresh_regimes", lambda: None)
  472. monkeypatch.setattr(strategy, "_grid_refresh_paused", lambda: False)
  473. monkeypatch.setattr(strategy, "_recenter_threshold_pct", lambda: 0.5)
  474. result = strategy.on_tick({})
  475. assert result["action"] in {"seed", "reseed"}
  476. assert ctx.cancelled_all == 1
  477. assert len(ctx.placed_orders) > 0
  478. assert strategy.state["last_action"] == "reseeded"
  479. def test_grid_side_imbalance_triggers_full_rebuild(monkeypatch):
  480. class FakeContext:
  481. base_currency = "XRP"
  482. counter_currency = "USD"
  483. market_symbol = "xrpusd"
  484. minimum_order_value = 10.0
  485. mode = "active"
  486. def __init__(self):
  487. self.cancelled_all = 0
  488. self.placed_orders = []
  489. def get_fee_rates(self, market):
  490. return {"maker": 0.0, "taker": 0.004}
  491. def get_account_info(self):
  492. return {"balances": [{"asset_code": "USD", "available": 41.29}, {"asset_code": "XRP", "available": 9.98954}]}
  493. def cancel_all_orders(self):
  494. self.cancelled_all += 1
  495. return {"ok": True}
  496. def suggest_order_amount(self, **kwargs):
  497. return 10.0
  498. def place_order(self, **kwargs):
  499. self.placed_orders.append(kwargs)
  500. return {"status": "ok", "id": f"oid-{len(self.placed_orders)}"}
  501. ctx = FakeContext()
  502. strategy = GridStrategy(ctx, {"grid_levels": 2, "order_call_delay_ms": 0, "enable_trend_guard": False, "fee_rate": 0.004})
  503. strategy.state["center_price"] = 1.3907
  504. strategy.state["seeded"] = True
  505. strategy.state["orders"] = [{"side": "buy", "price": 1.3800, "amount": 10.0, "id": "o1"} for _ in range(5)]
  506. strategy.state["order_ids"] = [f"o{i}" for i in range(5)]
  507. def fake_sync_open_orders_state():
  508. live = [{"side": "buy", "price": 1.3800, "amount": 10.0, "id": f"o{i}"} for i in range(5)]
  509. strategy.state["orders"] = live
  510. strategy.state["order_ids"] = [f"o{i}" for i in range(5)]
  511. strategy.state["open_order_count"] = 5
  512. return live
  513. monkeypatch.setattr(strategy, "_sync_open_orders_state", fake_sync_open_orders_state)
  514. monkeypatch.setattr(strategy, "_refresh_balance_snapshot", lambda: True)
  515. monkeypatch.setattr(strategy, "_price", lambda: 1.3915)
  516. monkeypatch.setattr(strategy, "_refresh_regimes", lambda: None)
  517. monkeypatch.setattr(strategy, "_grid_refresh_paused", lambda: False)
  518. monkeypatch.setattr(strategy, "_recenter_threshold_pct", lambda: 0.5)
  519. result = strategy.on_tick({})
  520. assert result["action"] in {"seed", "reseed"}
  521. assert ctx.cancelled_all == 1
  522. assert len(ctx.placed_orders) > 0
  523. def test_grid_recenters_exactly_on_live_price():
  524. class FakeContext:
  525. base_currency = "XRP"
  526. counter_currency = "USD"
  527. market_symbol = "xrpusd"
  528. minimum_order_value = 10.0
  529. mode = "active"
  530. def cancel_all_orders(self):
  531. return {"ok": True}
  532. def cancel_all_orders_confirmed(self):
  533. return {"conclusive": True, "error": None, "cleanup_status": "cleanup_confirmed", "cancelled_order_ids": []}
  534. def get_fee_rates(self, market):
  535. return {"maker": 0.0, "taker": 0.0}
  536. def suggest_order_amount(self, **kwargs):
  537. return 0.1
  538. def place_order(self, **kwargs):
  539. return {"status": "ok", "id": "oid-1"}
  540. strategy = GridStrategy(FakeContext(), {})
  541. strategy.state["center_price"] = 100.0
  542. strategy._recenter_and_rebuild_from_price(160.0, "test recenter")
  543. assert strategy.state["center_price"] == 160.0
  544. def test_grid_recenter_preserves_tracked_orders_when_cancel_is_inconclusive():
  545. class FakeContext:
  546. base_currency = "XRP"
  547. counter_currency = "USD"
  548. market_symbol = "xrpusd"
  549. minimum_order_value = 10.0
  550. mode = "active"
  551. def __init__(self):
  552. self.placed_orders = []
  553. def cancel_all_orders_confirmed(self):
  554. return {
  555. "conclusive": False,
  556. "error": "auth breaker active",
  557. "cleanup_status": "cleanup_partial",
  558. "cancelled_order_ids": ["o1"],
  559. }
  560. def get_fee_rates(self, market):
  561. return {"maker": 0.0, "taker": 0.0}
  562. def suggest_order_amount(self, **kwargs):
  563. return 0.1
  564. def place_order(self, **kwargs):
  565. self.placed_orders.append(kwargs)
  566. return {"status": "ok", "id": "oid-1"}
  567. ctx = FakeContext()
  568. strategy = GridStrategy(ctx, {})
  569. strategy.state["center_price"] = 100.0
  570. strategy.state["orders"] = [{"id": "o1"}, {"id": "o2"}]
  571. strategy.state["order_ids"] = ["o1", "o2"]
  572. strategy.state["open_order_count"] = 2
  573. strategy._recenter_and_rebuild_from_price(160.0, "test recenter")
  574. assert strategy.state["center_price"] == 100.0
  575. assert strategy.state["orders"] == [{"id": "o2"}]
  576. assert strategy.state["order_ids"] == ["o2"]
  577. assert strategy.state["open_order_count"] == 1
  578. assert strategy.state["cleanup_status"] == "cleanup_partial"
  579. assert strategy.state["last_action"] == "test recenter cleanup pending"
  580. assert ctx.placed_orders == []
  581. def test_grid_stop_cancels_all_open_orders():
  582. class FakeContext:
  583. base_currency = "XRP"
  584. counter_currency = "USD"
  585. market_symbol = "xrpusd"
  586. minimum_order_value = 10.0
  587. mode = "active"
  588. def __init__(self):
  589. self.cancelled = False
  590. def cancel_all_orders(self):
  591. self.cancelled = True
  592. return {"ok": True}
  593. def cancel_all_orders_confirmed(self):
  594. self.cancelled = True
  595. return {"conclusive": True, "error": None, "cleanup_status": "cleanup_confirmed", "cancelled_order_ids": ["o1"]}
  596. def get_fee_rates(self, market):
  597. return {"maker": 0.0, "taker": 0.0}
  598. strategy = GridStrategy(FakeContext(), {})
  599. strategy.state["orders"] = [{"id": "o1"}]
  600. strategy.state["order_ids"] = ["o1"]
  601. strategy.state["open_order_count"] = 1
  602. strategy.on_stop()
  603. assert strategy.context.cancelled is True
  604. assert strategy.state["open_order_count"] == 0
  605. assert strategy.state["cleanup_status"] == "cleanup_confirmed"
  606. assert strategy.state["last_action"] == "stopped"
  607. def test_grid_stop_preserves_tracked_orders_when_cancel_is_inconclusive():
  608. class FakeContext:
  609. base_currency = "XRP"
  610. counter_currency = "USD"
  611. market_symbol = "xrpusd"
  612. minimum_order_value = 10.0
  613. mode = "active"
  614. def cancel_all_orders_confirmed(self):
  615. return {
  616. "conclusive": False,
  617. "error": "auth breaker active",
  618. "cleanup_status": "cleanup_failed",
  619. "cancelled_order_ids": [],
  620. }
  621. def get_fee_rates(self, market):
  622. return {"maker": 0.0, "taker": 0.0}
  623. strategy = GridStrategy(FakeContext(), {})
  624. strategy.state["orders"] = [{"id": "o1"}]
  625. strategy.state["order_ids"] = ["o1"]
  626. strategy.state["open_order_count"] = 1
  627. strategy.on_stop()
  628. assert strategy.state["orders"] == [{"id": "o1"}]
  629. assert strategy.state["order_ids"] == ["o1"]
  630. assert strategy.state["open_order_count"] == 1
  631. assert strategy.state["cleanup_status"] == "cleanup_failed"
  632. assert strategy.state["last_action"] == "stop cleanup pending"
  633. assert strategy.state["last_error"] == "auth breaker active"
  634. def test_grid_observe_mode_preserves_tracked_orders_when_cancel_is_inconclusive(monkeypatch):
  635. class FakeContext:
  636. base_currency = "XRP"
  637. counter_currency = "USD"
  638. market_symbol = "xrpusd"
  639. minimum_order_value = 10.0
  640. mode = "observe"
  641. def cancel_all_orders_confirmed(self):
  642. return {
  643. "conclusive": False,
  644. "error": "auth breaker active",
  645. "cleanup_status": "cleanup_failed",
  646. "cancelled_order_ids": [],
  647. }
  648. def get_fee_rates(self, market):
  649. return {"maker": 0.0, "taker": 0.0}
  650. def get_account_info(self):
  651. return {"balances": [{"asset_code": "USD", "available": 50.0}, {"asset_code": "XRP", "available": 5.0}]}
  652. strategy = GridStrategy(FakeContext(), {})
  653. strategy.state["center_price"] = 1.42
  654. strategy.state["seeded"] = True
  655. strategy.state["orders"] = [{"id": "o1", "side": "buy", "price": 1.4, "amount": 10.0}]
  656. strategy.state["order_ids"] = ["o1"]
  657. strategy.state["open_order_count"] = 1
  658. monkeypatch.setattr(strategy, "_price", lambda: 1.42)
  659. monkeypatch.setattr(strategy, "_refresh_regimes", lambda: None)
  660. monkeypatch.setattr(strategy, "_refresh_balance_snapshot", lambda: True)
  661. monkeypatch.setattr(strategy, "_sync_open_orders_state", lambda: [{"id": "o1", "side": "buy", "price": 1.4, "amount": 10.0}])
  662. result = strategy.on_tick({})
  663. assert result["action"] == "observe"
  664. assert result["cleanup_pending"] is True
  665. assert strategy.state["orders"] == [{"id": "o1", "side": "buy", "price": 1.4, "amount": 10.0}]
  666. assert strategy.state["order_ids"] == ["o1"]
  667. assert strategy.state["open_order_count"] == 1
  668. assert strategy.state["cleanup_status"] == "cleanup_failed"
  669. assert strategy.state["last_action"] == "observe cleanup pending"
  670. assert strategy.state["last_error"] == "auth breaker active"
  671. def test_base_strategy_report_uses_context_snapshot():
  672. class FakeContext:
  673. id = "s-1"
  674. account_id = "acct-1"
  675. market_symbol = "xrpusd"
  676. base_currency = "XRP"
  677. counter_currency = "USD"
  678. mode = "active"
  679. def get_strategy_snapshot(self):
  680. return {
  681. "identity": {"strategy_id": "s-1", "strategy_name": "Demo", "account_id": "acct-1", "market": "xrpusd", "base_currency": "XRP", "quote_currency": "USD"},
  682. "control": {"enabled_state": "on", "mode": "active"},
  683. "position": {"balances": [{"asset_code": "XRP", "available": 1.0}]},
  684. "orders": {"open_orders": [{"id": "o1"}]},
  685. "execution": {"execution_quality": "good"},
  686. }
  687. class DemoStrategy(BaseStrategy):
  688. LABEL = "Demo"
  689. report = DemoStrategy(FakeContext(), {}).report()
  690. assert report["identity"]["strategy_id"] == "s-1"
  691. assert report["control"]["mode"] == "active"
  692. assert report["position"]["open_orders"][0]["id"] == "o1"
  693. def test_dumb_trader_uses_policy_and_reports_fit():
  694. class FakeContext:
  695. id = "s-2"
  696. account_id = "acct-2"
  697. client_id = "cid-2"
  698. mode = "active"
  699. market_symbol = "xrpusd"
  700. base_currency = "XRP"
  701. counter_currency = "USD"
  702. def get_price(self, symbol):
  703. return {"price": 1.2}
  704. def place_order(self, **kwargs):
  705. return {"ok": True, "order": kwargs}
  706. def get_strategy_snapshot(self):
  707. return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
  708. strat = DumbStrategy(FakeContext(), {"trade_side": "buy", "order_notional_quote": 1.5})
  709. strat.apply_policy()
  710. report = strat.report()
  711. assert report["fit"]["risk_profile"] == "neutral"
  712. assert strat.state["policy_derived"]["order_notional_quote"] > 0
  713. def test_dumb_trader_buys_on_configured_side_without_regime_input():
  714. class FakeContext:
  715. id = "s-bull"
  716. account_id = "acct-1"
  717. client_id = "cid-1"
  718. mode = "active"
  719. market_symbol = "xrpusd"
  720. base_currency = "XRP"
  721. counter_currency = "USD"
  722. def __init__(self):
  723. self.orders = []
  724. def get_price(self, symbol):
  725. return {"price": 1.2}
  726. def place_order(self, **kwargs):
  727. self.orders.append(kwargs)
  728. return {"ok": True, "order": kwargs}
  729. def get_account_info(self):
  730. return {"balances": [{"asset_code": "USD", "available": 1000}, {"asset_code": "XRP", "available": 0}]}
  731. minimum_order_value = 10.0
  732. def suggest_order_amount(self, **kwargs):
  733. return float(kwargs.get("quote_notional") or 0.0) / float(kwargs.get("price") or 1.0)
  734. def get_strategy_snapshot(self):
  735. return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
  736. ctx = FakeContext()
  737. strat = DumbStrategy(ctx, {"trade_side": "buy", "order_notional_quote": 20.0})
  738. result = strat.on_tick({})
  739. assert result["action"] == "buy"
  740. assert ctx.orders[-1]["side"] == "buy"
  741. assert ctx.orders[-1]["amount"] == 20.0 / 1.2
  742. assert strat.state["last_action"] == "buy_dumb"
  743. def test_dumb_trader_sells_on_configured_side_without_regime_input():
  744. class FakeContext:
  745. id = "s-bear"
  746. account_id = "acct-1"
  747. client_id = "cid-1"
  748. mode = "active"
  749. market_symbol = "xrpusd"
  750. base_currency = "XRP"
  751. counter_currency = "USD"
  752. def __init__(self):
  753. self.orders = []
  754. def get_price(self, symbol):
  755. return {"price": 1.2}
  756. def place_order(self, **kwargs):
  757. self.orders.append(kwargs)
  758. return {"ok": True, "order": kwargs}
  759. def get_account_info(self):
  760. return {"balances": [{"asset_code": "USD", "available": 1000}, {"asset_code": "XRP", "available": 10}]}
  761. minimum_order_value = 10.0
  762. def suggest_order_amount(self, **kwargs):
  763. return float(kwargs.get("quote_notional") or 0.0) / float(kwargs.get("price") or 1.0)
  764. def get_strategy_snapshot(self):
  765. return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
  766. ctx = FakeContext()
  767. strat = DumbStrategy(ctx, {"trade_side": "sell", "order_notional_quote": 20.0})
  768. result = strat.on_tick({})
  769. assert result["action"] == "sell"
  770. assert ctx.orders[-1]["side"] == "sell"
  771. assert ctx.orders[-1]["amount"] == 20.0 / 1.2
  772. assert strat.state["last_action"] == "sell_dumb"
  773. def test_dumb_trader_buy_only_ignores_bear_regime():
  774. class FakeContext:
  775. id = "s-buy-only"
  776. account_id = "acct-1"
  777. client_id = "cid-1"
  778. mode = "active"
  779. market_symbol = "xrpusd"
  780. base_currency = "XRP"
  781. counter_currency = "USD"
  782. def __init__(self):
  783. self.orders = []
  784. def get_price(self, symbol):
  785. return {"price": 1.2}
  786. def get_regime(self, symbol, timeframe="1h"):
  787. return {
  788. "trend": {"state": "bear", "ema_fast": 1.17, "ema_slow": 1.2},
  789. "momentum": {"state": "bear", "rsi": 36, "macd_histogram": -0.002},
  790. }
  791. def place_order(self, **kwargs):
  792. self.orders.append(kwargs)
  793. return {"ok": True, "order": kwargs}
  794. def get_account_info(self):
  795. return {"balances": [{"asset_code": "USD", "available": 1000}, {"asset_code": "XRP", "available": 10}]}
  796. minimum_order_value = 10.0
  797. def suggest_order_amount(self, **kwargs):
  798. return 10.0
  799. def get_strategy_snapshot(self):
  800. return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
  801. ctx = FakeContext()
  802. strat = DumbStrategy(ctx, {"trade_side": "buy", "order_notional_quote": 20.0})
  803. result = strat.on_tick({})
  804. assert result["action"] == "buy"
  805. assert ctx.orders[-1]["side"] == "buy"
  806. assert strat.state["last_action"] == "buy_dumb"
  807. def test_dumb_trader_sell_only_ignores_bull_regime():
  808. class FakeContext:
  809. id = "s-sell-only"
  810. account_id = "acct-1"
  811. client_id = "cid-1"
  812. mode = "active"
  813. market_symbol = "xrpusd"
  814. base_currency = "XRP"
  815. counter_currency = "USD"
  816. def __init__(self):
  817. self.orders = []
  818. def get_price(self, symbol):
  819. return {"price": 1.2}
  820. def get_regime(self, symbol, timeframe="1h"):
  821. return {
  822. "trend": {"state": "bull", "ema_fast": 1.21, "ema_slow": 1.18},
  823. "momentum": {"state": "bull", "rsi": 64, "macd_histogram": 0.002},
  824. }
  825. def place_order(self, **kwargs):
  826. self.orders.append(kwargs)
  827. return {"ok": True, "order": kwargs}
  828. def get_account_info(self):
  829. return {"balances": [{"asset_code": "USD", "available": 1000}, {"asset_code": "XRP", "available": 0}]}
  830. minimum_order_value = 10.0
  831. def suggest_order_amount(self, **kwargs):
  832. return 10.0
  833. def get_strategy_snapshot(self):
  834. return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
  835. ctx = FakeContext()
  836. strat = DumbStrategy(ctx, {"trade_side": "sell", "order_notional_quote": 20.0})
  837. result = strat.on_tick({})
  838. assert result["action"] == "sell"
  839. assert ctx.orders[-1]["side"] == "sell"
  840. assert strat.state["last_action"] == "sell_dumb"
  841. def test_dumb_trader_policy_does_not_override_explicit_order_notional_quote():
  842. class FakeContext:
  843. id = "s-explicit"
  844. account_id = "acct-1"
  845. client_id = "cid-1"
  846. mode = "active"
  847. market_symbol = "xrpusd"
  848. base_currency = "XRP"
  849. counter_currency = "USD"
  850. def get_price(self, symbol):
  851. return {"price": 1.2}
  852. def get_strategy_snapshot(self):
  853. return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
  854. strat = DumbStrategy(FakeContext(), {"trade_side": "buy", "order_notional_quote": 10.5})
  855. strat.apply_policy()
  856. assert strat.config["order_notional_quote"] == 10.5
  857. assert strat.state["policy_derived"]["order_notional_quote"] == 10.5
  858. def test_dumb_trader_passes_live_fee_rate_into_sizing_helper():
  859. class FakeContext:
  860. id = "s-fee"
  861. account_id = "acct-1"
  862. client_id = "cid-1"
  863. mode = "active"
  864. market_symbol = "xrpusd"
  865. base_currency = "XRP"
  866. counter_currency = "USD"
  867. minimum_order_value = 10.0
  868. def __init__(self):
  869. self.fee_calls = []
  870. self.suggest_calls = []
  871. def get_price(self, symbol):
  872. return {"price": 1.2}
  873. def get_fee_rates(self, market_symbol=None):
  874. self.fee_calls.append(market_symbol)
  875. return {"maker": 0.0025, "taker": 0.004}
  876. def suggest_order_amount(self, **kwargs):
  877. self.suggest_calls.append(kwargs)
  878. return 8.0
  879. def place_order(self, **kwargs):
  880. return {"ok": True, "order": kwargs}
  881. def get_account_info(self):
  882. return {"balances": [{"asset_code": "USD", "available": 1000}, {"asset_code": "XRP", "available": 0}]}
  883. def get_strategy_snapshot(self):
  884. return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
  885. ctx = FakeContext()
  886. strat = DumbStrategy(ctx, {"trade_side": "buy", "order_notional_quote": 10.5, "dust_collect": True})
  887. strat.on_tick({})
  888. assert ctx.fee_calls == ["xrpusd"]
  889. assert ctx.suggest_calls[-1]["fee_rate"] == 0.0025
  890. assert ctx.suggest_calls[-1]["dust_collect"] is True
  891. def test_grid_sizing_helper_receives_quote_controls_and_dust_collect():
  892. class FakeContext:
  893. base_currency = "XRP"
  894. counter_currency = "USD"
  895. market_symbol = "xrpusd"
  896. minimum_order_value = 10.0
  897. mode = "active"
  898. def __init__(self):
  899. self.suggest_calls = []
  900. def get_fee_rates(self, market_symbol=None):
  901. return {"maker": 0.001, "taker": 0.004}
  902. def suggest_order_amount(self, **kwargs):
  903. self.suggest_calls.append(kwargs)
  904. return 7.0
  905. ctx = FakeContext()
  906. strategy = GridStrategy(
  907. ctx,
  908. {
  909. "grid_levels": 3,
  910. "order_notional_quote": 11.0,
  911. "max_order_notional_quote": 12.0,
  912. "dust_collect": True,
  913. },
  914. )
  915. amount = strategy._suggest_amount("buy", 1.5, 3, 10.0)
  916. assert amount == 7.0
  917. assert ctx.suggest_calls[-1]["fee_rate"] == 0.004
  918. assert ctx.suggest_calls[-1]["quote_notional"] == 11.0
  919. assert ctx.suggest_calls[-1]["max_notional_per_order"] == 12.0
  920. assert ctx.suggest_calls[-1]["dust_collect"] is True
  921. assert ctx.suggest_calls[-1]["levels"] == 3
  922. def test_dumb_trader_buy_uses_requested_notional_even_with_balance_target_configured():
  923. class FakeContext:
  924. id = "s-buy-clamp"
  925. account_id = "acct-1"
  926. client_id = "cid-1"
  927. mode = "active"
  928. market_symbol = "xrpusd"
  929. base_currency = "XRP"
  930. counter_currency = "USD"
  931. minimum_order_value = 0.5
  932. def __init__(self):
  933. self.orders = []
  934. def get_price(self, symbol):
  935. return {"price": 1.0}
  936. def get_fee_rates(self, market_symbol=None):
  937. return {"maker": 0.0, "taker": 0.0}
  938. def suggest_order_amount(self, **kwargs):
  939. return float(kwargs.get("quote_notional") or 0.0) / float(kwargs.get("price") or 1.0)
  940. def place_order(self, **kwargs):
  941. self.orders.append(kwargs)
  942. return {"ok": True, "order": kwargs}
  943. def get_account_info(self):
  944. return {"balances": [{"asset_code": "USD", "available": 6.0}, {"asset_code": "XRP", "available": 4.0}]}
  945. def get_strategy_snapshot(self):
  946. return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
  947. ctx = FakeContext()
  948. strat = DumbStrategy(ctx, {"trade_side": "buy", "order_notional_quote": 3.0, "balance_target": 0.5})
  949. result = strat.on_tick({})
  950. assert result["action"] == "buy"
  951. assert ctx.orders[-1]["amount"] == 3.0
  952. def test_dumb_trader_sell_uses_requested_notional_even_with_balance_target_configured():
  953. class FakeContext:
  954. id = "s-sell-clamp"
  955. account_id = "acct-1"
  956. client_id = "cid-1"
  957. mode = "active"
  958. market_symbol = "xrpusd"
  959. base_currency = "XRP"
  960. counter_currency = "USD"
  961. minimum_order_value = 0.5
  962. def __init__(self):
  963. self.orders = []
  964. def get_price(self, symbol):
  965. return {"price": 1.0}
  966. def get_fee_rates(self, market_symbol=None):
  967. return {"maker": 0.0, "taker": 0.0}
  968. def suggest_order_amount(self, **kwargs):
  969. return float(kwargs.get("quote_notional") or 0.0) / float(kwargs.get("price") or 1.0)
  970. def place_order(self, **kwargs):
  971. self.orders.append(kwargs)
  972. return {"ok": True, "order": kwargs}
  973. def get_account_info(self):
  974. return {"balances": [{"asset_code": "USD", "available": 3.0}, {"asset_code": "XRP", "available": 7.0}]}
  975. def get_strategy_snapshot(self):
  976. return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
  977. ctx = FakeContext()
  978. strat = DumbStrategy(ctx, {"trade_side": "sell", "order_notional_quote": 5.0, "balance_target": 0.5})
  979. result = strat.on_tick({})
  980. assert result["action"] == "sell"
  981. assert ctx.orders[-1]["amount"] == 5.0
  982. def test_dumb_trader_sell_holds_sub_minimum_order():
  983. class FakeContext:
  984. id = "s-sell-min"
  985. account_id = "acct-1"
  986. client_id = "cid-1"
  987. mode = "active"
  988. market_symbol = "solusd"
  989. base_currency = "SOL"
  990. counter_currency = "USD"
  991. minimum_order_value = 1.0
  992. def __init__(self):
  993. self.orders = []
  994. def get_price(self, symbol):
  995. return {"price": 86.20062}
  996. def get_fee_rates(self, market_symbol=None):
  997. return {"maker": 0.0, "taker": 0.0}
  998. def suggest_order_amount(self, **kwargs):
  999. return 0.001
  1000. def place_order(self, **kwargs):
  1001. self.orders.append(kwargs)
  1002. return {"ok": True, "order": kwargs}
  1003. def get_account_info(self):
  1004. return {"balances": [{"asset_code": "USD", "available": 1000.0}, {"asset_code": "SOL", "available": 0.00447}]}
  1005. def get_strategy_snapshot(self):
  1006. return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
  1007. ctx = FakeContext()
  1008. strat = DumbStrategy(ctx, {"trade_side": "sell", "order_notional_quote": 5.0, "balance_target": 1.0})
  1009. result = strat.on_tick({})
  1010. assert result["action"] == "hold"
  1011. assert result["reason"] == "no usable size"
  1012. assert ctx.orders == []
  1013. def test_dumb_trader_holds_when_live_sizing_reports_no_affordable_sell():
  1014. class FakeContext:
  1015. id = "s-sell-no-funds"
  1016. account_id = "acct-1"
  1017. client_id = "cid-1"
  1018. mode = "active"
  1019. market_symbol = "solusd"
  1020. base_currency = "SOL"
  1021. counter_currency = "USD"
  1022. minimum_order_value = 0.5
  1023. def __init__(self):
  1024. self.orders = []
  1025. def get_price(self, symbol):
  1026. return {"price": 86.69}
  1027. def get_fee_rates(self, market_symbol=None):
  1028. return {"maker": 0.0, "taker": 0.0}
  1029. def suggest_order_amount(self, **kwargs):
  1030. return 0.0
  1031. def place_order(self, **kwargs):
  1032. self.orders.append(kwargs)
  1033. return {"ok": True, "order": kwargs}
  1034. def get_account_info(self):
  1035. return {"balances": [{"asset_code": "USD", "available": 1000.0}, {"asset_code": "SOL", "available": 0.00447}]}
  1036. def get_strategy_snapshot(self):
  1037. return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
  1038. ctx = FakeContext()
  1039. strat = DumbStrategy(ctx, {"trade_side": "sell", "order_notional_quote": 11.0, "dust_collect": True})
  1040. result = strat.on_tick({})
  1041. assert result["action"] == "hold"
  1042. assert result["reason"] == "no usable size"
  1043. assert ctx.orders == []
  1044. def test_dumb_trader_holds_when_balance_refresh_fails_after_restart():
  1045. class FakeContext:
  1046. id = "s-restart-hold"
  1047. account_id = "acct-1"
  1048. client_id = "cid-1"
  1049. mode = "active"
  1050. market_symbol = "solusd"
  1051. base_currency = "SOL"
  1052. counter_currency = "USD"
  1053. minimum_order_value = 1.0
  1054. def __init__(self):
  1055. self.orders = []
  1056. def get_price(self, symbol):
  1057. return {"price": 86.51}
  1058. def get_fee_rates(self, market_symbol=None):
  1059. return {"maker": 0.0, "taker": 0.0}
  1060. def get_account_info(self):
  1061. raise RuntimeError("Bitstamp auth breaker active, retry later")
  1062. def suggest_order_amount(self, **kwargs):
  1063. raise AssertionError("should not size an order after balance refresh failure")
  1064. def place_order(self, **kwargs):
  1065. self.orders.append(kwargs)
  1066. return {"ok": True, "order": kwargs}
  1067. def get_strategy_snapshot(self):
  1068. return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
  1069. ctx = FakeContext()
  1070. strat = DumbStrategy(
  1071. ctx,
  1072. {
  1073. "trade_side": "sell",
  1074. "order_notional_quote": 5.0,
  1075. "dust_collect": True,
  1076. },
  1077. )
  1078. strat.state["base_available"] = 0.127153
  1079. strat.state["counter_available"] = 0.0
  1080. result = strat.on_tick({})
  1081. assert result["action"] == "hold"
  1082. assert result["reason"] == "balance refresh unavailable"
  1083. assert strat.state["balance_snapshot_ok"] is False
  1084. assert strat.state["base_available"] == 0.0
  1085. assert ctx.orders == []
  1086. def test_dumb_trader_holds_when_trade_side_is_symmetrical():
  1087. class FakeContext:
  1088. id = "s-target-hold"
  1089. account_id = "acct-1"
  1090. client_id = "cid-1"
  1091. mode = "active"
  1092. market_symbol = "xrpusd"
  1093. base_currency = "XRP"
  1094. counter_currency = "USD"
  1095. minimum_order_value = 0.5
  1096. def get_price(self, symbol):
  1097. return {"price": 1.0}
  1098. def get_fee_rates(self, market_symbol=None):
  1099. return {"maker": 0.0, "taker": 0.0}
  1100. def suggest_order_amount(self, **kwargs):
  1101. return 10.0
  1102. def get_account_info(self):
  1103. return {"balances": [{"asset_code": "USD", "available": 5.0}, {"asset_code": "XRP", "available": 5.0}]}
  1104. def get_strategy_snapshot(self):
  1105. return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
  1106. strat = DumbStrategy(FakeContext(), {"trade_side": "both", "order_notional_quote": 3.0, "balance_target": 0.5})
  1107. result = strat.on_tick({})
  1108. assert result["action"] == "hold"
  1109. assert result["reason"] == "trade_side must be buy or sell"
  1110. def test_cap_amount_to_balance_target_caps_sell_to_live_base():
  1111. amount = cap_amount_to_balance_target(
  1112. suggested_amount=0.127226,
  1113. side="sell",
  1114. price=86.20062,
  1115. fee_rate=0.0,
  1116. balance_target=1.0,
  1117. base_available=0.00447,
  1118. counter_available=0.0,
  1119. min_notional=0.0,
  1120. )
  1121. assert amount == 0.00447
  1122. def test_cap_amount_to_balance_target_rejects_sell_below_min_notional():
  1123. amount = cap_amount_to_balance_target(
  1124. suggested_amount=0.127226,
  1125. side="sell",
  1126. price=86.20062,
  1127. fee_rate=0.0,
  1128. balance_target=1.0,
  1129. base_available=0.00447,
  1130. counter_available=0.0,
  1131. min_notional=1.0,
  1132. )
  1133. assert amount == 0.0
  1134. def test_dumb_trader_ignores_balance_target_and_keeps_size():
  1135. class FakeContext:
  1136. id = "s-target-open"
  1137. account_id = "acct-1"
  1138. client_id = "cid-1"
  1139. mode = "active"
  1140. market_symbol = "xrpusd"
  1141. base_currency = "XRP"
  1142. counter_currency = "USD"
  1143. minimum_order_value = 0.5
  1144. def __init__(self):
  1145. self.orders = []
  1146. def get_price(self, symbol):
  1147. return {"price": 1.0}
  1148. def get_fee_rates(self, market_symbol=None):
  1149. return {"maker": 0.0, "taker": 0.0}
  1150. def suggest_order_amount(self, **kwargs):
  1151. return float(kwargs.get("quote_notional") or 0.0) / float(kwargs.get("price") or 1.0)
  1152. def place_order(self, **kwargs):
  1153. self.orders.append(kwargs)
  1154. return {"ok": True, "order": kwargs}
  1155. def get_account_info(self):
  1156. return {"balances": [{"asset_code": "USD", "available": 6.0}, {"asset_code": "XRP", "available": 4.0}]}
  1157. def get_strategy_snapshot(self):
  1158. return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
  1159. ctx = FakeContext()
  1160. strat = DumbStrategy(ctx, {"trade_side": "buy", "order_notional_quote": 3.0, "balance_target": 0.5})
  1161. result = strat.on_tick({})
  1162. assert result["action"] == "buy"
  1163. assert ctx.orders[-1]["amount"] == 3.0
  1164. def test_exposure_protector_buy_sizing_respects_fee_when_min_order_quote_is_unaffordable():
  1165. class FakeContext:
  1166. account_id = "acct-1"
  1167. client_id = "cid-1"
  1168. mode = "active"
  1169. market_symbol = "xrpusd"
  1170. base_currency = "XRP"
  1171. counter_currency = "USD"
  1172. def get_fee_rates(self, market_symbol=None):
  1173. return {"maker": 0.1, "taker": 0.2}
  1174. strategy = ExposureStrategy(
  1175. FakeContext(),
  1176. {
  1177. "rebalance_target_ratio": 0.9,
  1178. "rebalance_step_ratio": 1.0,
  1179. "balance_tolerance": 0.0,
  1180. "min_order_notional_quote": 10.0,
  1181. },
  1182. )
  1183. strategy.state["base_available"] = 0.0
  1184. strategy.state["counter_available"] = 10.0
  1185. amount = strategy._suggest_amount("buy", 1.0)
  1186. assert amount == 0.0