exposure_protector.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. from __future__ import annotations
  2. from datetime import datetime, timezone
  3. from src.trader_mcp.strategy_sdk import Strategy
  4. from src.trader_mcp.logging_utils import log_event
  5. class Strategy(Strategy):
  6. LABEL = "Exposure Protector"
  7. STRATEGY_PROFILE = {
  8. "expects": {
  9. "trend": "mixed",
  10. "volatility": "moderate",
  11. "event_risk": "low",
  12. "liquidity": "normal",
  13. },
  14. "avoids": {
  15. "volatility": "chaotic",
  16. "event_risk": "high",
  17. "liquidity": "thin",
  18. },
  19. "risk_profile": "defensive",
  20. "capabilities": ["inventory_rebalancing", "exposure_trim", "companion_defense"],
  21. "role": "defensive",
  22. "inventory_behavior": "rebalancing",
  23. "requires_rebalance_before_start": False,
  24. "requires_rebalance_before_stop": False,
  25. "safe_when_unbalanced": True,
  26. "can_run_with": ["grid_trader", "trend_follower"],
  27. }
  28. TICK_MINUTES = 0.2
  29. CONFIG_SCHEMA = {
  30. "trail_distance_pct": {"type": "float", "default": 0.03, "min": 0.0, "max": 1.0},
  31. "rebalance_target_ratio": {"type": "float", "default": 0.5, "min": 0.0, "max": 1.0},
  32. "rebalance_step_ratio": {"type": "float", "default": 0.15, "min": 0.0, "max": 1.0},
  33. "min_order_size": {"type": "float", "default": 0.0, "min": 0.0},
  34. "max_order_size": {"type": "float", "default": 0.0, "min": 0.0},
  35. "order_spacing_ticks": {"type": "int", "default": 1, "min": 0, "max": 1000},
  36. "cooldown_ticks": {"type": "int", "default": 2, "min": 0, "max": 1000},
  37. "min_rebalance_seconds": {"type": "int", "default": 180, "min": 0, "max": 86400},
  38. "min_price_move_pct": {"type": "float", "default": 0.005, "min": 0.0, "max": 1.0},
  39. "balance_tolerance": {"type": "float", "default": 0.05, "min": 0.0, "max": 1.0},
  40. "fee_rate": {"type": "float", "default": 0.0025, "min": 0.0, "max": 0.05},
  41. "debug_orders": {"type": "bool", "default": True},
  42. }
  43. STATE_SCHEMA = {
  44. "last_price": {"type": "float", "default": 0.0},
  45. "last_action": {"type": "string", "default": "idle"},
  46. "last_error": {"type": "string", "default": ""},
  47. "debug_log": {"type": "list", "default": []},
  48. "regimes": {"type": "dict", "default": {}},
  49. "regimes_updated_at": {"type": "string", "default": ""},
  50. "base_available": {"type": "float", "default": 0.0},
  51. "counter_available": {"type": "float", "default": 0.0},
  52. "trailing_anchor": {"type": "float", "default": 0.0},
  53. "cooldown_remaining": {"type": "int", "default": 0},
  54. "last_order_at": {"type": "float", "default": 0.0},
  55. "last_order_price": {"type": "float", "default": 0.0},
  56. }
  57. def init(self):
  58. return {
  59. "last_price": 0.0,
  60. "last_action": "idle",
  61. "last_error": "",
  62. "debug_log": ["init exposure protector"],
  63. "regimes": {},
  64. "regimes_updated_at": "",
  65. "base_available": 0.0,
  66. "counter_available": 0.0,
  67. "trailing_anchor": 0.0,
  68. "cooldown_remaining": 0,
  69. "last_order_at": 0.0,
  70. "last_order_price": 0.0,
  71. }
  72. def _log(self, message: str) -> None:
  73. state = getattr(self, "state", {}) or {}
  74. log = list(state.get("debug_log") or [])
  75. log.append(message)
  76. state["debug_log"] = log[-12:]
  77. self.state = state
  78. log_event("stoploss", message)
  79. def _base_symbol(self) -> str:
  80. return (self.context.base_currency or self.context.market_symbol or "XRP").split("/")[0].upper()
  81. def _market_symbol(self) -> str:
  82. return self.context.market_symbol or f"{self._base_symbol().lower()}usd"
  83. def apply_policy(self):
  84. policy = super().apply_policy()
  85. risk = str(policy.get("risk_posture") or "normal").lower()
  86. priority = str(policy.get("priority") or "normal").lower()
  87. trail_map = {"cautious": 0.02, "normal": 0.03, "assertive": 0.04}
  88. step_map = {"cautious": 0.08, "normal": 0.15, "assertive": 0.25}
  89. wait_map = {"cautious": 420, "normal": 180, "assertive": 90}
  90. move_map = {"cautious": 0.01, "normal": 0.005, "assertive": 0.003}
  91. if priority in {"low", "background"}:
  92. trail = trail_map.get("cautious", 0.02)
  93. step = step_map.get("cautious", 0.08)
  94. wait = wait_map.get("cautious", 600)
  95. move = move_map.get("cautious", 0.02)
  96. elif priority in {"high", "urgent"}:
  97. trail = trail_map.get("assertive", 0.04)
  98. step = step_map.get("assertive", 0.25)
  99. wait = wait_map.get("assertive", 120)
  100. move = move_map.get("assertive", 0.005)
  101. else:
  102. trail = trail_map.get(risk, 0.03)
  103. step = step_map.get(risk, 0.15)
  104. wait = wait_map.get(risk, 300)
  105. move = move_map.get(risk, 0.01)
  106. self.config["trail_distance_pct"] = trail
  107. self.config["rebalance_step_ratio"] = step
  108. self.config["min_rebalance_seconds"] = wait
  109. self.config["min_price_move_pct"] = move
  110. self.state["policy_derived"] = {
  111. "trail_distance_pct": trail,
  112. "rebalance_step_ratio": step,
  113. "min_rebalance_seconds": wait,
  114. "min_price_move_pct": move,
  115. }
  116. return policy
  117. def _live_fee_rate(self) -> float:
  118. try:
  119. payload = self.context.get_fee_rates(self._market_symbol())
  120. return float(payload.get("maker") or 0.0)
  121. except Exception as exc:
  122. self._log(f"fee lookup failed: {exc}")
  123. return float(self.config.get("fee_rate", 0.0025) or 0.0)
  124. def _price(self) -> float:
  125. payload = self.context.get_price(self._base_symbol())
  126. return float(payload.get("price") or 0.0)
  127. def _refresh_regimes(self) -> None:
  128. try:
  129. self.state["regimes"] = self.context.get_strategy_snapshot().get("fit", {}) if hasattr(self.context, "get_strategy_snapshot") else {}
  130. except Exception:
  131. self.state["regimes"] = {}
  132. self.state["regimes_updated_at"] = datetime.now(timezone.utc).isoformat()
  133. def _refresh_balance_snapshot(self) -> None:
  134. try:
  135. info = self.context.get_account_info()
  136. except Exception as exc:
  137. self._log(f"balance refresh failed: {exc}")
  138. return
  139. balances = info.get("balances") if isinstance(info, dict) else []
  140. if not isinstance(balances, list):
  141. return
  142. base = self._base_symbol()
  143. quote = str(self.context.counter_currency or "USD").upper()
  144. for balance in balances:
  145. if not isinstance(balance, dict):
  146. continue
  147. asset = str(balance.get("asset_code") or "").upper()
  148. try:
  149. available = float(balance.get("available") if balance.get("available") is not None else balance.get("total") or 0.0)
  150. except Exception:
  151. continue
  152. if asset == base:
  153. self.state["base_available"] = available
  154. if asset == quote:
  155. self.state["counter_available"] = available
  156. def _account_value_ratio(self, price: float) -> float:
  157. base_value = float(self.state.get("base_available") or 0.0) * price
  158. counter_value = float(self.state.get("counter_available") or 0.0)
  159. total = base_value + counter_value
  160. if total <= 0:
  161. return 0.5
  162. return base_value / total
  163. def _supervision(self) -> dict:
  164. price = float(self.state.get("last_price") or 0.0)
  165. ratio = self._account_value_ratio(price if price > 0 else 1.0)
  166. target = float(self.config.get("rebalance_target_ratio", 0.5) or 0.5)
  167. tolerance = float(self.config.get("balance_tolerance", 0.05) or 0.05)
  168. drift = abs(ratio - target)
  169. last_error = str(self.state.get("last_error") or "")
  170. if drift >= 0.35:
  171. pressure = "critical"
  172. elif drift > tolerance:
  173. pressure = "elevated"
  174. else:
  175. pressure = "contained"
  176. return {
  177. "health": "degraded" if last_error else "healthy",
  178. "degraded": bool(last_error),
  179. "inventory_pressure": pressure,
  180. "capacity_available": drift > tolerance,
  181. "switch_readiness": "handoff_complete" if drift <= tolerance else "stay_attached",
  182. "last_reason": last_error or f"base_ratio={ratio:.3f}, target={target:.3f}, drift={drift:.3f}",
  183. "desired_companion": None,
  184. }
  185. def _desired_side(self, price: float) -> str:
  186. # If base dominates, sell some into strength, otherwise buy some back.
  187. ratio = self._account_value_ratio(price)
  188. target = float(self.config.get("rebalance_target_ratio", 0.5) or 0.5)
  189. return "sell" if ratio > target else "buy"
  190. def _suggest_amount(self, side: str, price: float) -> float:
  191. fee_rate = self._live_fee_rate()
  192. step_ratio = float(self.config.get("rebalance_step_ratio", 0.15) or 0.0)
  193. target = float(self.config.get("rebalance_target_ratio", 0.5) or 0.5)
  194. min_order = float(self.config.get("min_order_size", 0.0) or 0.0)
  195. max_order = float(self.config.get("max_order_size", 0.0) or 0.0)
  196. balance_tolerance = float(self.config.get("balance_tolerance", 0.05) or 0.0)
  197. base_value = float(self.state.get("base_available") or 0.0) * price
  198. counter_value = float(self.state.get("counter_available") or 0.0)
  199. total = base_value + counter_value
  200. if total <= 0 or price <= 0:
  201. return 0.0
  202. current = base_value / total
  203. drift = abs(current - target)
  204. if drift <= balance_tolerance:
  205. return 0.0
  206. notional = total * min(drift, step_ratio)
  207. if side == "sell":
  208. amount = notional / (price * (1 + fee_rate))
  209. amount = min(amount, float(self.state.get("base_available") or 0.0))
  210. else:
  211. amount = notional / (price * (1 + fee_rate))
  212. amount = min(amount, float(self.state.get("counter_available") or 0.0) / price if price > 0 else 0.0)
  213. if min_order > 0:
  214. amount = max(amount, min_order)
  215. if max_order > 0:
  216. amount = min(amount, max_order)
  217. return max(amount, 0.0)
  218. def on_tick(self, tick):
  219. self.state["last_error"] = ""
  220. self._log(f"tick alive price={self.state.get('last_price') or 0.0}")
  221. self._refresh_balance_snapshot()
  222. self._refresh_regimes()
  223. price = self._price()
  224. self.state["last_price"] = price
  225. if int(self.state.get("cooldown_remaining") or 0) > 0:
  226. self.state["cooldown_remaining"] = int(self.state.get("cooldown_remaining") or 0) - 1
  227. self.state["last_action"] = "cooldown"
  228. return {"action": "cooldown", "price": price}
  229. now = datetime.now(timezone.utc).timestamp()
  230. last_order_at = float(self.state.get("last_order_at") or 0.0)
  231. min_rebalance_seconds = int(self.config.get("min_rebalance_seconds", 300) or 0)
  232. if last_order_at and min_rebalance_seconds > 0 and (now - last_order_at) < min_rebalance_seconds:
  233. self.state["last_action"] = "hold"
  234. return {"action": "hold", "price": price, "reason": "rebalance cooldown"}
  235. last_order_price = float(self.state.get("last_order_price") or 0.0)
  236. min_price_move_pct = float(self.config.get("min_price_move_pct", 0.01) or 0.0)
  237. if last_order_price > 0 and min_price_move_pct > 0:
  238. move_pct = abs(price - last_order_price) / last_order_price
  239. if move_pct < min_price_move_pct:
  240. self.state["last_action"] = "hold"
  241. return {"action": "hold", "price": price, "reason": "insufficient price move", "move_pct": move_pct}
  242. side = self._desired_side(price)
  243. amount = self._suggest_amount(side, price)
  244. trail_distance = float(self.config.get("trail_distance_pct", 0.03) or 0.03)
  245. if amount <= 0:
  246. self.state["last_action"] = "hold"
  247. return {"action": "hold", "price": price}
  248. try:
  249. market = self._market_symbol()
  250. if side == "sell":
  251. self.state["trailing_anchor"] = max(float(self.state.get("trailing_anchor") or 0.0), price)
  252. order_price = round(price * (1 - trail_distance), 8)
  253. else:
  254. self.state["trailing_anchor"] = min(float(self.state.get("trailing_anchor") or price), price) if self.state.get("trailing_anchor") else price
  255. order_price = round(price * (1 + trail_distance), 8)
  256. if self.config.get("debug_orders", True):
  257. self._log(f"{side} rebalance amount={amount:.6g} price={order_price} ratio={self._account_value_ratio(price):.4f}")
  258. result = self.context.place_order(
  259. side=side,
  260. order_type="limit",
  261. amount=amount,
  262. price=order_price,
  263. market=market,
  264. )
  265. self.state["cooldown_remaining"] = int(self.config.get("cooldown_ticks", 2) or 2)
  266. self.state["last_order_at"] = now
  267. self.state["last_order_price"] = order_price
  268. self.state["last_action"] = f"{side}_rebalance"
  269. return {"action": side, "price": order_price, "amount": amount, "result": result}
  270. except Exception as exc:
  271. self.state["last_error"] = str(exc)
  272. self._log(f"rebalance failed: {exc}")
  273. self.state["last_action"] = "error"
  274. return {"action": "error", "price": price, "error": str(exc)}
  275. def report(self):
  276. snapshot = self.context.get_strategy_snapshot() if hasattr(self.context, "get_strategy_snapshot") else {}
  277. return {
  278. "identity": snapshot.get("identity", {}),
  279. "control": snapshot.get("control", {}),
  280. "fit": dict(getattr(self, "STRATEGY_PROFILE", {}) or {}),
  281. "position": {
  282. "balances": {
  283. "base_available": self.state.get("base_available", 0.0),
  284. "counter_available": self.state.get("counter_available", 0.0),
  285. },
  286. "open_orders": snapshot.get("orders", {}).get("open_orders", []),
  287. "exposure": "managed",
  288. },
  289. "state": {
  290. "last_price": self.state.get("last_price", 0.0),
  291. "last_action": self.state.get("last_action", "idle"),
  292. "trailing_anchor": self.state.get("trailing_anchor", 0.0),
  293. "cooldown_remaining": self.state.get("cooldown_remaining", 0),
  294. "regimes_updated_at": self.state.get("regimes_updated_at", ""),
  295. },
  296. "assessment": {
  297. "confidence": None,
  298. "uncertainty": None,
  299. "reason": "defensive exposure protection",
  300. "warnings": [],
  301. "policy": dict(self.config.get("policy") or {}),
  302. },
  303. "execution": snapshot.get("execution", {}),
  304. "supervision": self._supervision(),
  305. }
  306. def render(self):
  307. return {
  308. "widgets": [
  309. {"type": "metric", "label": "market", "value": self._market_symbol()},
  310. {"type": "metric", "label": "price", "value": round(float(self.state.get("last_price") or 0.0), 6)},
  311. {"type": "metric", "label": "state", "value": self.state.get("last_action", "idle")},
  312. {"type": "metric", "label": "base avail", "value": round(float(self.state.get("base_available") or 0.0), 8)},
  313. {"type": "metric", "label": "counter avail", "value": round(float(self.state.get("counter_available") or 0.0), 8)},
  314. {"type": "metric", "label": "ratio", "value": round(self._account_value_ratio(float(self.state.get("last_price") or 0.0) or 1.0), 4)},
  315. {"type": "metric", "label": "trailing anchor", "value": round(float(self.state.get("trailing_anchor") or 0.0), 6)},
  316. {"type": "metric", "label": "cooldown", "value": int(self.state.get("cooldown_remaining") or 0)},
  317. {"type": "text", "label": "error", "value": self.state.get("last_error", "") or "none"},
  318. {"type": "log", "label": "debug log", "lines": self.state.get("debug_log") or []},
  319. ]
  320. }