exposure_protector.py 15 KB

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