trend_follower.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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 = "Trend Follower"
  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": "growth",
  21. "capabilities": ["directional_continuation", "momentum_following", "inventory_accumulation"],
  22. "role": "primary",
  23. "inventory_behavior": "accumulative_long",
  24. "requires_rebalance_before_start": False,
  25. "requires_rebalance_before_stop": False,
  26. "safe_when_unbalanced": True,
  27. "can_run_with": ["exposure_protector"],
  28. }
  29. TICK_MINUTES = 0.5
  30. CONFIG_SCHEMA = {
  31. "trade_side": {"type": "string", "default": "both"},
  32. "entry_offset_pct": {"type": "float", "default": 0.003, "min": 0.0, "max": 1.0},
  33. "exit_offset_pct": {"type": "float", "default": 0.002, "min": 0.0, "max": 1.0},
  34. "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. "cooldown_ticks": {"type": "int", "default": 2, "min": 0, "max": 1000},
  37. "debug_orders": {"type": "bool", "default": True},
  38. }
  39. STATE_SCHEMA = {
  40. "last_price": {"type": "float", "default": 0.0},
  41. "last_action": {"type": "string", "default": "idle"},
  42. "last_error": {"type": "string", "default": ""},
  43. "debug_log": {"type": "list", "default": []},
  44. "trade_side": {"type": "string", "default": "both"},
  45. "cooldown_remaining": {"type": "int", "default": 0},
  46. "last_order_at": {"type": "float", "default": 0.0},
  47. "last_order_price": {"type": "float", "default": 0.0},
  48. "base_available": {"type": "float", "default": 0.0},
  49. "counter_available": {"type": "float", "default": 0.0},
  50. }
  51. def init(self):
  52. return {
  53. "last_price": 0.0,
  54. "last_action": "idle",
  55. "last_error": "",
  56. "debug_log": ["init trend follower"],
  57. "trade_side": "both",
  58. "cooldown_remaining": 0,
  59. "last_order_at": 0.0,
  60. "last_order_price": 0.0,
  61. "base_available": 0.0,
  62. "counter_available": 0.0,
  63. }
  64. def _log(self, message: str) -> None:
  65. state = getattr(self, "state", {}) or {}
  66. log = list(state.get("debug_log") or [])
  67. log.append(message)
  68. state["debug_log"] = log[-12:]
  69. self.state = state
  70. log_event("trend", message)
  71. def _base_symbol(self) -> str:
  72. return (self.context.base_currency or self.context.market_symbol or "XRP").split("/")[0].upper()
  73. def _market_symbol(self) -> str:
  74. return self.context.market_symbol or f"{self._base_symbol().lower()}usd"
  75. def _trade_side(self) -> str:
  76. side = str(self.config.get("trade_side") or "both").strip().lower()
  77. return side if side in {"buy", "sell", "both"} else "both"
  78. def _price(self) -> float:
  79. payload = self.context.get_price(self._base_symbol())
  80. return float(payload.get("price") or 0.0)
  81. def _live_fee_rate(self) -> float:
  82. try:
  83. payload = self.context.get_fee_rates(self._market_symbol())
  84. return float(payload.get("maker") or payload.get("taker") or 0.0)
  85. except Exception as exc:
  86. self._log(f"fee lookup failed: {exc}")
  87. return 0.0
  88. def _refresh_balance_snapshot(self) -> None:
  89. try:
  90. info = self.context.get_account_info()
  91. except Exception as exc:
  92. self._log(f"balance refresh failed: {exc}")
  93. return
  94. balances = info.get("balances") if isinstance(info, dict) else []
  95. if not isinstance(balances, list):
  96. return
  97. base = self._base_symbol()
  98. quote = str(self.context.counter_currency or "USD").upper()
  99. for balance in balances:
  100. if not isinstance(balance, dict):
  101. continue
  102. asset = str(balance.get("asset_code") or "").upper()
  103. try:
  104. available = float(balance.get("available") if balance.get("available") is not None else balance.get("total") or 0.0)
  105. except Exception:
  106. continue
  107. if asset == base:
  108. self.state["base_available"] = available
  109. if asset == quote:
  110. self.state["counter_available"] = available
  111. def _supervision(self) -> dict:
  112. last_error = str(self.state.get("last_error") or "")
  113. side = self._trade_side()
  114. pressure = "balanced" if side in {"buy", "sell"} else "unknown"
  115. entry_offset_pct = float(self.config.get("entry_offset_pct") or 0.003)
  116. exit_offset_pct = float(self.config.get("exit_offset_pct") or 0.002)
  117. last_order_at = float(self.state.get("last_order_at") or 0.0)
  118. now_ts = datetime.now(timezone.utc).timestamp()
  119. last_order_age_seconds = round(max(now_ts - last_order_at, 0.0), 3) if last_order_at > 0 else None
  120. if entry_offset_pct <= 0.0015:
  121. chasing_risk = "elevated"
  122. elif entry_offset_pct <= 0.0035:
  123. chasing_risk = "moderate"
  124. else:
  125. chasing_risk = "low"
  126. concerns = []
  127. if side == "both":
  128. concerns.append("generic trend instance relies on Hermes for direction")
  129. if chasing_risk == "elevated":
  130. concerns.append("entry offset is tight and may chase price")
  131. return {
  132. "health": "degraded" if last_error else "healthy",
  133. "degraded": bool(last_error),
  134. "inventory_pressure": pressure,
  135. "capacity_available": side in {"buy", "sell"},
  136. "trade_side": side,
  137. "entry_offset_pct": round(entry_offset_pct, 6),
  138. "exit_offset_pct": round(exit_offset_pct, 6),
  139. "order_notional_quote": float(self.config.get("order_notional_quote") or 0.0),
  140. "max_order_notional_quote": float(self.config.get("max_order_notional_quote") or 0.0),
  141. "last_order_age_seconds": last_order_age_seconds,
  142. "last_order_price": float(self.state.get("last_order_price") or 0.0),
  143. "chasing_risk": chasing_risk,
  144. "concerns": concerns,
  145. "last_reason": last_error or f"trade_side={side}",
  146. }
  147. def apply_policy(self):
  148. policy = super().apply_policy()
  149. quote_notional = float(self.config.get("order_notional_quote") or 0.0)
  150. max_quote_notional = float(self.config.get("max_order_notional_quote") or 0.0)
  151. self.state["policy_derived"] = {
  152. "trade_side": self._trade_side(),
  153. "entry_offset_pct": float(self.config.get("entry_offset_pct") or 0.003),
  154. "exit_offset_pct": float(self.config.get("exit_offset_pct") or 0.002),
  155. "cooldown_ticks": int(self.config.get("cooldown_ticks") or 2),
  156. "order_notional_quote": quote_notional,
  157. "max_order_notional_quote": max_quote_notional,
  158. }
  159. return policy
  160. def _suggest_amount(self, price: float, side: str) -> float:
  161. min_notional = float(self.context.minimum_order_value or 0.0)
  162. quote_notional = float(self.config.get("order_notional_quote") or 0.0)
  163. max_quote_notional = float(self.config.get("max_order_notional_quote") or 0.0)
  164. if hasattr(self.context, "suggest_order_amount"):
  165. kwargs = {
  166. "side": side,
  167. "price": price,
  168. "levels": 1,
  169. "min_notional": min_notional,
  170. "fee_rate": self._live_fee_rate(),
  171. "quote_notional": quote_notional,
  172. "max_notional_per_order": max_quote_notional,
  173. }
  174. try:
  175. return float(self.context.suggest_order_amount(**kwargs) or 0.0)
  176. except TypeError:
  177. kwargs.pop("quote_notional", None)
  178. return float(self.context.suggest_order_amount(**kwargs) or 0.0)
  179. if quote_notional <= 0:
  180. return 0.0
  181. amount = quote_notional / price
  182. if max_quote_notional > 0:
  183. amount = min(amount, max_quote_notional / price)
  184. return max(amount, 0.0)
  185. def on_tick(self, tick):
  186. self.state["last_error"] = ""
  187. self._log(f"tick alive price={self.state.get('last_price') or 0.0}")
  188. self._refresh_balance_snapshot()
  189. price = self._price()
  190. self.state["last_price"] = price
  191. if int(self.state.get("cooldown_remaining") or 0) > 0:
  192. self.state["cooldown_remaining"] = int(self.state.get("cooldown_remaining") or 0) - 1
  193. self.state["last_action"] = "cooldown"
  194. return {"action": "cooldown", "price": price}
  195. side = self._trade_side()
  196. if side not in {"buy", "sell"}:
  197. self.state["last_action"] = "hold"
  198. return {"action": "hold", "price": price, "reason": "trade_side must be buy or sell"}
  199. amount = self._suggest_amount(price, side)
  200. if amount <= 0:
  201. self.state["last_action"] = "hold"
  202. return {"action": "hold", "price": price, "reason": "no usable size"}
  203. offset = float(self.config.get("entry_offset_pct", 0.003) or 0.0)
  204. if side == "buy":
  205. order_price = round(price * (1 + offset), 8)
  206. else:
  207. order_price = round(price * (1 - offset), 8)
  208. try:
  209. if self.config.get("debug_orders", True):
  210. self._log(f"{side} trend amount={amount:.6g} price={order_price}")
  211. result = self.context.place_order(
  212. side=side,
  213. order_type="limit",
  214. amount=amount,
  215. price=order_price,
  216. market=self._market_symbol(),
  217. )
  218. self.state["cooldown_remaining"] = int(self.config.get("cooldown_ticks", 2) or 2)
  219. self.state["last_order_at"] = datetime.now(timezone.utc).timestamp()
  220. self.state["last_order_price"] = order_price
  221. self.state["last_action"] = f"{side}_trend"
  222. return {"action": side, "price": order_price, "amount": amount, "result": result}
  223. except Exception as exc:
  224. self.state["last_error"] = str(exc)
  225. self._log(f"trend order failed: {exc}")
  226. self.state["last_action"] = "error"
  227. return {"action": "error", "price": price, "error": str(exc)}
  228. def report(self):
  229. snapshot = self.context.get_strategy_snapshot() if hasattr(self.context, "get_strategy_snapshot") else {}
  230. return {
  231. "identity": snapshot.get("identity", {}),
  232. "control": snapshot.get("control", {}),
  233. "fit": dict(getattr(self, "STRATEGY_PROFILE", {}) or {}),
  234. "position": snapshot.get("position", {}),
  235. "state": {
  236. "last_price": self.state.get("last_price", 0.0),
  237. "last_action": self.state.get("last_action", "idle"),
  238. "trade_side": self._trade_side(),
  239. "order_notional_quote": float(self.config.get("order_notional_quote") or 0.0),
  240. "max_order_notional_quote": float(self.config.get("max_order_notional_quote") or 0.0),
  241. "cooldown_remaining": self.state.get("cooldown_remaining", 0),
  242. "base_available": self.state.get("base_available", 0.0),
  243. "counter_available": self.state.get("counter_available", 0.0),
  244. },
  245. "assessment": {
  246. "confidence": None,
  247. "uncertainty": None,
  248. "reason": "trend capture",
  249. "warnings": [w for w in (self._supervision().get("concerns") or []) if w],
  250. "policy": dict(self.config.get("policy") or {}),
  251. },
  252. "execution": snapshot.get("execution", {}),
  253. "supervision": self._supervision(),
  254. }
  255. def render(self):
  256. return {
  257. "widgets": [
  258. {"type": "metric", "label": "market", "value": self._market_symbol()},
  259. {"type": "metric", "label": "price", "value": round(float(self.state.get("last_price") or 0.0), 6)},
  260. {"type": "metric", "label": "side", "value": self._trade_side()},
  261. {"type": "metric", "label": "quote notional", "value": round(float(self.config.get("order_notional_quote") or 0.0), 6)},
  262. {"type": "metric", "label": "state", "value": self.state.get("last_action", "idle")},
  263. {"type": "metric", "label": "cooldown", "value": int(self.state.get("cooldown_remaining") or 0)},
  264. {"type": "text", "label": "error", "value": self.state.get("last_error", "") or "none"},
  265. {"type": "log", "label": "debug log", "lines": self.state.get("debug_log") or []},
  266. ]
  267. }