exposure_protector.py 15 KB

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