stop_loss_trader.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. from __future__ import annotations
  2. from datetime import datetime, timezone
  3. from src.trader_mcp.strategy_sdk import Strategy
  4. class Strategy(Strategy):
  5. LABEL = "Stop Loss Rebalancer"
  6. TICK_MINUTES = 0.2
  7. CONFIG_SCHEMA = {
  8. "regime_timeframes": {"type": "list", "default": ["1d", "4h", "1h", "15m"]},
  9. "trend_enter_threshold": {"type": "float", "default": 0.7, "min": 0.0, "max": 1.0},
  10. "trend_exit_threshold": {"type": "float", "default": 0.45, "min": 0.0, "max": 1.0},
  11. "trail_distance_pct": {"type": "float", "default": 0.03, "min": 0.0, "max": 1.0},
  12. "rebalance_target_ratio": {"type": "float", "default": 0.5, "min": 0.0, "max": 1.0},
  13. "rebalance_step_ratio": {"type": "float", "default": 0.15, "min": 0.0, "max": 1.0},
  14. "min_order_size": {"type": "float", "default": 0.0, "min": 0.0},
  15. "max_order_size": {"type": "float", "default": 0.0, "min": 0.0},
  16. "order_spacing_ticks": {"type": "int", "default": 1, "min": 0, "max": 1000},
  17. "cooldown_ticks": {"type": "int", "default": 2, "min": 0, "max": 1000},
  18. "balance_tolerance": {"type": "float", "default": 0.05, "min": 0.0, "max": 1.0},
  19. "fee_rate": {"type": "float", "default": 0.0025, "min": 0.0, "max": 0.05},
  20. "debug_orders": {"type": "bool", "default": True},
  21. }
  22. STATE_SCHEMA = {
  23. "last_price": {"type": "float", "default": 0.0},
  24. "last_action": {"type": "string", "default": "idle"},
  25. "last_error": {"type": "string", "default": ""},
  26. "debug_log": {"type": "list", "default": []},
  27. "regimes": {"type": "dict", "default": {}},
  28. "regimes_updated_at": {"type": "string", "default": ""},
  29. "base_available": {"type": "float", "default": 0.0},
  30. "counter_available": {"type": "float", "default": 0.0},
  31. "trailing_anchor": {"type": "float", "default": 0.0},
  32. "cooldown_remaining": {"type": "int", "default": 0},
  33. }
  34. def init(self):
  35. return {
  36. "last_price": 0.0,
  37. "last_action": "idle",
  38. "last_error": "",
  39. "debug_log": ["init stop loss rebalancer"],
  40. "regimes": {},
  41. "regimes_updated_at": "",
  42. "base_available": 0.0,
  43. "counter_available": 0.0,
  44. "trailing_anchor": 0.0,
  45. "cooldown_remaining": 0,
  46. }
  47. def _log(self, message: str) -> None:
  48. state = getattr(self, "state", {}) or {}
  49. log = list(state.get("debug_log") or [])
  50. log.append(message)
  51. state["debug_log"] = log[-12:]
  52. self.state = state
  53. def _base_symbol(self) -> str:
  54. return (self.context.base_currency or self.context.market_symbol or "XRP").split("/")[0].upper()
  55. def _market_symbol(self) -> str:
  56. return self.context.market_symbol or f"{self._base_symbol().lower()}usd"
  57. def _price(self) -> float:
  58. payload = self.context.get_price(self._base_symbol())
  59. return float(payload.get("price") or 0.0)
  60. def _refresh_regimes(self) -> None:
  61. regimes: dict[str, dict] = {}
  62. for tf in self.config.get("regime_timeframes") or ["1d", "4h", "1h", "15m"]:
  63. try:
  64. regimes[str(tf)] = self.context.get_regime(self._base_symbol(), str(tf))
  65. except Exception as exc:
  66. regimes[str(tf)] = {"error": str(exc)}
  67. self.state["regimes"] = regimes
  68. self.state["regimes_updated_at"] = datetime.now(timezone.utc).isoformat()
  69. def _refresh_balance_snapshot(self) -> None:
  70. try:
  71. info = self.context.get_account_info()
  72. except Exception as exc:
  73. self._log(f"balance refresh failed: {exc}")
  74. return
  75. balances = info.get("balances") if isinstance(info, dict) else []
  76. if not isinstance(balances, list):
  77. return
  78. base = self._base_symbol()
  79. quote = str(self.context.counter_currency or "USD").upper()
  80. for balance in balances:
  81. if not isinstance(balance, dict):
  82. continue
  83. asset = str(balance.get("asset_code") or "").upper()
  84. try:
  85. available = float(balance.get("available") if balance.get("available") is not None else balance.get("total") or 0.0)
  86. except Exception:
  87. continue
  88. if asset == base:
  89. self.state["base_available"] = available
  90. if asset == quote:
  91. self.state["counter_available"] = available
  92. def _regime_strength(self) -> float:
  93. regimes = self.state.get("regimes") or {}
  94. strengths = []
  95. for tf in self.config.get("regime_timeframes") or []:
  96. regime = regimes.get(str(tf)) or {}
  97. trend = regime.get("trend") or {}
  98. strengths.append(float(trend.get("strength") or 0.0))
  99. return max(strengths) if strengths else 0.0
  100. def _is_trending(self) -> bool:
  101. strength = self._regime_strength()
  102. return strength >= float(self.config.get("trend_enter_threshold", 0.7) or 0.7)
  103. def _account_value_ratio(self, price: float) -> float:
  104. base_value = float(self.state.get("base_available") or 0.0) * price
  105. counter_value = float(self.state.get("counter_available") or 0.0)
  106. total = base_value + counter_value
  107. if total <= 0:
  108. return 0.5
  109. return base_value / total
  110. def _desired_side(self, price: float) -> str:
  111. # If base dominates, sell some into strength, otherwise buy some back.
  112. ratio = self._account_value_ratio(price)
  113. target = float(self.config.get("rebalance_target_ratio", 0.5) or 0.5)
  114. return "sell" if ratio > target else "buy"
  115. def _suggest_amount(self, side: str, price: float) -> float:
  116. fee_rate = float(self.config.get("fee_rate", 0.0025) or 0.0)
  117. step_ratio = float(self.config.get("rebalance_step_ratio", 0.15) or 0.0)
  118. target = float(self.config.get("rebalance_target_ratio", 0.5) or 0.5)
  119. min_order = float(self.config.get("min_order_size", 0.0) or 0.0)
  120. max_order = float(self.config.get("max_order_size", 0.0) or 0.0)
  121. balance_tolerance = float(self.config.get("balance_tolerance", 0.05) or 0.0)
  122. base_value = float(self.state.get("base_available") or 0.0) * price
  123. counter_value = float(self.state.get("counter_available") or 0.0)
  124. total = base_value + counter_value
  125. if total <= 0 or price <= 0:
  126. return 0.0
  127. current = base_value / total
  128. drift = abs(current - target)
  129. if drift <= balance_tolerance:
  130. return 0.0
  131. notional = total * min(drift, step_ratio)
  132. if side == "sell":
  133. amount = notional / (price * (1 + fee_rate))
  134. amount = min(amount, float(self.state.get("base_available") or 0.0))
  135. else:
  136. amount = notional / (price * (1 + fee_rate))
  137. amount = min(amount, float(self.state.get("counter_available") or 0.0) / price if price > 0 else 0.0)
  138. if min_order > 0:
  139. amount = max(amount, min_order)
  140. if max_order > 0:
  141. amount = min(amount, max_order)
  142. return max(amount, 0.0)
  143. def on_tick(self, tick):
  144. self.state["last_error"] = ""
  145. self._log(f"tick alive price={self.state.get('last_price') or 0.0}")
  146. self._refresh_balance_snapshot()
  147. self._refresh_regimes()
  148. price = self._price()
  149. self.state["last_price"] = price
  150. if int(self.state.get("cooldown_remaining") or 0) > 0:
  151. self.state["cooldown_remaining"] = int(self.state.get("cooldown_remaining") or 0) - 1
  152. self.state["last_action"] = "cooldown"
  153. return {"action": "cooldown", "price": price}
  154. if not self._is_trending():
  155. self.state["last_action"] = "standby"
  156. return {"action": "standby", "price": price}
  157. side = self._desired_side(price)
  158. amount = self._suggest_amount(side, price)
  159. trail_distance = float(self.config.get("trail_distance_pct", 0.03) or 0.03)
  160. if amount <= 0:
  161. self.state["last_action"] = "hold"
  162. return {"action": "hold", "price": price}
  163. try:
  164. market = self._market_symbol()
  165. if side == "sell":
  166. self.state["trailing_anchor"] = max(float(self.state.get("trailing_anchor") or 0.0), price)
  167. order_price = round(price * (1 + trail_distance), 8)
  168. else:
  169. self.state["trailing_anchor"] = min(float(self.state.get("trailing_anchor") or price), price) if self.state.get("trailing_anchor") else price
  170. order_price = round(price * (1 - trail_distance), 8)
  171. if self.config.get("debug_orders", True):
  172. self._log(f"{side} rebalance amount={amount:.6g} price={order_price} ratio={self._account_value_ratio(price):.4f}")
  173. result = self.context.place_order(
  174. side=side,
  175. order_type="limit",
  176. amount=amount,
  177. price=order_price,
  178. market=market,
  179. )
  180. self.state["cooldown_remaining"] = int(self.config.get("cooldown_ticks", 2) or 2)
  181. self.state["last_action"] = f"{side}_rebalance"
  182. return {"action": side, "price": order_price, "amount": amount, "result": result}
  183. except Exception as exc:
  184. self.state["last_error"] = str(exc)
  185. self._log(f"rebalance failed: {exc}")
  186. self.state["last_action"] = "error"
  187. return {"action": "error", "price": price, "error": str(exc)}
  188. def render(self):
  189. return {
  190. "widgets": [
  191. {"type": "metric", "label": "market", "value": self._market_symbol()},
  192. {"type": "metric", "label": "price", "value": round(float(self.state.get("last_price") or 0.0), 6)},
  193. {"type": "metric", "label": "state", "value": self.state.get("last_action", "idle")},
  194. {"type": "metric", "label": "base avail", "value": round(float(self.state.get("base_available") or 0.0), 8)},
  195. {"type": "metric", "label": "counter avail", "value": round(float(self.state.get("counter_available") or 0.0), 8)},
  196. {"type": "metric", "label": "ratio", "value": round(self._account_value_ratio(float(self.state.get("last_price") or 0.0) or 1.0), 4)},
  197. {"type": "metric", "label": "trailing anchor", "value": round(float(self.state.get("trailing_anchor") or 0.0), 6)},
  198. {"type": "metric", "label": "cooldown", "value": int(self.state.get("cooldown_remaining") or 0)},
  199. {"type": "text", "label": "error", "value": self.state.get("last_error", "") or "none"},
  200. {"type": "log", "label": "debug log", "lines": self.state.get("debug_log") or []},
  201. ]
  202. }