test_strategies.py 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585
  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_grid_on_tick_honors_refresh_pause_before_shape_rebuild(monkeypatch):
  202. class FakeContext:
  203. account_id = "acct-1"
  204. market_symbol = "xrpusd"
  205. base_currency = "XRP"
  206. counter_currency = "USD"
  207. mode = "active"
  208. minimum_order_value = 1.0
  209. def get_account_info(self):
  210. return {
  211. "balances": [
  212. {"asset_code": "XRP", "available": 100.0, "total": 100.0},
  213. {"asset_code": "USD", "available": 100.0, "total": 100.0},
  214. ]
  215. }
  216. def get_price(self, _asset):
  217. return {"price": 1.0}
  218. def get_regime(self, *_args, **_kwargs):
  219. return {"volatility": {"atr_percent": 0.0}, "trend": {"state": "flat"}}
  220. def get_open_orders(self):
  221. return [{"bitstamp_order_id": "live-1", "side": "buy", "price": 0.99, "amount": 1.0}]
  222. strategy = GridStrategy(FakeContext(), {})
  223. strategy.state.update(
  224. {
  225. "center_price": 1.0,
  226. "seeded": True,
  227. "orders": [{"bitstamp_order_id": "old-1", "side": "buy", "price": 0.99, "amount": 1.0}],
  228. "order_ids": ["old-1"],
  229. "grid_refresh_pending_until": 9999999999.0,
  230. }
  231. )
  232. called = {"rebuild": 0}
  233. def fake_rebuild(*_args, **_kwargs):
  234. called["rebuild"] += 1
  235. monkeypatch.setattr(strategy, "_recenter_and_rebuild_from_price", fake_rebuild)
  236. result = strategy.on_tick({"ts": 0, "strategy_id": "grid-1"})
  237. assert result["action"] == "hold"
  238. assert result["refresh_paused"] is True
  239. assert called["rebuild"] == 0
  240. def test_dumb_trader_and_protector_supervision_reports_facts_only():
  241. class FakeContext:
  242. account_id = "acct-1"
  243. market_symbol = "xrpusd"
  244. base_currency = "XRP"
  245. counter_currency = "USD"
  246. mode = "active"
  247. trend = DumbStrategy(FakeContext(), {"trade_side": "buy", "order_notional_quote": 1.0})
  248. trend.state.update({"last_price": 1.45, "base_available": 20.0, "counter_available": 20.0, "last_order_at": 0.0})
  249. trend_supervision = trend._supervision()
  250. assert trend_supervision["trade_side"] == "buy"
  251. assert trend_supervision["capacity_available"] is True
  252. assert trend_supervision["entry_offset_pct"] == 0.003
  253. assert trend_supervision["chasing_risk"] in {"low", "moderate", "elevated"}
  254. assert "switch_readiness" not in trend_supervision
  255. assert "desired_companion" not in trend_supervision
  256. protector = ExposureStrategy(FakeContext(), {})
  257. protector.state.update({"last_price": 1.45, "base_available": 40.0, "counter_available": 10.0})
  258. protector_supervision = protector._supervision()
  259. assert protector_supervision["rebalance_needed"] is True
  260. assert protector_supervision["repair_progress"] <= 1.0
  261. assert "switch_readiness" not in protector_supervision
  262. assert "desired_companion" not in protector_supervision
  263. def test_exposure_protector_holds_inside_hysteresis_band(monkeypatch):
  264. class FakeContext:
  265. account_id = "acct-1"
  266. market_symbol = "xrpusd"
  267. base_currency = "XRP"
  268. counter_currency = "USD"
  269. mode = "active"
  270. def __init__(self):
  271. self.placed_orders = []
  272. def get_account_info(self):
  273. return {"balances": [{"asset_code": "XRP", "available": 9.2}, {"asset_code": "USD", "available": 10.0}]}
  274. def get_price(self, market):
  275. return {"price": 1.0}
  276. def get_fee_rates(self, market):
  277. return {"maker": 0.0, "taker": 0.004}
  278. def place_order(self, **kwargs):
  279. self.placed_orders.append(kwargs)
  280. return {"status": "ok", "id": f"oid-{len(self.placed_orders)}"}
  281. ctx = FakeContext()
  282. 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})
  283. strategy.state["last_rebalance_side"] = "sell"
  284. strategy.state["last_order_at"] = 0
  285. monkeypatch.setattr(strategy, "_refresh_regimes", lambda: None)
  286. result = strategy.on_tick({})
  287. assert result["action"] == "hold"
  288. assert result["reason"] == "within rebalance hysteresis"
  289. assert ctx.placed_orders == []
  290. def test_grid_apply_policy_keeps_explicit_grid_levels():
  291. class FakeContext:
  292. account_id = "acct-1"
  293. market_symbol = "xrpusd"
  294. base_currency = "XRP"
  295. counter_currency = "USD"
  296. mode = "active"
  297. strategy = GridStrategy(FakeContext(), {"grid_levels": 5, "policy": {"risk_posture": "normal"}})
  298. strategy.apply_policy()
  299. assert strategy.config["grid_levels"] == 5
  300. assert strategy.state["policy_derived"]["grid_levels"] == 5
  301. def test_grid_seed_keeps_other_side_when_one_side_fails(monkeypatch):
  302. class FakeContext:
  303. base_currency = "XRP"
  304. counter_currency = "USD"
  305. market_symbol = "xrpusd"
  306. minimum_order_value = 10.0
  307. mode = "active"
  308. def __init__(self):
  309. self.attempts = []
  310. self.buy_attempts = 0
  311. self.sell_attempts = 0
  312. def get_fee_rates(self, market):
  313. return {"maker": 0.0, "taker": 0.0}
  314. def suggest_order_amount(self, **kwargs):
  315. return 10.0
  316. def place_order(self, **kwargs):
  317. self.attempts.append(kwargs)
  318. if kwargs["side"] == "buy":
  319. self.buy_attempts += 1
  320. if self.buy_attempts == 3:
  321. raise RuntimeError("insufficient USD")
  322. elif kwargs["side"] == "sell":
  323. self.sell_attempts += 1
  324. return {"status": "ok", "id": f"{kwargs['side']}-{len(self.attempts)}"}
  325. ctx = FakeContext()
  326. strategy = GridStrategy(ctx, {"grid_levels": 5, "order_call_delay_ms": 0, "enable_trend_guard": False, "fee_rate": 0.0})
  327. strategy.state["center_price"] = 100.0
  328. monkeypatch.setattr(strategy, "_supported_levels", lambda side, center, min_notional: 5)
  329. monkeypatch.setattr(strategy, "_refresh_balance_snapshot", lambda: None)
  330. strategy._place_grid(100.0)
  331. orders = strategy.state["orders"]
  332. assert ctx.buy_attempts == 5
  333. assert ctx.sell_attempts == 5
  334. assert len([o for o in orders if o["side"] == "buy"]) == 4
  335. assert len([o for o in orders if o["side"] == "sell"]) == 5
  336. assert any("partial success" in line for line in (strategy.state.get("debug_log") or [])) or strategy.state.get("last_error") == "insufficient USD"
  337. def test_grid_skips_rebuild_when_balance_refresh_fails(monkeypatch):
  338. class FakeContext:
  339. base_currency = "XRP"
  340. counter_currency = "USD"
  341. market_symbol = "xrpusd"
  342. minimum_order_value = 10.0
  343. mode = "active"
  344. def __init__(self):
  345. self.cancelled_all = 0
  346. self.placed_orders = []
  347. def get_fee_rates(self, market):
  348. return {"maker": 0.0, "taker": 0.004}
  349. def get_account_info(self):
  350. raise RuntimeError("Bitstamp auth breaker active, retry later")
  351. def cancel_all_orders(self):
  352. self.cancelled_all += 1
  353. return {"ok": True}
  354. def suggest_order_amount(self, **kwargs):
  355. return 10.0
  356. def place_order(self, **kwargs):
  357. self.placed_orders.append(kwargs)
  358. return {"status": "ok", "id": f"oid-{len(self.placed_orders)}"}
  359. ctx = FakeContext()
  360. strategy = GridStrategy(ctx, {"grid_levels": 5, "order_call_delay_ms": 0, "enable_trend_guard": False, "fee_rate": 0.004})
  361. strategy.state["center_price"] = 1.4397
  362. strategy.state["seeded"] = True
  363. strategy.state["orders"] = [{"side": "buy", "price": 1.43, "amount": 10.0, "id": "o1"}]
  364. strategy.state["order_ids"] = ["o1"]
  365. monkeypatch.setattr(strategy, "_sync_open_orders_state", lambda: [{"side": "buy", "price": 1.43, "amount": 10.0, "id": "o1"}])
  366. monkeypatch.setattr(strategy, "_price", lambda: 1.4397)
  367. monkeypatch.setattr(strategy, "_refresh_regimes", lambda: None)
  368. result = strategy.on_tick({})
  369. assert result["action"] == "hold"
  370. assert result["reason"] == "balance refresh unavailable"
  371. assert ctx.cancelled_all == 0
  372. assert ctx.placed_orders == []
  373. def test_grid_skips_shape_rebuild_when_balance_reads_turn_inconclusive(monkeypatch):
  374. class FakeContext:
  375. base_currency = "XRP"
  376. counter_currency = "USD"
  377. market_symbol = "xrpusd"
  378. minimum_order_value = 10.0
  379. mode = "active"
  380. def __init__(self):
  381. self.cancelled_all = 0
  382. self.placed_orders = []
  383. self.calls = 0
  384. def get_fee_rates(self, market):
  385. return {"maker": 0.0, "taker": 0.004}
  386. def get_account_info(self):
  387. self.calls += 1
  388. if self.calls == 1:
  389. return {
  390. "balances": [
  391. {"asset_code": "USD", "available": 41.29},
  392. {"asset_code": "XRP", "available": 9.98954},
  393. ]
  394. }
  395. raise RuntimeError("Bitstamp auth breaker active, retry later")
  396. def cancel_all_orders(self):
  397. self.cancelled_all += 1
  398. return {"ok": True}
  399. def suggest_order_amount(self, **kwargs):
  400. return 10.0
  401. def place_order(self, **kwargs):
  402. self.placed_orders.append(kwargs)
  403. return {"status": "ok", "id": f"oid-{len(self.placed_orders)}"}
  404. ctx = FakeContext()
  405. strategy = GridStrategy(ctx, {"grid_levels": 2, "order_call_delay_ms": 0, "enable_trend_guard": False, "fee_rate": 0.004})
  406. strategy.state["center_price"] = 1.3285
  407. strategy.state["seeded"] = True
  408. strategy.state["orders"] = [
  409. {"side": "buy", "price": 1.3243993, "amount": 7.63, "id": "existing-buy"},
  410. {"side": "sell", "price": 1.3326007, "amount": 9.0, "id": "sell-1"},
  411. {"side": "sell", "price": 1.3367011, "amount": 9.0, "id": "sell-2"},
  412. ]
  413. strategy.state["order_ids"] = ["existing-buy", "sell-1", "sell-2"]
  414. def fake_sync_open_orders_state():
  415. live = [{"side": "sell", "price": 1.3326007, "amount": 9.0, "id": "sell-1"}]
  416. strategy.state["orders"] = live
  417. strategy.state["order_ids"] = ["sell-1"]
  418. strategy.state["open_order_count"] = 1
  419. return live
  420. monkeypatch.setattr(strategy, "_sync_open_orders_state", fake_sync_open_orders_state)
  421. monkeypatch.setattr(strategy, "_price", lambda: 1.3285)
  422. monkeypatch.setattr(strategy, "_refresh_regimes", lambda: None)
  423. monkeypatch.setattr(strategy, "_grid_refresh_paused", lambda: False)
  424. monkeypatch.setattr(strategy, "_recenter_threshold_pct", lambda: 0.5)
  425. result = strategy.on_tick({})
  426. assert result["action"] == "hold"
  427. assert ctx.cancelled_all == 0
  428. assert ctx.placed_orders == []
  429. def test_grid_missing_order_triggers_full_rebuild(monkeypatch):
  430. class FakeContext:
  431. base_currency = "XRP"
  432. counter_currency = "USD"
  433. market_symbol = "xrpusd"
  434. minimum_order_value = 10.0
  435. mode = "active"
  436. def __init__(self):
  437. self.cancelled_all = 0
  438. self.placed_orders = []
  439. def get_fee_rates(self, market):
  440. return {"maker": 0.0, "taker": 0.004}
  441. def get_account_info(self):
  442. return {
  443. "balances": [
  444. {"asset_code": "USD", "available": 13.55},
  445. {"asset_code": "XRP", "available": 22.0103},
  446. ]
  447. }
  448. def suggest_order_amount(
  449. self,
  450. *,
  451. side,
  452. price,
  453. levels,
  454. min_notional,
  455. fee_rate,
  456. max_notional_per_order=0.0,
  457. dust_collect=False,
  458. order_size=0.0,
  459. safety=0.995,
  460. ):
  461. if side == "buy":
  462. quote_available = 13.55
  463. spendable_quote = quote_available * safety
  464. quote_cap = min(spendable_quote, max_notional_per_order) if max_notional_per_order > 0 else spendable_quote
  465. if quote_cap < min_notional * (1 + fee_rate):
  466. return 0.0
  467. return quote_cap / (price * (1 + fee_rate))
  468. return 0.0
  469. def cancel_all_orders(self):
  470. self.cancelled_all += 1
  471. return {"ok": True}
  472. def place_order(self, **kwargs):
  473. self.placed_orders.append(kwargs)
  474. return {"status": "ok", "id": f"oid-{len(self.placed_orders)}"}
  475. ctx = FakeContext()
  476. strategy = GridStrategy(
  477. ctx,
  478. {
  479. "grid_levels": 2,
  480. "grid_step_pct": 0.0062,
  481. "grid_step_min_pct": 0.0033,
  482. "grid_step_max_pct": 0.012,
  483. "max_notional_per_order": 12,
  484. "order_call_delay_ms": 0,
  485. "trade_sides": "both",
  486. "debug_orders": True,
  487. "dust_collect": True,
  488. "enable_trend_guard": False,
  489. "fee_rate": 0.004,
  490. },
  491. )
  492. strategy.state["center_price"] = 1.3285
  493. strategy.state["seeded"] = True
  494. strategy.state["base_available"] = 22.0103
  495. strategy.state["counter_available"] = 13.55
  496. strategy.state["orders"] = [
  497. {"side": "buy", "price": 1.3243993, "amount": 7.63, "id": "existing-buy"},
  498. {"side": "sell", "price": 1.3326007, "amount": 9.0, "id": "sell-1"},
  499. {"side": "sell", "price": 1.3367011, "amount": 9.0, "id": "sell-2"},
  500. ]
  501. strategy.state["order_ids"] = ["existing-buy", "sell-1", "sell-2"]
  502. def fake_sync_open_orders_state():
  503. live = [{"side": "sell", "price": 1.3326007, "amount": 9.0, "id": "sell-1"}]
  504. strategy.state["orders"] = live
  505. strategy.state["order_ids"] = ["sell-1"]
  506. strategy.state["open_order_count"] = 1
  507. return live
  508. monkeypatch.setattr(strategy, "_sync_open_orders_state", fake_sync_open_orders_state)
  509. monkeypatch.setattr(strategy, "_price", lambda: 1.3285)
  510. monkeypatch.setattr(strategy, "_refresh_regimes", lambda: None)
  511. monkeypatch.setattr(strategy, "_grid_refresh_paused", lambda: False)
  512. monkeypatch.setattr(strategy, "_recenter_threshold_pct", lambda: 0.5)
  513. result = strategy.on_tick({})
  514. assert result["action"] in {"seed", "reseed"}
  515. assert ctx.cancelled_all == 1
  516. assert len(ctx.placed_orders) > 0
  517. assert strategy.state["last_action"] == "reseeded"
  518. def test_grid_side_imbalance_triggers_full_rebuild(monkeypatch):
  519. class FakeContext:
  520. base_currency = "XRP"
  521. counter_currency = "USD"
  522. market_symbol = "xrpusd"
  523. minimum_order_value = 10.0
  524. mode = "active"
  525. def __init__(self):
  526. self.cancelled_all = 0
  527. self.placed_orders = []
  528. def get_fee_rates(self, market):
  529. return {"maker": 0.0, "taker": 0.004}
  530. def get_account_info(self):
  531. return {"balances": [{"asset_code": "USD", "available": 41.29}, {"asset_code": "XRP", "available": 9.98954}]}
  532. def cancel_all_orders(self):
  533. self.cancelled_all += 1
  534. return {"ok": True}
  535. def suggest_order_amount(self, **kwargs):
  536. return 10.0
  537. def place_order(self, **kwargs):
  538. self.placed_orders.append(kwargs)
  539. return {"status": "ok", "id": f"oid-{len(self.placed_orders)}"}
  540. ctx = FakeContext()
  541. strategy = GridStrategy(ctx, {"grid_levels": 2, "order_call_delay_ms": 0, "enable_trend_guard": False, "fee_rate": 0.004})
  542. strategy.state["center_price"] = 1.3907
  543. strategy.state["seeded"] = True
  544. strategy.state["orders"] = [{"side": "buy", "price": 1.3800, "amount": 10.0, "id": "o1"} for _ in range(5)]
  545. strategy.state["order_ids"] = [f"o{i}" for i in range(5)]
  546. def fake_sync_open_orders_state():
  547. live = [{"side": "buy", "price": 1.3800, "amount": 10.0, "id": f"o{i}"} for i in range(5)]
  548. strategy.state["orders"] = live
  549. strategy.state["order_ids"] = [f"o{i}" for i in range(5)]
  550. strategy.state["open_order_count"] = 5
  551. return live
  552. monkeypatch.setattr(strategy, "_sync_open_orders_state", fake_sync_open_orders_state)
  553. monkeypatch.setattr(strategy, "_refresh_balance_snapshot", lambda: True)
  554. monkeypatch.setattr(strategy, "_price", lambda: 1.3915)
  555. monkeypatch.setattr(strategy, "_refresh_regimes", lambda: None)
  556. monkeypatch.setattr(strategy, "_grid_refresh_paused", lambda: False)
  557. monkeypatch.setattr(strategy, "_recenter_threshold_pct", lambda: 0.5)
  558. result = strategy.on_tick({})
  559. assert result["action"] in {"seed", "reseed"}
  560. assert ctx.cancelled_all == 1
  561. assert len(ctx.placed_orders) > 0
  562. def test_grid_recenters_exactly_on_live_price():
  563. class FakeContext:
  564. base_currency = "XRP"
  565. counter_currency = "USD"
  566. market_symbol = "xrpusd"
  567. minimum_order_value = 10.0
  568. mode = "active"
  569. def cancel_all_orders(self):
  570. return {"ok": True}
  571. def cancel_all_orders_confirmed(self):
  572. return {"conclusive": True, "error": None, "cleanup_status": "cleanup_confirmed", "cancelled_order_ids": []}
  573. def get_fee_rates(self, market):
  574. return {"maker": 0.0, "taker": 0.0}
  575. def suggest_order_amount(self, **kwargs):
  576. return 0.1
  577. def place_order(self, **kwargs):
  578. return {"status": "ok", "id": "oid-1"}
  579. strategy = GridStrategy(FakeContext(), {})
  580. strategy.state["center_price"] = 100.0
  581. strategy._recenter_and_rebuild_from_price(160.0, "test recenter")
  582. assert strategy.state["center_price"] == 160.0
  583. def test_grid_recenter_preserves_tracked_orders_when_cancel_is_inconclusive():
  584. class FakeContext:
  585. base_currency = "XRP"
  586. counter_currency = "USD"
  587. market_symbol = "xrpusd"
  588. minimum_order_value = 10.0
  589. mode = "active"
  590. def __init__(self):
  591. self.placed_orders = []
  592. def cancel_all_orders_confirmed(self):
  593. return {
  594. "conclusive": False,
  595. "error": "auth breaker active",
  596. "cleanup_status": "cleanup_partial",
  597. "cancelled_order_ids": ["o1"],
  598. }
  599. def get_fee_rates(self, market):
  600. return {"maker": 0.0, "taker": 0.0}
  601. def suggest_order_amount(self, **kwargs):
  602. return 0.1
  603. def place_order(self, **kwargs):
  604. self.placed_orders.append(kwargs)
  605. return {"status": "ok", "id": "oid-1"}
  606. ctx = FakeContext()
  607. strategy = GridStrategy(ctx, {})
  608. strategy.state["center_price"] = 100.0
  609. strategy.state["orders"] = [{"id": "o1"}, {"id": "o2"}]
  610. strategy.state["order_ids"] = ["o1", "o2"]
  611. strategy.state["open_order_count"] = 2
  612. strategy._recenter_and_rebuild_from_price(160.0, "test recenter")
  613. assert strategy.state["center_price"] == 100.0
  614. assert strategy.state["orders"] == [{"id": "o2"}]
  615. assert strategy.state["order_ids"] == ["o2"]
  616. assert strategy.state["open_order_count"] == 1
  617. assert strategy.state["cleanup_status"] == "cleanup_partial"
  618. assert strategy.state["last_action"] == "test recenter cleanup pending"
  619. assert ctx.placed_orders == []
  620. def test_grid_stop_cancels_all_open_orders():
  621. class FakeContext:
  622. base_currency = "XRP"
  623. counter_currency = "USD"
  624. market_symbol = "xrpusd"
  625. minimum_order_value = 10.0
  626. mode = "active"
  627. def __init__(self):
  628. self.cancelled = False
  629. def cancel_all_orders(self):
  630. self.cancelled = True
  631. return {"ok": True}
  632. def cancel_all_orders_confirmed(self):
  633. self.cancelled = True
  634. return {"conclusive": True, "error": None, "cleanup_status": "cleanup_confirmed", "cancelled_order_ids": ["o1"]}
  635. def get_fee_rates(self, market):
  636. return {"maker": 0.0, "taker": 0.0}
  637. strategy = GridStrategy(FakeContext(), {})
  638. strategy.state["orders"] = [{"id": "o1"}]
  639. strategy.state["order_ids"] = ["o1"]
  640. strategy.state["open_order_count"] = 1
  641. strategy.on_stop()
  642. assert strategy.context.cancelled is True
  643. assert strategy.state["open_order_count"] == 0
  644. assert strategy.state["cleanup_status"] == "cleanup_confirmed"
  645. assert strategy.state["last_action"] == "stopped"
  646. def test_grid_stop_preserves_tracked_orders_when_cancel_is_inconclusive():
  647. class FakeContext:
  648. base_currency = "XRP"
  649. counter_currency = "USD"
  650. market_symbol = "xrpusd"
  651. minimum_order_value = 10.0
  652. mode = "active"
  653. def cancel_all_orders_confirmed(self):
  654. return {
  655. "conclusive": False,
  656. "error": "auth breaker active",
  657. "cleanup_status": "cleanup_failed",
  658. "cancelled_order_ids": [],
  659. }
  660. def get_fee_rates(self, market):
  661. return {"maker": 0.0, "taker": 0.0}
  662. strategy = GridStrategy(FakeContext(), {})
  663. strategy.state["orders"] = [{"id": "o1"}]
  664. strategy.state["order_ids"] = ["o1"]
  665. strategy.state["open_order_count"] = 1
  666. strategy.on_stop()
  667. assert strategy.state["orders"] == [{"id": "o1"}]
  668. assert strategy.state["order_ids"] == ["o1"]
  669. assert strategy.state["open_order_count"] == 1
  670. assert strategy.state["cleanup_status"] == "cleanup_failed"
  671. assert strategy.state["last_action"] == "stop cleanup pending"
  672. assert strategy.state["last_error"] == "auth breaker active"
  673. def test_grid_observe_mode_preserves_tracked_orders_when_cancel_is_inconclusive(monkeypatch):
  674. class FakeContext:
  675. base_currency = "XRP"
  676. counter_currency = "USD"
  677. market_symbol = "xrpusd"
  678. minimum_order_value = 10.0
  679. mode = "observe"
  680. def cancel_all_orders_confirmed(self):
  681. return {
  682. "conclusive": False,
  683. "error": "auth breaker active",
  684. "cleanup_status": "cleanup_failed",
  685. "cancelled_order_ids": [],
  686. }
  687. def get_fee_rates(self, market):
  688. return {"maker": 0.0, "taker": 0.0}
  689. def get_account_info(self):
  690. return {"balances": [{"asset_code": "USD", "available": 50.0}, {"asset_code": "XRP", "available": 5.0}]}
  691. strategy = GridStrategy(FakeContext(), {})
  692. strategy.state["center_price"] = 1.42
  693. strategy.state["seeded"] = True
  694. strategy.state["orders"] = [{"id": "o1", "side": "buy", "price": 1.4, "amount": 10.0}]
  695. strategy.state["order_ids"] = ["o1"]
  696. strategy.state["open_order_count"] = 1
  697. monkeypatch.setattr(strategy, "_price", lambda: 1.42)
  698. monkeypatch.setattr(strategy, "_refresh_regimes", lambda: None)
  699. monkeypatch.setattr(strategy, "_refresh_balance_snapshot", lambda: True)
  700. monkeypatch.setattr(strategy, "_sync_open_orders_state", lambda: [{"id": "o1", "side": "buy", "price": 1.4, "amount": 10.0}])
  701. result = strategy.on_tick({})
  702. assert result["action"] == "observe"
  703. assert result["cleanup_pending"] is True
  704. assert strategy.state["orders"] == [{"id": "o1", "side": "buy", "price": 1.4, "amount": 10.0}]
  705. assert strategy.state["order_ids"] == ["o1"]
  706. assert strategy.state["open_order_count"] == 1
  707. assert strategy.state["cleanup_status"] == "cleanup_failed"
  708. assert strategy.state["last_action"] == "observe cleanup pending"
  709. assert strategy.state["last_error"] == "auth breaker active"
  710. def test_base_strategy_report_uses_context_snapshot():
  711. class FakeContext:
  712. id = "s-1"
  713. account_id = "acct-1"
  714. market_symbol = "xrpusd"
  715. base_currency = "XRP"
  716. counter_currency = "USD"
  717. mode = "active"
  718. def get_strategy_snapshot(self):
  719. return {
  720. "identity": {"strategy_id": "s-1", "strategy_name": "Demo", "account_id": "acct-1", "market": "xrpusd", "base_currency": "XRP", "quote_currency": "USD"},
  721. "control": {"enabled_state": "on", "mode": "active"},
  722. "position": {"balances": [{"asset_code": "XRP", "available": 1.0}]},
  723. "orders": {"open_orders": [{"id": "o1"}]},
  724. "execution": {"execution_quality": "good"},
  725. }
  726. class DemoStrategy(BaseStrategy):
  727. LABEL = "Demo"
  728. report = DemoStrategy(FakeContext(), {}).report()
  729. assert report["identity"]["strategy_id"] == "s-1"
  730. assert report["control"]["mode"] == "active"
  731. assert report["position"]["open_orders"][0]["id"] == "o1"
  732. def test_dumb_trader_uses_policy_and_reports_fit():
  733. class FakeContext:
  734. id = "s-2"
  735. account_id = "acct-2"
  736. client_id = "cid-2"
  737. mode = "active"
  738. market_symbol = "xrpusd"
  739. base_currency = "XRP"
  740. counter_currency = "USD"
  741. def get_price(self, symbol):
  742. return {"price": 1.2}
  743. def place_order(self, **kwargs):
  744. return {"ok": True, "order": kwargs}
  745. def get_strategy_snapshot(self):
  746. return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
  747. strat = DumbStrategy(FakeContext(), {"trade_side": "buy", "order_notional_quote": 1.5})
  748. strat.apply_policy()
  749. report = strat.report()
  750. assert report["fit"]["risk_profile"] == "neutral"
  751. assert strat.state["policy_derived"]["order_notional_quote"] > 0
  752. def test_dumb_trader_buys_on_configured_side_without_regime_input():
  753. class FakeContext:
  754. id = "s-bull"
  755. account_id = "acct-1"
  756. client_id = "cid-1"
  757. mode = "active"
  758. market_symbol = "xrpusd"
  759. base_currency = "XRP"
  760. counter_currency = "USD"
  761. def __init__(self):
  762. self.orders = []
  763. def get_price(self, symbol):
  764. return {"price": 1.2}
  765. def place_order(self, **kwargs):
  766. self.orders.append(kwargs)
  767. return {"ok": True, "order": kwargs}
  768. def get_account_info(self):
  769. return {"balances": [{"asset_code": "USD", "available": 1000}, {"asset_code": "XRP", "available": 0}]}
  770. minimum_order_value = 10.0
  771. def suggest_order_amount(self, **kwargs):
  772. return float(kwargs.get("quote_notional") or 0.0) / float(kwargs.get("price") or 1.0)
  773. def get_strategy_snapshot(self):
  774. return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
  775. ctx = FakeContext()
  776. strat = DumbStrategy(ctx, {"trade_side": "buy", "order_notional_quote": 20.0})
  777. result = strat.on_tick({})
  778. assert result["action"] == "buy"
  779. assert ctx.orders[-1]["side"] == "buy"
  780. assert ctx.orders[-1]["amount"] == 20.0 / 1.2
  781. assert strat.state["last_action"] == "buy_dumb"
  782. def test_dumb_trader_sells_on_configured_side_without_regime_input():
  783. class FakeContext:
  784. id = "s-bear"
  785. account_id = "acct-1"
  786. client_id = "cid-1"
  787. mode = "active"
  788. market_symbol = "xrpusd"
  789. base_currency = "XRP"
  790. counter_currency = "USD"
  791. def __init__(self):
  792. self.orders = []
  793. def get_price(self, symbol):
  794. return {"price": 1.2}
  795. def place_order(self, **kwargs):
  796. self.orders.append(kwargs)
  797. return {"ok": True, "order": kwargs}
  798. def get_account_info(self):
  799. return {"balances": [{"asset_code": "USD", "available": 1000}, {"asset_code": "XRP", "available": 10}]}
  800. minimum_order_value = 10.0
  801. def suggest_order_amount(self, **kwargs):
  802. return float(kwargs.get("quote_notional") or 0.0) / float(kwargs.get("price") or 1.0)
  803. def get_strategy_snapshot(self):
  804. return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
  805. ctx = FakeContext()
  806. strat = DumbStrategy(ctx, {"trade_side": "sell", "order_notional_quote": 20.0})
  807. result = strat.on_tick({})
  808. assert result["action"] == "sell"
  809. assert ctx.orders[-1]["side"] == "sell"
  810. assert ctx.orders[-1]["amount"] == 20.0 / 1.2
  811. assert strat.state["last_action"] == "sell_dumb"
  812. def test_dumb_trader_buy_only_ignores_bear_regime():
  813. class FakeContext:
  814. id = "s-buy-only"
  815. account_id = "acct-1"
  816. client_id = "cid-1"
  817. mode = "active"
  818. market_symbol = "xrpusd"
  819. base_currency = "XRP"
  820. counter_currency = "USD"
  821. def __init__(self):
  822. self.orders = []
  823. def get_price(self, symbol):
  824. return {"price": 1.2}
  825. def get_regime(self, symbol, timeframe="1h"):
  826. return {
  827. "trend": {"state": "bear", "ema_fast": 1.17, "ema_slow": 1.2},
  828. "momentum": {"state": "bear", "rsi": 36, "macd_histogram": -0.002},
  829. }
  830. def place_order(self, **kwargs):
  831. self.orders.append(kwargs)
  832. return {"ok": True, "order": kwargs}
  833. def get_account_info(self):
  834. return {"balances": [{"asset_code": "USD", "available": 1000}, {"asset_code": "XRP", "available": 10}]}
  835. minimum_order_value = 10.0
  836. def suggest_order_amount(self, **kwargs):
  837. return 10.0
  838. def get_strategy_snapshot(self):
  839. return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
  840. ctx = FakeContext()
  841. strat = DumbStrategy(ctx, {"trade_side": "buy", "order_notional_quote": 20.0})
  842. result = strat.on_tick({})
  843. assert result["action"] == "buy"
  844. assert ctx.orders[-1]["side"] == "buy"
  845. assert strat.state["last_action"] == "buy_dumb"
  846. def test_dumb_trader_sell_only_ignores_bull_regime():
  847. class FakeContext:
  848. id = "s-sell-only"
  849. account_id = "acct-1"
  850. client_id = "cid-1"
  851. mode = "active"
  852. market_symbol = "xrpusd"
  853. base_currency = "XRP"
  854. counter_currency = "USD"
  855. def __init__(self):
  856. self.orders = []
  857. def get_price(self, symbol):
  858. return {"price": 1.2}
  859. def get_regime(self, symbol, timeframe="1h"):
  860. return {
  861. "trend": {"state": "bull", "ema_fast": 1.21, "ema_slow": 1.18},
  862. "momentum": {"state": "bull", "rsi": 64, "macd_histogram": 0.002},
  863. }
  864. def place_order(self, **kwargs):
  865. self.orders.append(kwargs)
  866. return {"ok": True, "order": kwargs}
  867. def get_account_info(self):
  868. return {"balances": [{"asset_code": "USD", "available": 1000}, {"asset_code": "XRP", "available": 0}]}
  869. minimum_order_value = 10.0
  870. def suggest_order_amount(self, **kwargs):
  871. return 10.0
  872. def get_strategy_snapshot(self):
  873. return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
  874. ctx = FakeContext()
  875. strat = DumbStrategy(ctx, {"trade_side": "sell", "order_notional_quote": 20.0})
  876. result = strat.on_tick({})
  877. assert result["action"] == "sell"
  878. assert ctx.orders[-1]["side"] == "sell"
  879. assert strat.state["last_action"] == "sell_dumb"
  880. def test_dumb_trader_policy_does_not_override_explicit_order_notional_quote():
  881. class FakeContext:
  882. id = "s-explicit"
  883. account_id = "acct-1"
  884. client_id = "cid-1"
  885. mode = "active"
  886. market_symbol = "xrpusd"
  887. base_currency = "XRP"
  888. counter_currency = "USD"
  889. def get_price(self, symbol):
  890. return {"price": 1.2}
  891. def get_strategy_snapshot(self):
  892. return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
  893. strat = DumbStrategy(FakeContext(), {"trade_side": "buy", "order_notional_quote": 10.5})
  894. strat.apply_policy()
  895. assert strat.config["order_notional_quote"] == 10.5
  896. assert strat.state["policy_derived"]["order_notional_quote"] == 10.5
  897. def test_dumb_trader_passes_live_fee_rate_into_sizing_helper():
  898. class FakeContext:
  899. id = "s-fee"
  900. account_id = "acct-1"
  901. client_id = "cid-1"
  902. mode = "active"
  903. market_symbol = "xrpusd"
  904. base_currency = "XRP"
  905. counter_currency = "USD"
  906. minimum_order_value = 10.0
  907. def __init__(self):
  908. self.fee_calls = []
  909. self.suggest_calls = []
  910. def get_price(self, symbol):
  911. return {"price": 1.2}
  912. def get_fee_rates(self, market_symbol=None):
  913. self.fee_calls.append(market_symbol)
  914. return {"maker": 0.0025, "taker": 0.004}
  915. def suggest_order_amount(self, **kwargs):
  916. self.suggest_calls.append(kwargs)
  917. return 8.0
  918. def place_order(self, **kwargs):
  919. return {"ok": True, "order": kwargs}
  920. def get_account_info(self):
  921. return {"balances": [{"asset_code": "USD", "available": 1000}, {"asset_code": "XRP", "available": 0}]}
  922. def get_strategy_snapshot(self):
  923. return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
  924. ctx = FakeContext()
  925. strat = DumbStrategy(ctx, {"trade_side": "buy", "order_notional_quote": 10.5, "dust_collect": True})
  926. strat.on_tick({})
  927. assert ctx.fee_calls == ["xrpusd"]
  928. assert ctx.suggest_calls[-1]["fee_rate"] == 0.0025
  929. assert ctx.suggest_calls[-1]["dust_collect"] is True
  930. def test_grid_sizing_helper_receives_quote_controls_and_dust_collect():
  931. class FakeContext:
  932. base_currency = "XRP"
  933. counter_currency = "USD"
  934. market_symbol = "xrpusd"
  935. minimum_order_value = 10.0
  936. mode = "active"
  937. def __init__(self):
  938. self.suggest_calls = []
  939. def get_fee_rates(self, market_symbol=None):
  940. return {"maker": 0.001, "taker": 0.004}
  941. def suggest_order_amount(self, **kwargs):
  942. self.suggest_calls.append(kwargs)
  943. return 7.0
  944. ctx = FakeContext()
  945. strategy = GridStrategy(
  946. ctx,
  947. {
  948. "grid_levels": 3,
  949. "order_notional_quote": 11.0,
  950. "max_order_notional_quote": 12.0,
  951. "dust_collect": True,
  952. },
  953. )
  954. amount = strategy._suggest_amount("buy", 1.5, 3, 10.0)
  955. assert amount == 7.0
  956. assert ctx.suggest_calls[-1]["fee_rate"] == 0.004
  957. assert ctx.suggest_calls[-1]["quote_notional"] == 11.0
  958. assert ctx.suggest_calls[-1]["max_notional_per_order"] == 12.0
  959. assert ctx.suggest_calls[-1]["dust_collect"] is True
  960. assert ctx.suggest_calls[-1]["levels"] == 3
  961. def test_dumb_trader_buy_uses_requested_notional_even_with_balance_target_configured():
  962. class FakeContext:
  963. id = "s-buy-clamp"
  964. account_id = "acct-1"
  965. client_id = "cid-1"
  966. mode = "active"
  967. market_symbol = "xrpusd"
  968. base_currency = "XRP"
  969. counter_currency = "USD"
  970. minimum_order_value = 0.5
  971. def __init__(self):
  972. self.orders = []
  973. def get_price(self, symbol):
  974. return {"price": 1.0}
  975. def get_fee_rates(self, market_symbol=None):
  976. return {"maker": 0.0, "taker": 0.0}
  977. def suggest_order_amount(self, **kwargs):
  978. return float(kwargs.get("quote_notional") or 0.0) / float(kwargs.get("price") or 1.0)
  979. def place_order(self, **kwargs):
  980. self.orders.append(kwargs)
  981. return {"ok": True, "order": kwargs}
  982. def get_account_info(self):
  983. return {"balances": [{"asset_code": "USD", "available": 6.0}, {"asset_code": "XRP", "available": 4.0}]}
  984. def get_strategy_snapshot(self):
  985. return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
  986. ctx = FakeContext()
  987. strat = DumbStrategy(ctx, {"trade_side": "buy", "order_notional_quote": 3.0, "balance_target": 0.5})
  988. result = strat.on_tick({})
  989. assert result["action"] == "buy"
  990. assert ctx.orders[-1]["amount"] == 3.0
  991. def test_dumb_trader_sell_uses_requested_notional_even_with_balance_target_configured():
  992. class FakeContext:
  993. id = "s-sell-clamp"
  994. account_id = "acct-1"
  995. client_id = "cid-1"
  996. mode = "active"
  997. market_symbol = "xrpusd"
  998. base_currency = "XRP"
  999. counter_currency = "USD"
  1000. minimum_order_value = 0.5
  1001. def __init__(self):
  1002. self.orders = []
  1003. def get_price(self, symbol):
  1004. return {"price": 1.0}
  1005. def get_fee_rates(self, market_symbol=None):
  1006. return {"maker": 0.0, "taker": 0.0}
  1007. def suggest_order_amount(self, **kwargs):
  1008. return float(kwargs.get("quote_notional") or 0.0) / float(kwargs.get("price") or 1.0)
  1009. def place_order(self, **kwargs):
  1010. self.orders.append(kwargs)
  1011. return {"ok": True, "order": kwargs}
  1012. def get_account_info(self):
  1013. return {"balances": [{"asset_code": "USD", "available": 3.0}, {"asset_code": "XRP", "available": 7.0}]}
  1014. def get_strategy_snapshot(self):
  1015. return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
  1016. ctx = FakeContext()
  1017. strat = DumbStrategy(ctx, {"trade_side": "sell", "order_notional_quote": 5.0, "balance_target": 0.5})
  1018. result = strat.on_tick({})
  1019. assert result["action"] == "sell"
  1020. assert ctx.orders[-1]["amount"] == 5.0
  1021. def test_dumb_trader_sell_holds_sub_minimum_order():
  1022. class FakeContext:
  1023. id = "s-sell-min"
  1024. account_id = "acct-1"
  1025. client_id = "cid-1"
  1026. mode = "active"
  1027. market_symbol = "solusd"
  1028. base_currency = "SOL"
  1029. counter_currency = "USD"
  1030. minimum_order_value = 1.0
  1031. def __init__(self):
  1032. self.orders = []
  1033. def get_price(self, symbol):
  1034. return {"price": 86.20062}
  1035. def get_fee_rates(self, market_symbol=None):
  1036. return {"maker": 0.0, "taker": 0.0}
  1037. def suggest_order_amount(self, **kwargs):
  1038. return 0.001
  1039. def place_order(self, **kwargs):
  1040. self.orders.append(kwargs)
  1041. return {"ok": True, "order": kwargs}
  1042. def get_account_info(self):
  1043. return {"balances": [{"asset_code": "USD", "available": 1000.0}, {"asset_code": "SOL", "available": 0.00447}]}
  1044. def get_strategy_snapshot(self):
  1045. return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
  1046. ctx = FakeContext()
  1047. strat = DumbStrategy(ctx, {"trade_side": "sell", "order_notional_quote": 5.0, "balance_target": 1.0})
  1048. result = strat.on_tick({})
  1049. assert result["action"] == "hold"
  1050. assert result["reason"] == "no usable size"
  1051. assert ctx.orders == []
  1052. def test_dumb_trader_holds_when_live_sizing_reports_no_affordable_sell():
  1053. class FakeContext:
  1054. id = "s-sell-no-funds"
  1055. account_id = "acct-1"
  1056. client_id = "cid-1"
  1057. mode = "active"
  1058. market_symbol = "solusd"
  1059. base_currency = "SOL"
  1060. counter_currency = "USD"
  1061. minimum_order_value = 0.5
  1062. def __init__(self):
  1063. self.orders = []
  1064. def get_price(self, symbol):
  1065. return {"price": 86.69}
  1066. def get_fee_rates(self, market_symbol=None):
  1067. return {"maker": 0.0, "taker": 0.0}
  1068. def suggest_order_amount(self, **kwargs):
  1069. return 0.0
  1070. def place_order(self, **kwargs):
  1071. self.orders.append(kwargs)
  1072. return {"ok": True, "order": kwargs}
  1073. def get_account_info(self):
  1074. return {"balances": [{"asset_code": "USD", "available": 1000.0}, {"asset_code": "SOL", "available": 0.00447}]}
  1075. def get_strategy_snapshot(self):
  1076. return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
  1077. ctx = FakeContext()
  1078. strat = DumbStrategy(ctx, {"trade_side": "sell", "order_notional_quote": 11.0, "dust_collect": True})
  1079. result = strat.on_tick({})
  1080. assert result["action"] == "hold"
  1081. assert result["reason"] == "no usable size"
  1082. assert ctx.orders == []
  1083. def test_dumb_trader_holds_when_balance_refresh_fails_after_restart():
  1084. class FakeContext:
  1085. id = "s-restart-hold"
  1086. account_id = "acct-1"
  1087. client_id = "cid-1"
  1088. mode = "active"
  1089. market_symbol = "solusd"
  1090. base_currency = "SOL"
  1091. counter_currency = "USD"
  1092. minimum_order_value = 1.0
  1093. def __init__(self):
  1094. self.orders = []
  1095. def get_price(self, symbol):
  1096. return {"price": 86.51}
  1097. def get_fee_rates(self, market_symbol=None):
  1098. return {"maker": 0.0, "taker": 0.0}
  1099. def get_account_info(self):
  1100. raise RuntimeError("Bitstamp auth breaker active, retry later")
  1101. def suggest_order_amount(self, **kwargs):
  1102. raise AssertionError("should not size an order after balance refresh failure")
  1103. def place_order(self, **kwargs):
  1104. self.orders.append(kwargs)
  1105. return {"ok": True, "order": kwargs}
  1106. def get_strategy_snapshot(self):
  1107. return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
  1108. ctx = FakeContext()
  1109. strat = DumbStrategy(
  1110. ctx,
  1111. {
  1112. "trade_side": "sell",
  1113. "order_notional_quote": 5.0,
  1114. "dust_collect": True,
  1115. },
  1116. )
  1117. strat.state["base_available"] = 0.127153
  1118. strat.state["counter_available"] = 0.0
  1119. result = strat.on_tick({})
  1120. assert result["action"] == "hold"
  1121. assert result["reason"] == "balance refresh unavailable"
  1122. assert strat.state["balance_snapshot_ok"] is False
  1123. assert strat.state["base_available"] == 0.0
  1124. assert ctx.orders == []
  1125. def test_dumb_trader_holds_when_trade_side_is_symmetrical():
  1126. class FakeContext:
  1127. id = "s-target-hold"
  1128. account_id = "acct-1"
  1129. client_id = "cid-1"
  1130. mode = "active"
  1131. market_symbol = "xrpusd"
  1132. base_currency = "XRP"
  1133. counter_currency = "USD"
  1134. minimum_order_value = 0.5
  1135. def get_price(self, symbol):
  1136. return {"price": 1.0}
  1137. def get_fee_rates(self, market_symbol=None):
  1138. return {"maker": 0.0, "taker": 0.0}
  1139. def suggest_order_amount(self, **kwargs):
  1140. return 10.0
  1141. def get_account_info(self):
  1142. return {"balances": [{"asset_code": "USD", "available": 5.0}, {"asset_code": "XRP", "available": 5.0}]}
  1143. def get_strategy_snapshot(self):
  1144. return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
  1145. strat = DumbStrategy(FakeContext(), {"trade_side": "both", "order_notional_quote": 3.0, "balance_target": 0.5})
  1146. result = strat.on_tick({})
  1147. assert result["action"] == "hold"
  1148. assert result["reason"] == "trade_side must be buy or sell"
  1149. def test_cap_amount_to_balance_target_caps_sell_to_live_base():
  1150. amount = cap_amount_to_balance_target(
  1151. suggested_amount=0.127226,
  1152. side="sell",
  1153. price=86.20062,
  1154. fee_rate=0.0,
  1155. balance_target=1.0,
  1156. base_available=0.00447,
  1157. counter_available=0.0,
  1158. min_notional=0.0,
  1159. )
  1160. assert amount == 0.00447
  1161. def test_cap_amount_to_balance_target_rejects_sell_below_min_notional():
  1162. amount = cap_amount_to_balance_target(
  1163. suggested_amount=0.127226,
  1164. side="sell",
  1165. price=86.20062,
  1166. fee_rate=0.0,
  1167. balance_target=1.0,
  1168. base_available=0.00447,
  1169. counter_available=0.0,
  1170. min_notional=1.0,
  1171. )
  1172. assert amount == 0.0
  1173. def test_dumb_trader_ignores_balance_target_and_keeps_size():
  1174. class FakeContext:
  1175. id = "s-target-open"
  1176. account_id = "acct-1"
  1177. client_id = "cid-1"
  1178. mode = "active"
  1179. market_symbol = "xrpusd"
  1180. base_currency = "XRP"
  1181. counter_currency = "USD"
  1182. minimum_order_value = 0.5
  1183. def __init__(self):
  1184. self.orders = []
  1185. def get_price(self, symbol):
  1186. return {"price": 1.0}
  1187. def get_fee_rates(self, market_symbol=None):
  1188. return {"maker": 0.0, "taker": 0.0}
  1189. def suggest_order_amount(self, **kwargs):
  1190. return float(kwargs.get("quote_notional") or 0.0) / float(kwargs.get("price") or 1.0)
  1191. def place_order(self, **kwargs):
  1192. self.orders.append(kwargs)
  1193. return {"ok": True, "order": kwargs}
  1194. def get_account_info(self):
  1195. return {"balances": [{"asset_code": "USD", "available": 6.0}, {"asset_code": "XRP", "available": 4.0}]}
  1196. def get_strategy_snapshot(self):
  1197. return {"identity": {}, "control": {}, "position": {}, "orders": {}, "execution": {}}
  1198. ctx = FakeContext()
  1199. strat = DumbStrategy(ctx, {"trade_side": "buy", "order_notional_quote": 3.0, "balance_target": 0.5})
  1200. result = strat.on_tick({})
  1201. assert result["action"] == "buy"
  1202. assert ctx.orders[-1]["amount"] == 3.0
  1203. def test_exposure_protector_buy_sizing_respects_fee_when_min_order_quote_is_unaffordable():
  1204. class FakeContext:
  1205. account_id = "acct-1"
  1206. client_id = "cid-1"
  1207. mode = "active"
  1208. market_symbol = "xrpusd"
  1209. base_currency = "XRP"
  1210. counter_currency = "USD"
  1211. def get_fee_rates(self, market_symbol=None):
  1212. return {"maker": 0.1, "taker": 0.2}
  1213. strategy = ExposureStrategy(
  1214. FakeContext(),
  1215. {
  1216. "rebalance_target_ratio": 0.9,
  1217. "rebalance_step_ratio": 1.0,
  1218. "balance_tolerance": 0.0,
  1219. "min_order_notional_quote": 10.0,
  1220. },
  1221. )
  1222. strategy.state["base_available"] = 0.0
  1223. strategy.state["counter_available"] = 10.0
  1224. amount = strategy._suggest_amount("buy", 1.0)
  1225. assert amount == 0.0