exposure_protector.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. from __future__ import annotations
  2. from datetime import datetime, timezone
  3. from src.trader_mcp.strategy_sizing import suggest_rebalance_amount
  4. from src.trader_mcp.strategy_sdk import Strategy
  5. from src.trader_mcp.logging_utils import log_event
  6. class Strategy(Strategy):
  7. LABEL = "Exposure Protector"
  8. STRATEGY_PROFILE = {
  9. "expects": {
  10. "trend": "mixed",
  11. "volatility": "moderate",
  12. "event_risk": "low",
  13. "liquidity": "normal",
  14. },
  15. "avoids": {
  16. "volatility": "chaotic",
  17. "event_risk": "high",
  18. "liquidity": "thin",
  19. },
  20. "risk_profile": "defensive",
  21. "capabilities": ["inventory_rebalancing", "exposure_trim", "companion_defense"],
  22. "role": "defensive",
  23. "inventory_behavior": "rebalancing",
  24. "requires_rebalance_before_start": False,
  25. "requires_rebalance_before_stop": False,
  26. "safe_when_unbalanced": True,
  27. "can_run_with": ["grid_trader", "dumb_trader"],
  28. }
  29. TICK_MINUTES = 0.2
  30. CONFIG_SCHEMA = {
  31. "trail_distance_pct": {"type": "float", "default": 0.03, "min": 0.0, "max": 1.0},
  32. "rebalance_target_ratio": {"type": "float", "default": 0.5, "min": 0.0, "max": 1.0},
  33. "rebalance_step_ratio": {"type": "float", "default": 0.15, "min": 0.0, "max": 1.0},
  34. "min_order_notional_quote": {"type": "float", "default": 0.0, "min": 0.0},
  35. "max_order_notional_quote": {"type": "float", "default": 0.0, "min": 0.0},
  36. "order_spacing_ticks": {"type": "int", "default": 1, "min": 0, "max": 1000},
  37. "cooldown_ticks": {"type": "int", "default": 2, "min": 0, "max": 1000},
  38. "min_rebalance_seconds": {"type": "int", "default": 180, "min": 0, "max": 86400},
  39. "min_price_move_pct": {"type": "float", "default": 0.005, "min": 0.0, "max": 1.0},
  40. "balance_tolerance": {"type": "float", "default": 0.05, "min": 0.0, "max": 1.0},
  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 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. repair_progress = max(0.0, 1.0 - min(drift / max(tolerance, 0.35), 1.0))
  171. concerns = []
  172. if drift > tolerance:
  173. concerns.append(f"inventory drift {drift:.3f} still above tolerance {tolerance:.3f}")
  174. if drift >= 0.35:
  175. concerns.append("inventory imbalance is critical")
  176. if last_error:
  177. concerns.append(last_error)
  178. if drift >= 0.35:
  179. pressure = "critical"
  180. elif drift > tolerance:
  181. pressure = "elevated"
  182. else:
  183. pressure = "contained"
  184. return {
  185. "health": "degraded" if last_error else "healthy",
  186. "degraded": bool(last_error),
  187. "inventory_pressure": pressure,
  188. "capacity_available": drift > tolerance,
  189. "rebalance_needed": drift > tolerance,
  190. "drift": round(drift, 6),
  191. "target_ratio": target,
  192. "repair_progress": round(repair_progress, 6),
  193. "concerns": concerns,
  194. "last_reason": last_error or f"base_ratio={ratio:.3f}, target={target:.3f}, drift={drift:.3f}",
  195. }
  196. def _desired_side(self, price: float) -> str:
  197. # If base dominates, sell some into strength, otherwise buy some back.
  198. ratio = self._account_value_ratio(price)
  199. target = float(self.config.get("rebalance_target_ratio", 0.5) or 0.5)
  200. step_ratio = float(self.config.get("rebalance_step_ratio", 0.15) or 0.0)
  201. tolerance = float(self.config.get("balance_tolerance", 0.05) or 0.0)
  202. hysteresis = max(tolerance, step_ratio * 0.5, 0.02)
  203. last_side = str(self.state.get("last_rebalance_side") or "").lower()
  204. if last_side == "sell":
  205. if ratio <= target - hysteresis:
  206. return "buy"
  207. if ratio >= target + hysteresis:
  208. return "sell"
  209. return ""
  210. if last_side == "buy":
  211. if ratio >= target + hysteresis:
  212. return "sell"
  213. if ratio <= target - hysteresis:
  214. return "buy"
  215. return ""
  216. if ratio > target + hysteresis:
  217. return "sell"
  218. if ratio < target - hysteresis:
  219. return "buy"
  220. return ""
  221. def _suggest_amount(self, side: str, price: float) -> float:
  222. return suggest_rebalance_amount(
  223. side=side,
  224. price=price,
  225. fee_rate=self._live_fee_rate(),
  226. base_available=float(self.state.get("base_available") or 0.0),
  227. counter_available=float(self.state.get("counter_available") or 0.0),
  228. target_ratio=float(self.config.get("rebalance_target_ratio", 0.5) or 0.5),
  229. step_ratio=float(self.config.get("rebalance_step_ratio", 0.15) or 0.0),
  230. balance_tolerance=float(self.config.get("balance_tolerance", 0.05) or 0.0),
  231. min_order_notional_quote=float(self.config.get("min_order_notional_quote") or self.config.get("min_order_size") or 0.0),
  232. max_order_notional_quote=float(self.config.get("max_order_notional_quote") or self.config.get("max_order_size") or 0.0),
  233. )
  234. def on_tick(self, tick):
  235. self.state["last_error"] = ""
  236. self._log(f"tick alive price={self.state.get('last_price') or 0.0}")
  237. self._refresh_balance_snapshot()
  238. self._refresh_regimes()
  239. price = self._price()
  240. self.state["last_price"] = price
  241. if int(self.state.get("cooldown_remaining") or 0) > 0:
  242. self.state["cooldown_remaining"] = int(self.state.get("cooldown_remaining") or 0) - 1
  243. self.state["last_action"] = "cooldown"
  244. return {"action": "cooldown", "price": price}
  245. now = datetime.now(timezone.utc).timestamp()
  246. last_order_at = float(self.state.get("last_order_at") or 0.0)
  247. min_rebalance_seconds = int(self.config.get("min_rebalance_seconds", 300) or 0)
  248. if last_order_at and min_rebalance_seconds > 0 and (now - last_order_at) < min_rebalance_seconds:
  249. self.state["last_action"] = "hold"
  250. return {"action": "hold", "price": price, "reason": "rebalance cooldown"}
  251. last_order_price = float(self.state.get("last_order_price") or 0.0)
  252. min_price_move_pct = float(self.config.get("min_price_move_pct", 0.01) or 0.0)
  253. if last_order_price > 0 and min_price_move_pct > 0:
  254. move_pct = abs(price - last_order_price) / last_order_price
  255. if move_pct < min_price_move_pct:
  256. self.state["last_action"] = "hold"
  257. return {"action": "hold", "price": price, "reason": "insufficient price move", "move_pct": move_pct}
  258. side = self._desired_side(price)
  259. if not side:
  260. self.state["last_action"] = "hold"
  261. return {"action": "hold", "price": price, "reason": "within rebalance hysteresis"}
  262. amount = self._suggest_amount(side, price)
  263. trail_distance = float(self.config.get("trail_distance_pct", 0.03) or 0.03)
  264. if amount <= 0:
  265. self.state["last_action"] = "hold"
  266. return {"action": "hold", "price": price}
  267. try:
  268. market = self._market_symbol()
  269. if side == "sell":
  270. self.state["trailing_anchor"] = max(float(self.state.get("trailing_anchor") or 0.0), price)
  271. order_price = round(price * (1 - trail_distance), 8)
  272. else:
  273. self.state["trailing_anchor"] = min(float(self.state.get("trailing_anchor") or price), price) if self.state.get("trailing_anchor") else price
  274. order_price = round(price * (1 + trail_distance), 8)
  275. if self.config.get("debug_orders", True):
  276. self._log(f"{side} rebalance amount={amount:.6g} price={order_price} ratio={self._account_value_ratio(price):.4f}")
  277. result = self.context.place_order(
  278. side=side,
  279. order_type="limit",
  280. amount=amount,
  281. price=order_price,
  282. market=market,
  283. )
  284. self.state["cooldown_remaining"] = int(self.config.get("cooldown_ticks", 2) or 2)
  285. self.state["last_order_at"] = now
  286. self.state["last_order_price"] = order_price
  287. self.state["last_rebalance_side"] = side
  288. self.state["last_action"] = f"{side}_rebalance"
  289. return {"action": side, "price": order_price, "amount": amount, "result": result}
  290. except Exception as exc:
  291. self.state["last_error"] = str(exc)
  292. self._log(f"rebalance failed: {exc}")
  293. self.state["last_action"] = "error"
  294. return {"action": "error", "price": price, "error": str(exc)}
  295. def report(self):
  296. snapshot = self.context.get_strategy_snapshot() if hasattr(self.context, "get_strategy_snapshot") else {}
  297. return {
  298. "identity": snapshot.get("identity", {}),
  299. "control": snapshot.get("control", {}),
  300. "fit": dict(getattr(self, "STRATEGY_PROFILE", {}) or {}),
  301. "position": {
  302. "balances": {
  303. "base_available": self.state.get("base_available", 0.0),
  304. "counter_available": self.state.get("counter_available", 0.0),
  305. },
  306. "open_orders": snapshot.get("orders", {}).get("open_orders", []),
  307. "exposure": "managed",
  308. },
  309. "state": {
  310. "last_price": self.state.get("last_price", 0.0),
  311. "last_action": self.state.get("last_action", "idle"),
  312. "trailing_anchor": self.state.get("trailing_anchor", 0.0),
  313. "cooldown_remaining": self.state.get("cooldown_remaining", 0),
  314. "regimes_updated_at": self.state.get("regimes_updated_at", ""),
  315. },
  316. "assessment": {
  317. "confidence": None,
  318. "uncertainty": None,
  319. "reason": "defensive exposure protection",
  320. "warnings": [w for w in (self._supervision().get("concerns") or []) if w],
  321. "policy": dict(self.config.get("policy") or {}),
  322. },
  323. "execution": snapshot.get("execution", {}),
  324. "supervision": self._supervision(),
  325. }
  326. def render(self):
  327. return {
  328. "widgets": [
  329. {"type": "metric", "label": "market", "value": self._market_symbol()},
  330. {"type": "metric", "label": "price", "value": round(float(self.state.get("last_price") or 0.0), 6)},
  331. {"type": "metric", "label": "state", "value": self.state.get("last_action", "idle")},
  332. {"type": "metric", "label": "base avail", "value": round(float(self.state.get("base_available") or 0.0), 8)},
  333. {"type": "metric", "label": "counter avail", "value": round(float(self.state.get("counter_available") or 0.0), 8)},
  334. {"type": "metric", "label": "ratio", "value": round(self._account_value_ratio(float(self.state.get("last_price") or 0.0) or 1.0), 4)},
  335. {"type": "metric", "label": "trailing anchor", "value": round(float(self.state.get("trailing_anchor") or 0.0), 6)},
  336. {"type": "metric", "label": "cooldown", "value": int(self.state.get("cooldown_remaining") or 0)},
  337. {"type": "text", "label": "error", "value": self.state.get("last_error", "") or "none"},
  338. {"type": "log", "label": "debug log", "lines": self.state.get("debug_log") or []},
  339. ]
  340. }