grid_trader.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  1. from __future__ import annotations
  2. import time
  3. from datetime import datetime, timezone
  4. from src.trader_mcp.strategy_sdk import Strategy
  5. class Strategy(Strategy):
  6. LABEL = "Grid Trader"
  7. TICK_MINUTES = 0.2
  8. # NOTE:
  9. # This strategy is currently using a protective workaround for stale order state,
  10. # because exec-mcp can temporarily report order records that do not reflect the
  11. # clean post-reset strategy state. The grid prefers its own fresh persisted state
  12. # first, so the real exchange behavior stays testable while exec-mcp is improved.
  13. # Expect the reconciliation behavior to change again once exec-mcp is fixed.
  14. CONFIG_SCHEMA = {
  15. "grid_levels": {"type": "int", "default": 6, "min": 1, "max": 20},
  16. "grid_step_pct": {"type": "float", "default": 0.012, "min": 0.001, "max": 0.1},
  17. "volatility_timeframe": {"type": "string", "default": "1h"},
  18. "volatility_multiplier": {"type": "float", "default": 0.5, "min": 0.0, "max": 10.0},
  19. "grid_step_min_pct": {"type": "float", "default": 0.005, "min": 0.0001, "max": 0.5},
  20. "grid_step_max_pct": {"type": "float", "default": 0.03, "min": 0.0001, "max": 1.0},
  21. "order_size": {"type": "float", "default": 0.0, "min": 0.0},
  22. "inventory_cap_pct": {"type": "float", "default": 0.7, "min": 0.0, "max": 1.0},
  23. "recenter_pct": {"type": "float", "default": 0.05, "min": 0.0, "max": 0.5},
  24. "fee_rate": {"type": "float", "default": 0.0025, "min": 0.0, "max": 0.05},
  25. "trade_sides": {"type": "string", "default": "both"},
  26. "max_notional_per_order": {"type": "float", "default": 0.0, "min": 0.0},
  27. "order_call_delay_ms": {"type": "int", "default": 250, "min": 0, "max": 10000},
  28. "enable_trend_guard": {"type": "bool", "default": True},
  29. "trend_guard_reversal_max": {"type": "float", "default": 0.25, "min": 0.0, "max": 1.0},
  30. "debug_orders": {"type": "bool", "default": True},
  31. "use_all_available": {"type": "bool", "default": True},
  32. }
  33. STATE_SCHEMA = {
  34. "center_price": {"type": "float", "default": 0.0},
  35. "last_price": {"type": "float", "default": 0.0},
  36. "seeded": {"type": "bool", "default": False},
  37. "last_action": {"type": "string", "default": "idle"},
  38. "last_error": {"type": "string", "default": ""},
  39. "orders": {"type": "list", "default": []},
  40. "order_ids": {"type": "list", "default": []},
  41. "debug_log": {"type": "list", "default": []},
  42. "base_available": {"type": "float", "default": 0.0},
  43. "counter_available": {"type": "float", "default": 0.0},
  44. "trend_guard_active": {"type": "bool", "default": False},
  45. "regimes_updated_at": {"type": "string", "default": ""},
  46. "account_snapshot_updated_at": {"type": "string", "default": ""},
  47. }
  48. def init(self):
  49. return {
  50. "center_price": 0.0,
  51. "last_price": 0.0,
  52. "seeded": False,
  53. "last_action": "idle",
  54. "last_error": "",
  55. "orders": [],
  56. "order_ids": [],
  57. "debug_log": ["init cancel all orders"],
  58. "base_available": 0.0,
  59. "counter_available": 0.0,
  60. "trend_guard_active": False,
  61. "regimes_updated_at": "",
  62. "account_snapshot_updated_at": "",
  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. def _base_symbol(self) -> str:
  71. return (self.context.base_currency or self.context.market_symbol or "XRP").split("/")[0].upper()
  72. def _market_symbol(self) -> str:
  73. return self.context.market_symbol or f"{self._base_symbol().lower()}usd"
  74. def _mode(self) -> str:
  75. return getattr(self.context, "mode", "active") or "active"
  76. def _price(self) -> float:
  77. payload = self.context.get_price(self._base_symbol())
  78. return float(payload.get("price") or 0.0)
  79. def _regime_snapshot(self) -> dict:
  80. timeframes = ["1d", "4h", "1h", "15m"]
  81. snapshot = {}
  82. for tf in timeframes:
  83. try:
  84. snapshot[tf] = self.context.get_regime(self._base_symbol(), tf)
  85. except Exception as exc:
  86. snapshot[tf] = {"error": str(exc)}
  87. return snapshot
  88. def _refresh_regimes(self) -> None:
  89. self.state["regimes"] = self._regime_snapshot()
  90. self.state["regimes_updated_at"] = datetime.now(timezone.utc).isoformat()
  91. def _trend_guard_status(self) -> tuple[bool, str]:
  92. if not bool(self.config.get("enable_trend_guard", True)):
  93. return False, "disabled"
  94. reversal_max = float(self.config.get("trend_guard_reversal_max", 0.25) or 0.0)
  95. regimes = self.state.get("regimes") or self._regime_snapshot()
  96. d1 = (regimes.get("1d") or {}) if isinstance(regimes, dict) else {}
  97. h4 = (regimes.get("4h") or {}) if isinstance(regimes, dict) else {}
  98. d1_trend = str((d1.get("trend") or {}).get("state") or "unknown")
  99. h4_trend = str((h4.get("trend") or {}).get("state") or "unknown")
  100. d1_rev = float((d1.get("reversal") or {}).get("score") or 0.0)
  101. h4_rev = float((h4.get("reversal") or {}).get("score") or 0.0)
  102. strong_trend = d1_trend in {"bull", "bear"} and d1_trend == h4_trend
  103. weak_reversal = max(d1_rev, h4_rev) <= reversal_max
  104. active = bool(strong_trend and weak_reversal)
  105. reason = f"1d={d1_trend} 4h={h4_trend} rev={max(d1_rev, h4_rev):.3f}"
  106. return active, reason
  107. def _grid_step_pct(self) -> float:
  108. base_step = float(self.config.get("grid_step_pct", 0.012) or 0.012)
  109. tf = str(self.config.get("volatility_timeframe", "1h") or "1h")
  110. multiplier = float(self.config.get("volatility_multiplier", 0.5) or 0.0)
  111. min_step = float(self.config.get("grid_step_min_pct", 0.005) or 0.0)
  112. max_step = float(self.config.get("grid_step_max_pct", 0.03) or 1.0)
  113. try:
  114. regime = self.context.get_regime(self._base_symbol(), tf)
  115. short_regime = self.context.get_regime(self._base_symbol(), "15m")
  116. tf_atr_pct = float((regime or {}).get("volatility", {}).get("atr_percent") or 0.0)
  117. atr_pct = float((regime or {}).get("volatility", {}).get("atr_percent") or 0.0)
  118. short_atr_pct = float((short_regime or {}).get("volatility", {}).get("atr_percent") or 0.0)
  119. atr_pct = max(atr_pct, short_atr_pct)
  120. self.state["regimes"] = self._regime_snapshot()
  121. except Exception as exc:
  122. self._log(f"regime fetch failed: {exc}")
  123. tf_atr_pct = 0.0
  124. atr_pct = 0.0
  125. short_atr_pct = 0.0
  126. adaptive = (atr_pct / 100.0) * multiplier if atr_pct > 0 else base_step
  127. step = adaptive if atr_pct > 0 else base_step
  128. step = max(step, min_step)
  129. step = min(step, max_step)
  130. self.state["grid_step_pct"] = step
  131. self.state["atr_percent_tf"] = tf_atr_pct
  132. self.state["atr_percent_15m"] = short_atr_pct
  133. self.state["atr_percent"] = atr_pct
  134. return step
  135. def _available_balance(self, asset_code: str) -> float:
  136. try:
  137. info = self.context.get_account_info()
  138. except Exception as exc:
  139. self._log(f"account info failed: {exc}")
  140. return 0.0
  141. balances = info.get("balances") if isinstance(info, dict) else []
  142. if not isinstance(balances, list):
  143. return 0.0
  144. wanted = str(asset_code or "").upper()
  145. for balance in balances:
  146. if not isinstance(balance, dict):
  147. continue
  148. if str(balance.get("asset_code") or "").upper() != wanted:
  149. continue
  150. try:
  151. return float(balance.get("available") if balance.get("available") is not None else balance.get("total") or 0.0)
  152. except Exception:
  153. return 0.0
  154. return 0.0
  155. def _refresh_balance_snapshot(self) -> None:
  156. try:
  157. info = self.context.get_account_info()
  158. except Exception as exc:
  159. self._log(f"balance refresh failed: {exc}")
  160. return
  161. balances = info.get("balances") if isinstance(info, dict) else []
  162. if not isinstance(balances, list):
  163. return
  164. base = self._base_symbol()
  165. quote = self.context.counter_currency or "USD"
  166. for balance in balances:
  167. if not isinstance(balance, dict):
  168. continue
  169. asset = str(balance.get("asset_code") or "").upper()
  170. try:
  171. available = float(balance.get("available") if balance.get("available") is not None else balance.get("total") or 0.0)
  172. except Exception:
  173. continue
  174. if asset == base:
  175. self.state["base_available"] = available
  176. if asset == str(quote).upper():
  177. self.state["counter_available"] = available
  178. self.state["account_snapshot_updated_at"] = datetime.now(timezone.utc).isoformat()
  179. def _supported_levels(self, side: str, price: float, min_notional: float) -> int:
  180. if min_notional <= 0 or price <= 0:
  181. return 0
  182. safety = 0.995
  183. fee_rate = float(self.config.get("fee_rate", 0.0025) or 0.0)
  184. if side == "buy":
  185. quote = self.context.counter_currency or "USD"
  186. quote_available = self._available_balance(quote)
  187. self.state["counter_available"] = quote_available
  188. usable_notional = quote_available * safety
  189. return max(int(usable_notional / min_notional), 0)
  190. base = self._base_symbol()
  191. base_available = self._available_balance(base)
  192. self.state["base_available"] = base_available
  193. usable_notional = base_available * safety * price / (1 + fee_rate)
  194. return max(int(usable_notional / min_notional), 0)
  195. def _side_allowed(self, side: str) -> bool:
  196. selected = str(self.config.get("trade_sides", "both") or "both").strip().lower()
  197. if selected == "both":
  198. return True
  199. return selected == side
  200. def _desired_sides(self) -> set[str]:
  201. selected = str(self.config.get("trade_sides", "both") or "both").strip().lower()
  202. if selected == "both":
  203. return {"buy", "sell"}
  204. if selected in {"buy", "sell"}:
  205. return {selected}
  206. return {"buy", "sell"}
  207. def _suggest_amount(self, side: str, price: float, levels: int, min_notional: float) -> float:
  208. if levels <= 0 or price <= 0:
  209. return 0.0
  210. safety = 0.995
  211. fee_rate = float(self.config.get("fee_rate", 0.0025) or 0.0)
  212. max_notional = float(self.config.get("max_notional_per_order", 0.0) or 0.0)
  213. manual = float(self.config.get("order_size", 0.0) or 0.0)
  214. min_amount = (min_notional / price) if min_notional > 0 else 0.0
  215. if side == "buy":
  216. quote = self.context.counter_currency or "USD"
  217. quote_available = self._available_balance(quote)
  218. self.state["counter_available"] = quote_available
  219. spendable_quote = quote_available * safety
  220. amount = spendable_quote / (max(levels, 1) * price * (1 + fee_rate))
  221. else:
  222. base = self._base_symbol()
  223. base_available = self._available_balance(base)
  224. self.state["base_available"] = base_available
  225. spendable_base = (base_available * safety) / (1 + fee_rate)
  226. amount = spendable_base / max(levels, 1)
  227. amount = max(amount, min_amount * 1.05)
  228. if max_notional > 0 and price > 0:
  229. amount = min(amount, max_notional / (price * (1 + fee_rate)))
  230. if manual > 0:
  231. if manual >= min_amount:
  232. amount = min(amount, manual)
  233. else:
  234. self._log(
  235. f"manual order_size below minimum: order_size={manual:.6g} min_amount={min_amount:.6g} price={price} min_notional={min_notional}"
  236. )
  237. return max(amount, 0.0)
  238. def _place_grid(self, center: float) -> None:
  239. mode = self._mode()
  240. levels = int(self.config.get("grid_levels", 6) or 6)
  241. step = self._grid_step_pct()
  242. min_notional = float(self.context.minimum_order_value or 0.0)
  243. market = self._market_symbol()
  244. orders = []
  245. order_ids = []
  246. def _capture_order_id(result):
  247. if isinstance(result, dict):
  248. return result.get("bitstamp_order_id") or result.get("order_id") or result.get("id") or result.get("client_order_id")
  249. return None
  250. buy_levels = min(levels, self._supported_levels("buy", center, min_notional)) if (mode == "active" and self._side_allowed("buy")) else (levels if self._side_allowed("buy") else 0)
  251. sell_levels = min(levels, self._supported_levels("sell", center, min_notional)) if (mode == "active" and self._side_allowed("sell")) else (levels if self._side_allowed("sell") else 0)
  252. buy_amount = self._suggest_amount("buy", center, max(buy_levels, 1), min_notional)
  253. sell_amount = self._suggest_amount("sell", center, max(sell_levels, 1), min_notional)
  254. for i in range(1, levels + 1):
  255. buy_price = round(center * (1 - (step * i)), 8)
  256. sell_price = round(center * (1 + (step * i)), 8)
  257. if mode != "active":
  258. orders.append({"side": "buy", "price": buy_price, "amount": buy_amount, "result": {"simulated": True}})
  259. orders.append({"side": "sell", "price": sell_price, "amount": sell_amount, "result": {"simulated": True}})
  260. self._log(f"plan level {i}: buy {buy_price} amount {buy_amount:.6g} / sell {sell_price} amount {sell_amount:.6g}")
  261. continue
  262. if i > buy_levels and i > sell_levels:
  263. self._log(f"skip level {i}: no capacity on either side")
  264. continue
  265. min_size_buy = (min_notional / buy_price) if buy_price > 0 else 0.0
  266. min_size_sell = (min_notional / sell_price) if sell_price > 0 else 0.0
  267. try:
  268. if i <= buy_levels and buy_amount >= min_size_buy:
  269. buy = self.context.place_order(side="buy", order_type="limit", amount=buy_amount, price=buy_price, market=market)
  270. orders.append({"side": "buy", "price": buy_price, "amount": buy_amount, "result": buy})
  271. buy_id = _capture_order_id(buy)
  272. if buy_id is not None:
  273. order_ids.append(str(buy_id))
  274. if i <= sell_levels and sell_amount >= min_size_sell:
  275. sell = self.context.place_order(side="sell", order_type="limit", amount=sell_amount, price=sell_price, market=market)
  276. orders.append({"side": "sell", "price": sell_price, "amount": sell_amount, "result": sell})
  277. sell_id = _capture_order_id(sell)
  278. if sell_id is not None:
  279. order_ids.append(str(sell_id))
  280. self._log(f"seed level {i}: buy {buy_price} amount {buy_amount:.6g} / sell {sell_price} amount {sell_amount:.6g}")
  281. except Exception as exc: # best effort for first draft
  282. self.state["last_error"] = str(exc)
  283. self._log(f"seed level {i} failed: {exc}")
  284. continue
  285. delay = max(int(self.config.get("order_call_delay_ms", 250) or 0), 0) / 1000.0
  286. if delay > 0:
  287. time.sleep(delay)
  288. self.state["orders"] = orders
  289. self.state["order_ids"] = order_ids
  290. self.state["last_action"] = "seeded grid"
  291. def _place_side_grid(self, side: str, center: float, *, start_level: int = 1) -> None:
  292. levels = int(self.config.get("grid_levels", 6) or 6)
  293. step = self._grid_step_pct()
  294. min_notional = float(self.context.minimum_order_value or 0.0)
  295. fee_rate = float(self.config.get("fee_rate", 0.0025) or 0.0)
  296. safety = 0.995
  297. market = self._market_symbol()
  298. orders = list(self.state.get("orders") or [])
  299. order_ids = list(self.state.get("order_ids") or [])
  300. side_levels = min(levels, self._supported_levels(side, center, min_notional))
  301. amount = self._suggest_amount(side, center, max(side_levels, 1), min_notional)
  302. if side == "buy":
  303. quote = self.context.counter_currency or "USD"
  304. quote_available = self._available_balance(quote)
  305. max_affordable_amount = (quote_available * safety) / (center * (1 + fee_rate)) if center > 0 else 0.0
  306. min_amount = (min_notional / center) if center > 0 and min_notional > 0 else 0.0
  307. if max_affordable_amount < min_amount:
  308. self._log(
  309. f"skip side buy: insufficient counter balance quote={quote_available:.6g} max_affordable_amount={max_affordable_amount:.6g} min_amount={min_amount:.6g} fee_rate={fee_rate}"
  310. )
  311. return
  312. amount = min(amount, max_affordable_amount)
  313. if side_levels <= 0 and min_notional > 0 and center > 0:
  314. min_amount = min_notional / center
  315. if amount >= min_amount:
  316. side_levels = 1
  317. self._log(f"side {side} restored to 1 level because amount clears minimum: amount={amount:.6g} min_amount={min_amount:.6g}")
  318. self._log(
  319. f"prepare side {side}: market={market} center={center} levels={side_levels} amount={amount:.6g} min_notional={min_notional} existing_ids={order_ids}"
  320. )
  321. for i in range(start_level, levels + 1):
  322. price = round(center * (1 - (step * i)) if side == "buy" else center * (1 + (step * i)), 8)
  323. min_size = (min_notional / price) if price > 0 else 0.0
  324. if i > side_levels or amount < min_size:
  325. self._log(
  326. f"skip side {side} level {i}: amount={amount:.6g} below min_size={min_size:.6g} min_notional={min_notional} price={price}"
  327. )
  328. continue
  329. try:
  330. self._log(f"place side {side} level {i}: price={price} amount={amount:.6g}")
  331. result = self.context.place_order(side=side, order_type="limit", amount=amount, price=price, market=market)
  332. status = None
  333. order_id = None
  334. if isinstance(result, dict):
  335. status = result.get("status")
  336. order_id = result.get("bitstamp_order_id") or result.get("order_id") or result.get("id") or result.get("client_order_id")
  337. self._log(f"place side {side} level {i} result status={status} order_id={order_id} raw={result}")
  338. orders.append({"side": side, "price": price, "amount": amount, "result": result})
  339. if order_id is not None:
  340. order_ids.append(str(order_id))
  341. self._log(f"seed side {side} level {i}: {price} amount {amount:.6g}")
  342. except Exception as exc:
  343. self.state["last_error"] = str(exc)
  344. self._log(f"seed side {side} level {i} failed: {exc}")
  345. continue
  346. delay = max(int(self.config.get("order_call_delay_ms", 250) or 0), 0) / 1000.0
  347. if delay > 0:
  348. time.sleep(delay)
  349. self.state["orders"] = orders
  350. self.state["order_ids"] = order_ids
  351. self._log(f"side {side} placement complete: tracked_ids={order_ids}")
  352. def _top_up_missing_levels(self, center: float, live_orders: list[dict]) -> None:
  353. target_levels = int(self.config.get("grid_levels", 6) or 6)
  354. if target_levels <= 0:
  355. return
  356. for side in ("buy", "sell"):
  357. count = 0
  358. for order in live_orders:
  359. if not isinstance(order, dict):
  360. continue
  361. if str(order.get("side") or "").lower() == side:
  362. count += 1
  363. if 0 < count < target_levels:
  364. self._log(f"top up side {side}: have {count}, want {target_levels}")
  365. self._place_side_grid(side, center, start_level=count + 1)
  366. def _cancel_obsolete_side_orders(self, open_orders: list[dict], desired_sides: set[str]) -> list[str]:
  367. removed: list[str] = []
  368. for order in open_orders:
  369. if not isinstance(order, dict):
  370. continue
  371. side = str(order.get("side") or "").lower()
  372. order_id = str(order.get("bitstamp_order_id") or order.get("order_id") or order.get("id") or order.get("client_order_id") or "")
  373. if not order_id or side in desired_sides:
  374. continue
  375. try:
  376. self.context.cancel_order(order_id)
  377. removed.append(order_id)
  378. self._log(f"cancelled obsolete {side} order {order_id}")
  379. except Exception as exc:
  380. self.state["last_error"] = str(exc)
  381. self._log(f"cancel obsolete {side} order {order_id} failed: {exc}")
  382. return removed
  383. def _sync_open_orders_state(self) -> list[dict]:
  384. try:
  385. open_orders = self.context.get_open_orders()
  386. except Exception as exc:
  387. self.state["last_error"] = str(exc)
  388. self._log(f"open orders sync failed: {exc}")
  389. return []
  390. if not isinstance(open_orders, list):
  391. open_orders = []
  392. live_orders = [order for order in open_orders if isinstance(order, dict)]
  393. live_ids = [str(order.get("bitstamp_order_id") or order.get("order_id") or order.get("id") or order.get("client_order_id") or "") for order in live_orders]
  394. live_ids = [oid for oid in live_ids if oid]
  395. live_sides = [str(order.get("side") or "").lower() for order in live_orders]
  396. self.state["orders"] = live_orders
  397. self.state["order_ids"] = live_ids
  398. self.state["open_order_count"] = len(live_ids)
  399. self._log(f"sync live orders: count={len(live_ids)} sides={live_sides} ids={live_ids}")
  400. return live_orders
  401. def _cancel_orders(self, order_ids) -> None:
  402. for order_id in order_ids or []:
  403. self._log(f"dropping stale order {order_id} from state")
  404. def on_tick(self, tick):
  405. self._refresh_balance_snapshot()
  406. price = self._price()
  407. self.state["last_price"] = price
  408. self.state["last_error"] = ""
  409. self._refresh_regimes()
  410. try:
  411. live_orders = self._sync_open_orders_state()
  412. live_ids = list(self.state.get("order_ids") or [])
  413. open_order_count = len(live_ids)
  414. expected_ids = [str(oid) for oid in (self.state.get("order_ids") or []) if oid]
  415. stale_ids = []
  416. missing_ids = []
  417. except Exception as exc:
  418. open_order_count = -1
  419. live_orders = []
  420. live_ids = []
  421. expected_ids = []
  422. stale_ids = []
  423. missing_ids = []
  424. self.state["last_error"] = str(exc)
  425. self._log(f"open orders check failed: {exc}")
  426. # Workaround: after a reset, trust the fresh strategy state first.
  427. # This prevents stale exec-mcp records from blocking the next clean test.
  428. if not (self.state.get("order_ids") or []):
  429. live_orders = []
  430. live_ids = []
  431. open_order_count = 0
  432. expected_ids = []
  433. stale_ids = []
  434. missing_ids = []
  435. self.state["open_order_count"] = open_order_count
  436. desired_sides = self._desired_sides()
  437. mode = self._mode()
  438. guard_active, guard_reason = self._trend_guard_status()
  439. self.state["trend_guard_active"] = guard_active
  440. if mode == "active" and guard_active:
  441. self._log(f"trend guard active: {guard_reason}")
  442. try:
  443. self.context.cancel_all_orders()
  444. except Exception as exc:
  445. self.state["last_error"] = str(exc)
  446. self._log(f"trend guard cancel failed: {exc}")
  447. self.state["last_action"] = "trend_guard"
  448. return {"action": "guard", "price": price, "reason": guard_reason}
  449. if mode != "active":
  450. if not self.state.get("seeded") or not self.state.get("center_price"):
  451. self.state["center_price"] = price
  452. self._place_grid(price)
  453. self.state["seeded"] = True
  454. self._log(f"planned grid at {price}")
  455. return {"action": "plan", "price": price}
  456. center = float(self.state.get("center_price") or price)
  457. recenter_pct = float(self.config.get("recenter_pct", 0.05) or 0.05)
  458. deviation = abs(price - center) / center if center else 0.0
  459. if deviation >= recenter_pct:
  460. self.state["center_price"] = price
  461. self._place_grid(price)
  462. self._log(f"planned recenter to {price}")
  463. return {"action": "plan", "price": price, "deviation": deviation}
  464. self.state["last_action"] = "observe monitor"
  465. self._log(f"observe at {price} dev {deviation:.4f}")
  466. return {"action": "observe", "price": price, "deviation": deviation}
  467. if stale_ids:
  468. self._log(f"stale live orders: {stale_ids}")
  469. self._cancel_orders(stale_ids)
  470. live_ids = [oid for oid in live_ids if oid not in stale_ids]
  471. if missing_ids:
  472. self._log(f"missing tracked orders: {missing_ids}")
  473. self.state["order_ids"] = live_ids
  474. cancelled_obsolete = self._cancel_obsolete_side_orders(live_orders, desired_sides)
  475. if cancelled_obsolete:
  476. live_orders = self._sync_open_orders_state()
  477. live_ids = list(self.state.get("order_ids") or [])
  478. open_order_count = len(live_ids)
  479. if desired_sides != {"buy", "sell"}:
  480. current_sides = {str(order.get("side") or "").lower() for order in live_orders if isinstance(order, dict)}
  481. missing_side = next((side for side in desired_sides if side not in current_sides), None)
  482. if missing_side and self.state.get("center_price"):
  483. self._log(f"adding missing {missing_side} side after trade_sides change, live_sides={sorted(current_sides)} live_ids={live_ids}")
  484. self._place_side_grid(missing_side, float(self.state.get("center_price") or price))
  485. live_orders = self._sync_open_orders_state()
  486. self._log(f"post-add sync: open_order_count={self.state.get('open_order_count', 0)} live_ids={self.state.get('order_ids') or []}")
  487. self.state["last_action"] = f"added {missing_side} side"
  488. return {"action": "add_side", "price": price, "side": missing_side}
  489. if desired_sides == {"buy", "sell"}:
  490. current_sides = {str(order.get("side") or "").lower() for order in live_orders if isinstance(order, dict)}
  491. missing_sides = [side for side in ("buy", "sell") if side not in current_sides]
  492. reconciled_sides: list[str] = []
  493. if missing_sides and self.state.get("center_price"):
  494. for side in missing_sides:
  495. self._log(f"adding missing {side} side after trade_sides change, live_sides={sorted(current_sides)} live_ids={live_ids}")
  496. self._place_side_grid(side, float(self.state.get("center_price") or price))
  497. reconciled_sides.append(side)
  498. live_orders = self._sync_open_orders_state()
  499. self._log(f"post-add sync: open_order_count={self.state.get('open_order_count', 0)} live_ids={self.state.get('order_ids') or []}")
  500. if live_orders and self.state.get("center_price"):
  501. self._top_up_missing_levels(float(self.state.get("center_price") or price), live_orders)
  502. live_orders = self._sync_open_orders_state()
  503. if reconciled_sides:
  504. self.state["last_action"] = f"reconciled {','.join(reconciled_sides)}"
  505. return {"action": "reconcile", "price": price, "side": ",".join(reconciled_sides)}
  506. if not self.state.get("seeded") or not self.state.get("center_price"):
  507. self.state["center_price"] = price
  508. self._place_grid(price)
  509. live_orders = self._sync_open_orders_state()
  510. self.state["seeded"] = True
  511. mode = self._mode()
  512. self._log(f"{'seeded' if mode == 'active' else 'planned'} grid at {price}")
  513. return {"action": "seed" if mode == "active" else "plan", "price": price}
  514. if open_order_count == 0 or (expected_ids and not set(expected_ids).intersection(set(live_ids))):
  515. self._log("no open orders, reseeding grid")
  516. self.state["center_price"] = price
  517. self._place_grid(price)
  518. live_orders = self._sync_open_orders_state()
  519. mode = self._mode()
  520. self.state["last_action"] = "reseeded" if mode == "active" else f"{mode} monitor"
  521. return {"action": "reseed" if mode == "active" else "plan", "price": price}
  522. center = float(self.state.get("center_price") or price)
  523. recenter_pct = float(self.config.get("recenter_pct", 0.05) or 0.05)
  524. deviation = abs(price - center) / center if center else 0.0
  525. if deviation >= recenter_pct:
  526. try:
  527. self.context.cancel_all_orders()
  528. except Exception as exc:
  529. self.state["last_error"] = str(exc)
  530. self.state["center_price"] = price
  531. self._place_grid(price)
  532. live_orders = self._sync_open_orders_state()
  533. mode = self._mode()
  534. self.state["last_action"] = "recentered" if mode == "active" else f"{mode} monitor"
  535. self._log(f"recentered grid to {price}")
  536. return {"action": "recenter" if mode == "active" else "plan", "price": price, "deviation": deviation}
  537. mode = self._mode()
  538. self.state["last_action"] = "hold" if mode == "active" else f"{mode} monitor"
  539. self._log(f"hold at {price} dev {deviation:.4f}")
  540. return {"action": "hold" if mode == "active" else "plan", "price": price, "deviation": deviation}
  541. def render(self):
  542. # Refresh the market-derived display values on render so the dashboard
  543. # reflects the same inputs the strategy would use on the next tick.
  544. live_step_pct = float(self.state.get("grid_step_pct") or 0.0)
  545. live_atr_pct = float(self.state.get("atr_percent") or 0.0)
  546. try:
  547. self._refresh_balance_snapshot()
  548. live_step_pct = self._grid_step_pct()
  549. live_atr_pct = float(self.state.get("atr_percent") or live_atr_pct)
  550. except Exception as exc:
  551. self._log(f"render refresh failed: {exc}")
  552. return {
  553. "widgets": [
  554. {"type": "metric", "label": "market", "value": self._market_symbol()},
  555. {"type": "metric", "label": "center", "value": round(float(self.state.get("center_price") or 0.0), 6)},
  556. {"type": "metric", "label": "last price", "value": round(float(self.state.get("last_price") or 0.0), 6)},
  557. {"type": "metric", "label": "state", "value": self.state.get("last_action", "idle")},
  558. {"type": "metric", "label": "orders", "value": len(self.state.get("orders") or [])},
  559. {"type": "metric", "label": "open orders", "value": self.state.get("open_order_count", 0)},
  560. {"type": "metric", "label": f"ATR({self.config.get('volatility_timeframe', '1h')}) %", "value": round(live_atr_pct, 4)},
  561. {"type": "metric", "label": "grid step %", "value": round(live_step_pct * 100.0, 4)},
  562. {"type": "metric", "label": "1d", "value": ((self.state.get('regimes') or {}).get('1d') or {}).get('trend', {}).get('state', 'n/a')},
  563. {"type": "metric", "label": "4h", "value": ((self.state.get('regimes') or {}).get('4h') or {}).get('trend', {}).get('state', 'n/a')},
  564. {"type": "metric", "label": "1h", "value": ((self.state.get('regimes') or {}).get('1h') or {}).get('trend', {}).get('state', 'n/a')},
  565. {"type": "metric", "label": "15m", "value": ((self.state.get('regimes') or {}).get('15m') or {}).get('trend', {}).get('state', 'n/a')},
  566. {"type": "metric", "label": f"{self._base_symbol()} avail", "value": round(float(self.state.get("base_available") or 0.0), 8)},
  567. {"type": "metric", "label": f"{self.context.counter_currency or 'USD'} avail", "value": round(float(self.state.get("counter_available") or 0.0), 8)},
  568. *([
  569. {"type": "metric", "label": "trend guard active", "value": "on"},
  570. {"type": "text", "label": "trend guard reason", "value": "higher-timeframe trend conflict"},
  571. ] if self.state.get("trend_guard_active") else []),
  572. {"type": "text", "label": "error", "value": self.state.get("last_error", "") or "none"},
  573. {"type": "log", "label": "debug log", "lines": self.state.get("debug_log") or []},
  574. ]
  575. }