trend_follower.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. from __future__ import annotations
  2. from datetime import datetime, timezone
  3. from src.trader_mcp.strategy_sizing import cap_amount_to_balance_target, suggest_quote_sized_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 = "Trend Follower"
  8. STRATEGY_PROFILE = {
  9. "expects": {
  10. "trend": "strong",
  11. "volatility": "moderate",
  12. "event_risk": "low",
  13. "liquidity": "normal",
  14. },
  15. "avoids": {
  16. "trend": "range",
  17. "volatility": "chaotic",
  18. "event_risk": "high",
  19. "liquidity": "thin",
  20. },
  21. "risk_profile": "growth",
  22. "capabilities": ["directional_continuation", "momentum_following", "inventory_accumulation"],
  23. "role": "primary",
  24. "inventory_behavior": "accumulative_long",
  25. "requires_rebalance_before_start": False,
  26. "requires_rebalance_before_stop": False,
  27. "safe_when_unbalanced": True,
  28. "can_run_with": ["exposure_protector"],
  29. }
  30. TICK_MINUTES = 0.5
  31. CONFIG_SCHEMA = {
  32. "trade_side": {"type": "string", "default": "both"},
  33. "balance_target": {"type": "float", "default": 1.0, "min": 0.0, "max": 1.0},
  34. "entry_offset_pct": {"type": "float", "default": 0.003, "min": 0.0, "max": 1.0},
  35. "exit_offset_pct": {"type": "float", "default": 0.002, "min": 0.0, "max": 1.0},
  36. "order_notional_quote": {"type": "float", "default": 0.0, "min": 0.0},
  37. "max_order_notional_quote": {"type": "float", "default": 0.0, "min": 0.0},
  38. "dust_collect": {"type": "bool", "default": False},
  39. "cooldown_ticks": {"type": "int", "default": 2, "min": 0, "max": 1000},
  40. "debug_orders": {"type": "bool", "default": True},
  41. }
  42. STATE_SCHEMA = {
  43. "last_price": {"type": "float", "default": 0.0},
  44. "last_action": {"type": "string", "default": "idle"},
  45. "last_error": {"type": "string", "default": ""},
  46. "debug_log": {"type": "list", "default": []},
  47. "trade_side": {"type": "string", "default": "both"},
  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. "base_available": {"type": "float", "default": 0.0},
  52. "counter_available": {"type": "float", "default": 0.0},
  53. }
  54. def init(self):
  55. return {
  56. "last_price": 0.0,
  57. "last_action": "idle",
  58. "last_error": "",
  59. "debug_log": ["init trend follower"],
  60. "trade_side": "both",
  61. "cooldown_remaining": 0,
  62. "last_order_at": 0.0,
  63. "last_order_price": 0.0,
  64. "base_available": 0.0,
  65. "counter_available": 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("trend", 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 _trade_side(self) -> str:
  79. side = str(self.config.get("trade_side") or "both").strip().lower()
  80. return side if side in {"buy", "sell", "both"} else "both"
  81. def _price(self) -> float:
  82. payload = self.context.get_price(self._base_symbol())
  83. return float(payload.get("price") or 0.0)
  84. def _live_fee_rate(self) -> float:
  85. try:
  86. payload = self.context.get_fee_rates(self._market_symbol())
  87. return float(payload.get("maker") or payload.get("taker") or 0.0)
  88. except Exception as exc:
  89. self._log(f"fee lookup failed: {exc}")
  90. return 0.0
  91. def _refresh_balance_snapshot(self) -> None:
  92. try:
  93. info = self.context.get_account_info()
  94. except Exception as exc:
  95. self._log(f"balance refresh failed: {exc}")
  96. return
  97. balances = info.get("balances") if isinstance(info, dict) else []
  98. if not isinstance(balances, list):
  99. return
  100. base = self._base_symbol()
  101. quote = str(self.context.counter_currency or "USD").upper()
  102. for balance in balances:
  103. if not isinstance(balance, dict):
  104. continue
  105. asset = str(balance.get("asset_code") or "").upper()
  106. try:
  107. available = float(balance.get("available") if balance.get("available") is not None else balance.get("total") or 0.0)
  108. except Exception:
  109. continue
  110. if asset == base:
  111. self.state["base_available"] = available
  112. if asset == quote:
  113. self.state["counter_available"] = available
  114. def _supervision(self) -> dict:
  115. last_error = str(self.state.get("last_error") or "")
  116. side = self._trade_side()
  117. pressure = "balanced" if side in {"buy", "sell"} else "unknown"
  118. balance_target = self._balance_target()
  119. base_ratio = self._account_value_ratio(float(self.state.get("last_price") or 0.0))
  120. quote_ratio = max(0.0, 1.0 - base_ratio)
  121. entry_offset_pct = float(self.config.get("entry_offset_pct") or 0.003)
  122. exit_offset_pct = float(self.config.get("exit_offset_pct") or 0.002)
  123. last_order_at = float(self.state.get("last_order_at") or 0.0)
  124. now_ts = datetime.now(timezone.utc).timestamp()
  125. last_order_age_seconds = round(max(now_ts - last_order_at, 0.0), 3) if last_order_at > 0 else None
  126. if entry_offset_pct <= 0.0015:
  127. chasing_risk = "elevated"
  128. elif entry_offset_pct <= 0.0035:
  129. chasing_risk = "moderate"
  130. else:
  131. chasing_risk = "low"
  132. concerns = []
  133. if side == "both":
  134. concerns.append("generic trend instance relies on Hermes for direction")
  135. if chasing_risk == "elevated":
  136. concerns.append("entry offset is tight and may chase price")
  137. return {
  138. "health": "degraded" if last_error else "healthy",
  139. "degraded": bool(last_error),
  140. "inventory_pressure": pressure,
  141. "capacity_available": side in {"buy", "sell"},
  142. "trade_side": side,
  143. "balance_target": round(balance_target, 6),
  144. "base_ratio": round(base_ratio, 6),
  145. "quote_ratio": round(quote_ratio, 6),
  146. "entry_offset_pct": round(entry_offset_pct, 6),
  147. "exit_offset_pct": round(exit_offset_pct, 6),
  148. "order_notional_quote": float(self.config.get("order_notional_quote") or 0.0),
  149. "max_order_notional_quote": float(self.config.get("max_order_notional_quote") or 0.0),
  150. "dust_collect": bool(self.config.get("dust_collect", False)),
  151. "last_order_age_seconds": last_order_age_seconds,
  152. "last_order_price": float(self.state.get("last_order_price") or 0.0),
  153. "chasing_risk": chasing_risk,
  154. "concerns": concerns,
  155. "last_reason": last_error or f"trade_side={side}",
  156. }
  157. def apply_policy(self):
  158. policy = super().apply_policy()
  159. quote_notional = float(self.config.get("order_notional_quote") or 0.0)
  160. max_quote_notional = float(self.config.get("max_order_notional_quote") or 0.0)
  161. self.state["policy_derived"] = {
  162. "trade_side": self._trade_side(),
  163. "balance_target": self._balance_target(),
  164. "entry_offset_pct": float(self.config.get("entry_offset_pct") or 0.003),
  165. "exit_offset_pct": float(self.config.get("exit_offset_pct") or 0.002),
  166. "cooldown_ticks": int(self.config.get("cooldown_ticks") or 2),
  167. "order_notional_quote": quote_notional,
  168. "max_order_notional_quote": max_quote_notional,
  169. "dust_collect": bool(self.config.get("dust_collect", False)),
  170. }
  171. return policy
  172. def _balance_target(self) -> float:
  173. try:
  174. target = float(self.config.get("balance_target") if self.config.get("balance_target") is not None else 1.0)
  175. except Exception:
  176. return 1.0
  177. return min(max(target, 0.0), 1.0)
  178. def _account_value_ratio(self, price: float) -> float:
  179. if price <= 0:
  180. return 0.5
  181. base_value = float(self.state.get("base_available") or 0.0) * price
  182. counter_value = float(self.state.get("counter_available") or 0.0)
  183. total = base_value + counter_value
  184. if total <= 0:
  185. return 0.5
  186. return base_value / total
  187. def _balance_target_reached(self, side: str, price: float) -> bool:
  188. target = self._balance_target()
  189. if target >= 1.0:
  190. return False
  191. base_ratio = self._account_value_ratio(price)
  192. if side == "buy":
  193. return base_ratio >= target
  194. if side == "sell":
  195. return (1.0 - base_ratio) >= target
  196. return False
  197. def _suggest_amount(self, price: float, side: str) -> float:
  198. min_notional = float(self.context.minimum_order_value or 0.0)
  199. fee_rate = self._live_fee_rate()
  200. amount = suggest_quote_sized_amount(
  201. self.context,
  202. side=side,
  203. price=price,
  204. levels=1,
  205. min_notional=min_notional,
  206. fee_rate=fee_rate,
  207. order_notional_quote=float(self.config.get("order_notional_quote") or 0.0),
  208. max_order_notional_quote=float(self.config.get("max_order_notional_quote") or 0.0),
  209. dust_collect=bool(self.config.get("dust_collect", False)),
  210. )
  211. return cap_amount_to_balance_target(
  212. suggested_amount=amount,
  213. side=side,
  214. price=price,
  215. fee_rate=fee_rate,
  216. balance_target=self._balance_target(),
  217. base_available=float(self.state.get("base_available") or 0.0),
  218. counter_available=float(self.state.get("counter_available") or 0.0),
  219. min_notional=min_notional,
  220. )
  221. def on_tick(self, tick):
  222. self.state["last_error"] = ""
  223. self._log(f"tick alive price={self.state.get('last_price') or 0.0}")
  224. self._refresh_balance_snapshot()
  225. price = self._price()
  226. self.state["last_price"] = price
  227. if int(self.state.get("cooldown_remaining") or 0) > 0:
  228. self.state["cooldown_remaining"] = int(self.state.get("cooldown_remaining") or 0) - 1
  229. self.state["last_action"] = "cooldown"
  230. return {"action": "cooldown", "price": price}
  231. side = self._trade_side()
  232. if side not in {"buy", "sell"}:
  233. self.state["last_action"] = "hold"
  234. return {"action": "hold", "price": price, "reason": "trade_side must be buy or sell"}
  235. if self._balance_target_reached(side, price):
  236. self.state["last_action"] = "target_reached"
  237. return {"action": "hold", "price": price, "reason": "balance target reached"}
  238. amount = self._suggest_amount(price, side)
  239. if amount <= 0:
  240. self.state["last_action"] = "hold"
  241. return {"action": "hold", "price": price, "reason": "no usable size"}
  242. offset = float(self.config.get("entry_offset_pct", 0.003) or 0.0)
  243. if side == "buy":
  244. order_price = round(price * (1 + offset), 8)
  245. else:
  246. order_price = round(price * (1 - offset), 8)
  247. try:
  248. if self.config.get("debug_orders", True):
  249. self._log(f"{side} trend amount={amount:.6g} price={order_price}")
  250. result = self.context.place_order(
  251. side=side,
  252. order_type="limit",
  253. amount=amount,
  254. price=order_price,
  255. market=self._market_symbol(),
  256. )
  257. self.state["cooldown_remaining"] = int(self.config.get("cooldown_ticks", 2) or 2)
  258. self.state["last_order_at"] = datetime.now(timezone.utc).timestamp()
  259. self.state["last_order_price"] = order_price
  260. self.state["last_action"] = f"{side}_trend"
  261. return {"action": side, "price": order_price, "amount": amount, "result": result}
  262. except Exception as exc:
  263. self.state["last_error"] = str(exc)
  264. self._log(f"trend order failed: {exc}")
  265. self.state["last_action"] = "error"
  266. return {"action": "error", "price": price, "error": str(exc)}
  267. def report(self):
  268. snapshot = self.context.get_strategy_snapshot() if hasattr(self.context, "get_strategy_snapshot") else {}
  269. return {
  270. "identity": snapshot.get("identity", {}),
  271. "control": snapshot.get("control", {}),
  272. "fit": dict(getattr(self, "STRATEGY_PROFILE", {}) or {}),
  273. "position": snapshot.get("position", {}),
  274. "state": {
  275. "last_price": self.state.get("last_price", 0.0),
  276. "last_action": self.state.get("last_action", "idle"),
  277. "trade_side": self._trade_side(),
  278. "balance_target": self._balance_target(),
  279. "order_notional_quote": float(self.config.get("order_notional_quote") or 0.0),
  280. "max_order_notional_quote": float(self.config.get("max_order_notional_quote") or 0.0),
  281. "dust_collect": bool(self.config.get("dust_collect", False)),
  282. "cooldown_remaining": self.state.get("cooldown_remaining", 0),
  283. "base_available": self.state.get("base_available", 0.0),
  284. "counter_available": self.state.get("counter_available", 0.0),
  285. },
  286. "assessment": {
  287. "confidence": None,
  288. "uncertainty": None,
  289. "reason": "trend capture",
  290. "warnings": [w for w in (self._supervision().get("concerns") or []) if w],
  291. "policy": dict(self.config.get("policy") or {}),
  292. },
  293. "execution": snapshot.get("execution", {}),
  294. "supervision": self._supervision(),
  295. }
  296. def render(self):
  297. return {
  298. "widgets": [
  299. {"type": "metric", "label": "market", "value": self._market_symbol()},
  300. {"type": "metric", "label": "price", "value": round(float(self.state.get("last_price") or 0.0), 6)},
  301. {"type": "metric", "label": "side", "value": self._trade_side()},
  302. {"type": "metric", "label": "balance target", "value": round(self._balance_target(), 6)},
  303. {"type": "metric", "label": "quote notional", "value": round(float(self.config.get("order_notional_quote") or 0.0), 6)},
  304. {"type": "metric", "label": "dust collect", "value": bool(self.config.get("dust_collect", False))},
  305. {"type": "metric", "label": "state", "value": self.state.get("last_action", "idle")},
  306. {"type": "metric", "label": "cooldown", "value": int(self.state.get("cooldown_remaining") or 0)},
  307. {"type": "text", "label": "error", "value": self.state.get("last_error", "") or "none"},
  308. {"type": "log", "label": "debug log", "lines": self.state.get("debug_log") or []},
  309. ]
  310. }